S Price: $0.06755 (+1.57%)
Gas: 55 Gwei

Contract

0x84ff7a1e60Ea5f5C5a3a1FecDcB2494e9728812b

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

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
SiloLeverageStrategy

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 {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {CommonLib} from "../core/libs/CommonLib.sol";
import {ConstantsLib} from "../core/libs/ConstantsLib.sol";
import {StrategyBase} from "./base/StrategyBase.sol";
import {LeverageLendingBase} from "./base/LeverageLendingBase.sol";
import {StrategyIdLib} from "./libs/StrategyIdLib.sol";
import {StrategyLib} from "./libs/StrategyLib.sol";
import {SiloLib} from "./libs/SiloLib.sol";
import {IStrategy} from "../interfaces/IStrategy.sol";
import {IControllable} from "../interfaces/IControllable.sol";
import {IFactory} from "../interfaces/IFactory.sol";
import {IPlatform} from "../interfaces/IPlatform.sol";
import {IPriceReader} from "../interfaces/IPriceReader.sol";
import {ILeverageLendingStrategy} from "../interfaces/ILeverageLendingStrategy.sol";
import {ISilo} from "../integrations/silo/ISilo.sol";
import {ISiloConfig} from "../integrations/silo/ISiloConfig.sol";
import {ISiloLens} from "../integrations/silo/ISiloLens.sol";
import {IVaultMainV3} from "../integrations/balancerv3/IVaultMainV3.sol";
import {IFlashLoanRecipient} from "../integrations/balancer/IFlashLoanRecipient.sol";
import {IUniswapV3FlashCallback} from "../integrations/uniswapv3/IUniswapV3FlashCallback.sol";
import {IBalancerV3FlashCallback} from "../integrations/balancerv3/IBalancerV3FlashCallback.sol";
import {IAlgebraFlashCallback} from "../integrations/algebrav4/callback/IAlgebraFlashCallback.sol";

/// @title Silo V2 leverage strategy
/// Changelog:
///   2.1.8: StrategyBase 2.6.4
///   2.1.7: StrategyBase 2.6.3
///   2.1.6: StrategyBase 2.6.2
///   2.1.5: StrategyBase 2.6.1
///   2.1.4: StrategyBase 2.6.0
///   2.1.3: StrategyBase 2.5.1
///   2.1.2: Add maxDeploy, use StrategyBase 2.5.0 - #330
///   2.1.1: Use StrategyBase 2.4.0 - add default poolTvl, maxWithdrawAssets
///   2.1.0: Use StrategyBase 2.3.0 - add fuseMode
///   2.0.0:
///     * feat: use BeetsV3 OR UniswapV3-like DeX free flash loans #257, use universalAddress1 as flashLoanVault for borrow asset
///     * Change logic of withdraw: add deposit at the end and possibility to withdraw through increasing LTV
///     * use LeverageLendingBase 1.2.2
///   1.1.3: Move depositAssets impl to SiloLib to reduce size, use LeverageLendingBase 1.1.2, #269
///   1.1.2: realApr bugfix
///   1.1.1: use LeverageLendingBase 1.1.1
///   1.1.0: use LeverageLendingBase 1.1.0
/// @author Alien Deployer (https://github.com/a17)
/// @author dvpublic (https://github.com/dvpublic)
contract SiloLeverageStrategy is
    LeverageLendingBase,
    IFlashLoanRecipient,
    IUniswapV3FlashCallback,
    IBalancerV3FlashCallback,
    IAlgebraFlashCallback
{
    using SafeERC20 for IERC20;

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

    /// @inheritdoc IControllable
    string public constant VERSION = "2.1.8";

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

    /// @inheritdoc IStrategy
    function initialize(address[] memory addresses, uint[] memory nums, int24[] memory ticks) public initializer {
        if (addresses.length != 6 || nums.length != 0 || ticks.length != 0) {
            revert IControllable.IncorrectInitParams();
        }

        LeverageLendingStrategyBaseInitParams memory params;
        params.platform = addresses[0];
        params.vault = addresses[1];
        params.collateralAsset = IERC4626(addresses[2]).asset();
        params.borrowAsset = IERC4626(addresses[3]).asset();
        params.lendingVault = addresses[2];
        params.borrowingVault = addresses[3];
        params.flashLoanVault = addresses[4];
        params.helper = addresses[5];
        params.targetLeveragePercent = 87_00;
        __LeverageLendingBase_init(params);

        IERC20(params.collateralAsset).forceApprove(params.lendingVault, type(uint).max);
        IERC20(params.borrowAsset).forceApprove(params.borrowingVault, type(uint).max);
        address swapper = IPlatform(params.platform).swapper();
        IERC20(params.collateralAsset).forceApprove(swapper, type(uint).max);
        IERC20(params.borrowAsset).forceApprove(swapper, type(uint).max);
    }

    //region ---------------- Callbacks (flash loan)
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CALLBACKS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc IFlashLoanRecipient
    function receiveFlashLoan(
        address[] memory tokens,
        uint[] memory amounts,
        uint[] memory feeAmounts,
        bytes memory /*userData*/
    ) external {
        // Flash loan is performed upon deposit and withdrawal
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        SiloLib.receiveFlashLoan(platform(), $, tokens[0], amounts[0], feeAmounts[0]);
    }

    /// @inheritdoc IBalancerV3FlashCallback
    function receiveFlashLoanV3(address token, uint amount, bytes memory /*userData*/ ) external {
        // sender is vault, it's checked inside receiveFlashLoan
        // we can use msg.sender below but $.flashLoanVault looks more safe
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        IVaultMainV3 vault = IVaultMainV3(payable($.flashLoanVault));

        // ensure that the vault has available amount
        require(IERC20(token).balanceOf(address(vault)) >= amount, IControllable.InsufficientBalance());

        // receive flash loan from the vault
        vault.sendTo(token, address(this), amount);

        // Flash loan is performed upon deposit and withdrawal
        SiloLib.receiveFlashLoan(platform(), $, token, amount, 0); // assume that flash loan is free, fee is 0

        // return flash loan back to the vault
        // assume that the amount was transferred back to the vault inside receiveFlashLoan()
        // we need only to register this transferring
        vault.settle(token, amount);
    }

    /// @inheritdoc IUniswapV3FlashCallback
    function uniswapV3FlashCallback(uint fee0, uint fee1, bytes calldata userData) external {
        // sender is the pool, it's checked inside receiveFlashLoan
        _uniswapV3FlashCallback(fee0, fee1, userData);
    }

    function algebraFlashCallback(uint fee0, uint fee1, bytes calldata userData) external {
        // sender is the pool, it's checked inside receiveFlashLoan
        _uniswapV3FlashCallback(fee0, fee1, userData);
    }

    //endregion ---------------- Callbacks (flash loan)

    //region ---------------- View
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc IStrategy
    function isHardWorkOnDepositAllowed() external pure returns (bool) {
        return true;
    }

    /// @inheritdoc IStrategy
    function strategyLogicId() public pure override returns (string memory) {
        return StrategyIdLib.SILO_LEVERAGE;
    }

    /// @inheritdoc IStrategy
    function initVariants(address platform_)
        public
        view
        returns (string[] memory variants, address[] memory addresses, uint[] memory nums, int24[] memory ticks)
    {
        IFactory.StrategyAvailableInitParams memory params =
            IFactory(IPlatform(platform_).factory()).strategyAvailableInitParams(keccak256(bytes(strategyLogicId())));
        uint len = params.initNums[0];
        variants = new string[](len);
        addresses = new address[](len * 4);
        nums = new uint[](0);
        ticks = new int24[](0);
        for (uint i; i < len; ++i) {
            address collateralAsset = IERC4626(params.initAddresses[i * 2]).asset();
            address borrowAsset = IERC4626(params.initAddresses[i * 2 + 1]).asset();
            variants[i] = _generateDescription(params.initAddresses[i * 2], collateralAsset, borrowAsset);
            addresses[i * 2] = params.initAddresses[i * 2];
            addresses[i * 2 + 1] = params.initAddresses[i * 2 + 1];
            addresses[i * 2 + 2] = params.initAddresses[i * 2 + 2];
            addresses[i * 2 + 3] = params.initAddresses[i * 2 + 3];
        }
    }

    /// @inheritdoc IStrategy
    function description() external view returns (string memory) {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        return _generateDescription($.lendingVault, $.collateralAsset, $.borrowAsset);
    }

    /// @inheritdoc IStrategy
    function getSpecificName() external view override returns (string memory, bool) {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        address lendingVault = $.lendingVault;
        uint siloId = ISiloConfig(ISilo(lendingVault).config()).SILO_ID();
        string memory borrowAssetSymbol = IERC20Metadata($.borrowAsset).symbol();
        (,, uint targetLeverage) = SiloLib.getLtvData(lendingVault, $.targetLeveragePercent);
        return (
            string.concat(CommonLib.u2s(siloId), " ", borrowAssetSymbol, " ", _formatLeverageShort(targetLeverage)),
            false
        );
    }

    /// @inheritdoc ILeverageLendingStrategy
    function realTvl() public view returns (uint tvl, bool trusted) {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        return SiloLib.realTvl(platform(), $);
    }

    function _realSharePrice() internal view override returns (uint sharePrice, bool trusted) {
        uint _realTvl;
        (_realTvl, trusted) = realTvl();
        uint totalSupply = IERC20(vault()).totalSupply();
        if (totalSupply != 0) {
            sharePrice = _realTvl * 1e18 / totalSupply;
        }
    }

    /// @inheritdoc ILeverageLendingStrategy
    function health()
        public
        view
        returns (
            uint ltv,
            uint maxLtv,
            uint leverage,
            uint collateralAmount,
            uint debtAmount,
            uint targetLeveragePercent
        )
    {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        return SiloLib.health(platform(), $);
    }

    /// @inheritdoc ILeverageLendingStrategy
    function getSupplyAndBorrowAprs() external view returns (uint supplyApr, uint borrowApr) {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        return _getDepositAndBorrowAprs($.helper, $.lendingVault, $.borrowingVault);
    }
    //endregion ---------------- View

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   LEVERAGE LENDING BASE                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _rebalanceDebt(uint newLtv) internal override returns (uint resultLtv) {
        return SiloLib.rebalanceDebt(platform(), newLtv, _getLeverageLendingBaseStorage());
    }

    //region ---------------- Strategy base
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       STRATEGY BASE                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc StrategyBase
    function _assetsAmounts() internal view override returns (address[] memory assets_, uint[] memory amounts_) {
        assets_ = assets();
        amounts_ = new uint[](1);
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        amounts_[0] = SiloLib.totalCollateral($.lendingVault);
    }

    /// @inheritdoc StrategyBase
    function _claimRevenue()
        internal
        override
        returns (
            address[] memory __assets,
            uint[] memory __amounts,
            address[] memory __rewardAssets,
            uint[] memory __rewardAmounts
        )
    {
        __assets = assets();
        __rewardAssets = new address[](0);
        __rewardAmounts = new uint[](0);
        __amounts = new uint[](1);

        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        LeverageLendingAddresses memory v = SiloLib.getLeverageLendingAddresses($);
        StrategyBaseStorage storage $base = _getStrategyBaseStorage();

        uint totalWas = $base.total;

        ISilo(v.lendingVault).accrueInterest();
        ISilo(v.borrowingVault).accrueInterest();

        uint totalNow = StrategyLib.balance(v.collateralAsset) + SiloLib.calcTotal(v);
        if (totalNow > totalWas) {
            __amounts[0] = totalNow - totalWas;
        }
        $base.total = totalNow;

        {
            int earned = int(totalNow) - int(totalWas);
            (uint _realTvl,) = realTvl();
            uint duration = block.timestamp - $base.lastHardWork;
            IPriceReader priceReader = IPriceReader(IPlatform(platform()).priceReader());
            (uint collateralPrice,) = priceReader.getPrice(v.collateralAsset);
            int realEarned = earned * int(collateralPrice) / int(10 ** IERC20Metadata(v.collateralAsset).decimals());
            int realApr = StrategyLib.computeAprInt(_realTvl, realEarned, duration);
            (uint depositApr, uint borrowApr) = _getDepositAndBorrowAprs($.helper, v.lendingVault, v.borrowingVault);
            (uint sharePrice,) = _realSharePrice();
            emit LeverageLendingHardWork(realApr, earned, _realTvl, duration, sharePrice, depositApr, borrowApr);
        }

        (uint ltv,, uint leverage,,,) = health();
        emit LeverageLendingHealth(ltv, leverage);
    }

    /// @inheritdoc StrategyBase
    function _previewDepositAssets(uint[] memory amountsMax)
        internal
        pure
        override(StrategyBase)
        returns (uint[] memory amountsConsumed, uint value)
    {
        amountsConsumed = new uint[](1);
        amountsConsumed[0] = amountsMax[0];
        value = amountsConsumed[0];
    }

    /// @inheritdoc StrategyBase
    function _depositAssets(uint[] memory amounts, bool /*claimRevenue*/ ) internal override returns (uint value) {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        StrategyBaseStorage storage $base = _getStrategyBaseStorage();

        return SiloLib.depositAssets($, $base, assets(), amounts);
    }

    /// @inheritdoc StrategyBase
    function _withdrawAssets(uint value, address receiver) internal override returns (uint[] memory amountsOut) {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        StrategyBaseStorage storage $base = _getStrategyBaseStorage();
        return SiloLib.withdrawAssets(platform(), $, $base, value, receiver);
    }
    //endregion ---------------- Strategy base

    //region ---------------- Internal logic
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       INTERNAL LOGIC                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _generateDescription(
        address lendingVault,
        address collateralAsset,
        address borrowAsset
    ) internal view returns (string memory) {
        uint siloId = ISiloConfig(ISilo(lendingVault).config()).SILO_ID();
        return string.concat(
            "Supply ",
            IERC20Metadata(collateralAsset).symbol(),
            " and borrow ",
            IERC20Metadata(borrowAsset).symbol(),
            " on Silo V2 market ",
            CommonLib.u2s(siloId),
            " with leverage looping"
        );
    }

    function _formatLeverageShort(uint amount) internal pure returns (string memory) {
        uint intAmount = amount / 100_00;
        uint decimalAmount = (amount - intAmount * 100_00) / 10_00;
        return string.concat("x", CommonLib.u2s(intAmount), ".", CommonLib.u2s(decimalAmount));
    }

    function _getDepositAndBorrowAprs(
        address lens,
        address lendingVault,
        address debtVault
    ) internal view returns (uint depositApr, uint borrowApr) {
        depositApr = ISiloLens(lens).getDepositAPR(lendingVault) * ConstantsLib.DENOMINATOR / 1e18;
        borrowApr = ISiloLens(lens).getBorrowAPR(debtVault) * ConstantsLib.DENOMINATOR / 1e18;
    }

    function _uniswapV3FlashCallback(uint fee0, uint fee1, bytes calldata userData) internal {
        // sender is the pool, it's checked inside receiveFlashLoan
        (address token, uint amount, bool isToken0) = abi.decode(userData, (address, uint, bool));

        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        SiloLib.receiveFlashLoan(platform(), $, token, amount, isToken0 ? fee0 : fee1);
    }

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

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 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.4.0) (interfaces/IERC4626.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface of the ERC-4626 "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 redemption 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.23;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {ConstantsLib} from "./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)));
    }
}

File 7 of 56 : 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;
}

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

import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Controllable, IControllable} from "../../core/base/Controllable.sol";
import {StrategyLib} from "../libs/StrategyLib.sol";
import {IStrategy} from "../../interfaces/IStrategy.sol";
import {IVault} from "../../interfaces/IVault.sol";

/// @dev Base universal strategy
/// Changelog:
///   2.6.4: virtual revenue fix
///   2.6.3: virtual revenue fix
///   2.6.2: virtual revenue fix
///   2.6.1: virtual revenue fix
///   2.6.0: protocols, setSpecific
///   2.5.1: add maxWithdrawAssets(uint) - #360
///   2.5.0: add maxDepositAssets - #330
///   2.4.0: add poolTvl, maxWithdrawAssets - #326
///   2.3.0: add fuseMode - #305
///   2.2.0: extractFees use RevenueRouter
///   2.1.3: call hardWorkMintFeeCallback always
///   2.1.2: call hardWorkMintFeeCallback only on positive amounts
///   2.1.1: extractFees fixed
///   2.1.0: customPriceImpactTolerance
///   2.0.0: previewDepositAssetsWrite; use platform.getCustomVaultFee
///   1.1.0: autoCompoundingByUnderlyingProtocol(), virtual total()
/// @author Alien Deployer (https://github.com/a17)
/// @author JodsMigel (https://github.com/JodsMigel)
abstract contract StrategyBase is Controllable, IStrategy {
    using SafeERC20 for IERC20;

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

    /// @dev Version of StrategyBase implementation
    string public constant VERSION_STRATEGY_BASE = "2.6.4";

    // keccak256(abi.encode(uint256(keccak256("erc7201:stability.StrategyBase")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 private constant STRATEGYBASE_STORAGE_LOCATION =
        0xb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba00;

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

    //slither-disable-next-line naming-convention
    function __StrategyBase_init(
        address platform_,
        string memory id_,
        address vault_,
        address[] memory assets_,
        address underlying_,
        uint exchangeAssetIndex_
    ) internal onlyInitializing {
        __Controllable_init(platform_);
        StrategyBaseStorage storage $ = _getStrategyBaseStorage();
        ($._id, $.vault, $._assets, $._underlying, $._exchangeAssetIndex) =
            (id_, vault_, assets_, underlying_, exchangeAssetIndex_);
    }

    //region -------------------- Restricted actions
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      RESTRICTED ACTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    modifier onlyVault() {
        _requireVault();
        _;
    }

    /// @inheritdoc IStrategy
    function depositAssets(uint[] memory amounts) external override onlyVault returns (uint value) {
        StrategyBaseStorage storage $ = _getStrategyBaseStorage();
        if ($.lastHardWork == 0) {
            $.lastHardWork = block.timestamp;
        }
        _beforeDeposit();
        return _depositAssets(amounts, true);
    }

    /// @inheritdoc IStrategy
    function withdrawAssets(
        address[] memory assets_,
        uint value,
        address receiver
    ) external virtual onlyVault returns (uint[] memory amountsOut) {
        _beforeWithdraw();
        return _withdrawAssets(assets_, value, receiver);
    }

    function depositUnderlying(uint amount)
        external
        virtual
        override
        onlyVault
        returns (uint[] memory amountsConsumed)
    {
        _beforeDeposit();
        return _depositUnderlying(amount);
    }

    function withdrawUnderlying(uint amount, address receiver) external virtual override onlyVault {
        _beforeWithdraw();
        _withdrawUnderlying(amount, receiver);
    }

    /// @inheritdoc IStrategy
    function transferAssets(
        uint amount,
        uint total_,
        address receiver
    ) external onlyVault returns (uint[] memory amountsOut) {
        _beforeTransferAssets();
        //slither-disable-next-line unused-return
        return StrategyLib.transferAssets(_getStrategyBaseStorage(), amount, total_, receiver);
    }

    /// @inheritdoc IStrategy
    function doHardWork() external onlyVault {
        _beforeDoHardWork();
        StrategyBaseStorage storage $ = _getStrategyBaseStorage();
        address _vault = $.vault;
        //slither-disable-next-line unused-return
        (uint tvl,) = IVault(_vault).tvl();
        if (tvl > 0) {
            address _platform = platform();
            uint exchangeAssetIndex = $._exchangeAssetIndex;

            (
                address[] memory __assets,
                uint[] memory __amounts,
                address[] memory __rewardAssets,
                uint[] memory __rewardAmounts
            ) = _claimRevenue();

            //slither-disable-next-line uninitialized-local
            uint totalBefore;
            if (!autoCompoundingByUnderlyingProtocol()) {
                __amounts[
                    exchangeAssetIndex
                ] += _liquidateRewards(__assets[exchangeAssetIndex], __rewardAssets, __rewardAmounts);

                uint[] memory amountsRemaining = StrategyLib.extractFees(_platform, _vault, __assets, __amounts);

                bool needCompound = _processRevenue(__assets, amountsRemaining);

                totalBefore = $.total;

                if (needCompound) {
                    _compound();
                }
            } else {
                // maybe this is not final logic
                // vault shares as fees can be used not only for autoCompoundingByUnderlyingProtocol strategies,
                // but for many strategies linked to CVault if this feature will be implemented

                (, uint[] memory __assetsAmounts) = assetsAmounts();
                uint[] memory virtualRevenueAmounts = new uint[](__assets.length);
                virtualRevenueAmounts[0] = __assetsAmounts[0] * (block.timestamp - $.lastHardWork) / 300 days;
                IVault(_vault).hardWorkMintFeeCallback(__assets, virtualRevenueAmounts);
                // call empty method only for coverage or them can be overriden
                _liquidateRewards(__assets[0], __rewardAssets, __rewardAmounts);
                _processRevenue(__assets, __amounts);
                _compound();
            }

            StrategyLib.emitApr($, _platform, __assets, __amounts, tvl, totalBefore);
        }
    }

    /// @inheritdoc IStrategy
    function emergencyStopInvesting() external onlyGovernanceOrMultisig {
        // slither-disable-next-line unused-return
        _withdrawAssets(total(), address(this));

        // Activate fuse mode. In the fuse mode all assets are transferred
        // from the underlying pool to the strategy balance, no deposits are allowed after that.
        _getStrategyBaseStorage().fuseOn = uint(IStrategy.FuseMode.FUSE_ON_1);
    }

    /// @inheritdoc IStrategy
    function setCustomPriceImpactTolerance(uint priceImpactTolerance) external onlyOperator {
        StrategyBaseStorage storage $ = _getStrategyBaseStorage();
        $.customPriceImpactTolerance = priceImpactTolerance;
    }

    /// @inheritdoc IStrategy
    function setProtocols(string[] memory protocols_) external onlyOperator {
        StrategyBaseStorage storage $ = _getStrategyBaseStorage();
        $.protocols = protocols_;
        emit StrategyProtocols(protocols_);
    }

    /// @inheritdoc IStrategy
    function setSpecificName(string memory specific) external onlyOperator {
        StrategyBaseStorage storage $ = _getStrategyBaseStorage();
        $.specific = specific;
        emit SpecificName(specific);
    }

    //endregion -------------------- Restricted actions

    //region -------------------- View functions
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(Controllable, IERC165) returns (bool) {
        return interfaceId == type(IStrategy).interfaceId || super.supportsInterface(interfaceId);
    }

    function strategyLogicId() public view virtual returns (string memory);

    /// @inheritdoc IStrategy
    function assets() public view virtual returns (address[] memory) {
        return _getStrategyBaseStorage()._assets;
    }

    /// @inheritdoc IStrategy
    function underlying() public view override returns (address) {
        return _getStrategyBaseStorage()._underlying;
    }

    /// @inheritdoc IStrategy
    function vault() public view override returns (address) {
        return _getStrategyBaseStorage().vault;
    }

    /// @inheritdoc IStrategy
    function total() public view virtual override returns (uint) {
        return _getStrategyBaseStorage().total;
    }

    /// @inheritdoc IStrategy
    function lastHardWork() public view override returns (uint) {
        return _getStrategyBaseStorage().lastHardWork;
    }

    /// @inheritdoc IStrategy
    function lastApr() public view override returns (uint) {
        return _getStrategyBaseStorage().lastApr;
    }

    /// @inheritdoc IStrategy
    function lastAprCompound() public view override returns (uint) {
        return _getStrategyBaseStorage().lastAprCompound;
    }

    /// @inheritdoc IStrategy
    function assetsAmounts() public view virtual returns (address[] memory assets_, uint[] memory amounts_) {
        (assets_, amounts_) = _assetsAmounts();
        //slither-disable-next-line unused-return
        return StrategyLib.assetsAmountsWithBalances(assets_, amounts_);
    }

    /// @inheritdoc IStrategy
    function previewDepositAssets(
        address[] memory assets_,
        uint[] memory amountsMax
    ) public view virtual returns (uint[] memory amountsConsumed, uint value) {
        // nosemgrep
        if (assets_.length == 1 && assets_[0] == _getStrategyBaseStorage()._underlying && assets_[0] != address(0)) {
            if (amountsMax.length != 1) {
                revert IControllable.IncorrectArrayLength();
            }
            value = amountsMax[0];
            amountsConsumed = _previewDepositUnderlying(amountsMax[0]);
        } else {
            return _previewDepositAssets(assets_, amountsMax);
        }
    }

    /// @inheritdoc IStrategy
    function previewDepositAssetsWrite(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external virtual returns (uint[] memory amountsConsumed, uint value) {
        // nosemgrep
        if (assets_.length == 1 && assets_[0] == _getStrategyBaseStorage()._underlying && assets_[0] != address(0)) {
            if (amountsMax.length != 1) {
                revert IControllable.IncorrectArrayLength();
            }
            value = amountsMax[0];
            amountsConsumed = _previewDepositUnderlyingWrite(amountsMax[0]);
        } else {
            return _previewDepositAssetsWrite(assets_, amountsMax);
        }
    }

    /// @inheritdoc IStrategy
    function autoCompoundingByUnderlyingProtocol() public view virtual returns (bool) {
        return false;
    }

    /// @inheritdoc IStrategy
    function customPriceImpactTolerance() public view returns (uint) {
        return _getStrategyBaseStorage().customPriceImpactTolerance;
    }

    /// @notice IStrategy
    function maxWithdrawAssets() public view virtual returns (uint[] memory amounts) {
        return maxWithdrawAssets(0);
    }

    /// @notice IStrategy
    function maxWithdrawAssets(
        uint /*mode*/
    ) public view virtual returns (uint[] memory amounts) {
        // by default zero-length array is returned to indicate that all available amounts can be withdrawn
        return amounts;
    }

    /// @inheritdoc IStrategy
    function poolTvl() public view virtual returns (uint tvlUsd) {
        // by default max uint is returned to indicate that pool TVL is not calculated
        return type(uint).max;
    }

    /// @notice IStrategy
    function maxDepositAssets() public view virtual returns (uint[] memory amounts) {
        // by default zero-length array is returned to indicate that there are no limits on deposit amounts
        return amounts;
    }

    /// @notice IStrategy
    function protocols() external view returns (string[] memory) {
        return _getStrategyBaseStorage().protocols;
    }

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

    //region -------------------- Default implementations
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  Default implementations                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc IStrategy
    function fuseMode() external view returns (uint) {
        return _getStrategyBaseStorage().fuseOn;
    }

    /// @dev Invest underlying asset. Asset must be already on strategy contract balance.
    /// @return Consumed amounts of invested assets
    function _depositUnderlying(
        uint /*amount*/
    )
        internal
        virtual
        returns (
            uint[] memory /*amountsConsumed*/
        )
    {
        revert(_getStrategyBaseStorage()._underlying == address(0) ? "no underlying" : "not implemented");
    }

    /// @dev Withdraw underlying invested and send to receiver
    function _withdrawUnderlying(
        uint,
        /*amount*/
        address /*receiver*/
    ) internal virtual {
        revert(_getStrategyBaseStorage()._underlying == address(0) ? "no underlying" : "not implemented");
    }

    /// @dev Calculation of consumed amounts and liquidity/underlying value for provided amount of underlying
    function _previewDepositUnderlying(
        uint /*amount*/
    )
        internal
        view
        virtual
        returns (
            uint[] memory /*amountsConsumed*/
        )
    {}

    function _previewDepositUnderlyingWrite(uint amount) internal view virtual returns (uint[] memory amountsConsumed) {
        return _previewDepositUnderlying(amount);
    }

    /// @dev Can be overrided by derived base strategies for custom logic
    function _beforeDeposit() internal virtual {}

    /// @dev Can be overrided by derived base strategies for custom logic
    function _beforeWithdraw() internal virtual {}

    /// @dev Can be overrided by derived base strategies for custom logic
    function _beforeTransferAssets() internal virtual {}

    /// @dev Can be overrided by derived base strategies for custom logic
    function _beforeDoHardWork() internal virtual {
        if (!IStrategy(this).isReadyForHardWork()) {
            revert NotReadyForHardWork();
        }
    }

    /// @inheritdoc IStrategy
    function getSpecificName() external view virtual returns (string memory, bool) {
        return (_getStrategyBaseStorage().specific, true);
    }
    //endregion -------------------- Default implementations

    //region -------------------- Must be implemented by derived contracts
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*         Must be implemented by derived contracts           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc IStrategy
    function supportedVaultTypes() external view virtual returns (string[] memory types);

    /// @dev Investing assets. Amounts must be on strategy contract balance.
    /// @param amounts Amounts of strategy assets to invest
    /// @param claimRevenue Claim revenue before investing
    /// @return value Output of liquidity value or underlying token amount
    function _depositAssets(uint[] memory amounts, bool claimRevenue) internal virtual returns (uint value);

    /// @dev Withdraw assets from investing and send to user.
    /// Here we give the user a choice of assets to withdraw if strategy support it.
    /// This full form of _withdrawAssets can be implemented only in inherited base strategy contract.
    /// @param assets_ Assets for withdrawal. Can contain not all strategy assets if it need.
    /// @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
    ) internal virtual returns (uint[] memory amountsOut);

    /// @dev Withdraw strategy assets from investing and send to user.
    /// This light form of _withdrawAssets is suitable for implementation into final strategy contract.
    /// @param value Part of strategy total value to withdraw
    /// @param receiver User address
    /// @return amountsOut Amounts of assets sent to user
    function _withdrawAssets(uint value, address receiver) internal virtual returns (uint[] memory amountsOut);

    /// @dev Claim all possible revenue to strategy contract balance and calculate claimed revenue after previous HardWork
    /// @return __assets Strategy assets
    /// @return __amounts Amounts of claimed revenue in form of strategy assets
    /// @return __rewardAssets Farming reward assets
    /// @return __rewardAmounts Amounts of claimed farming rewards
    function _claimRevenue()
        internal
        virtual
        returns (
            address[] memory __assets,
            uint[] memory __amounts,
            address[] memory __rewardAssets,
            uint[] memory __rewardAmounts
        );

    function _processRevenue(
        address[] memory assets_,
        uint[] memory amountsRemaining
    ) internal virtual returns (bool needCompound);

    function _liquidateRewards(
        address exchangeAsset,
        address[] memory rewardAssets_,
        uint[] memory rewardAmounts_
    ) internal virtual returns (uint earnedExchangeAsset);

    /// @dev Reinvest strategy assets of strategy contract balance
    function _compound() internal virtual;

    /// @dev Strategy assets and amounts that strategy invests. Without assets on strategy contract balance
    /// @return assets_ Strategy assets
    /// @return amounts_ Amounts invested
    function _assetsAmounts() internal view virtual returns (address[] memory assets_, uint[] memory amounts_);

    /// @dev Calculation of consumed amounts and liquidity/underlying value for provided strategy assets and amounts.
    /// @dev This full form of _previewDepositAssets can be implemented only in inherited base strategy contract
    /// @param assets_ Strategy assets or part of them, if necessary
    /// @param amountsMax Amounts of specified assets available for investing
    /// @return amountsConsumed Consumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function _previewDepositAssets(
        address[] memory assets_,
        uint[] memory amountsMax
    ) internal view virtual returns (uint[] memory amountsConsumed, uint value);

    /// @dev 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 Consumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function _previewDepositAssetsWrite(
        address[] memory assets_,
        uint[] memory amountsMax
    ) internal virtual returns (uint[] memory amountsConsumed, uint value) {
        return _previewDepositAssets(assets_, amountsMax);
    }

    /// @dev Calculation of consumed amounts and liquidity/underlying value for provided strategy assets and amounts.
    /// Light form of _previewDepositAssets is suitable for implementation into final strategy contract.
    /// @param amountsMax Amounts of specified assets available for investing
    /// @return amountsConsumed Consumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function _previewDepositAssets(uint[] memory amountsMax)
        internal
        view
        virtual
        returns (uint[] memory amountsConsumed, uint value);

    /// @dev Write version of _previewDepositAssets
    /// @param amountsMax Amounts of specified assets available for investing
    /// @return amountsConsumed Consumed amounts of assets when investing
    /// @return value Liquidity value or underlying token amount minted when investing
    function _previewDepositAssetsWrite(uint[] memory amountsMax)
        internal
        virtual
        returns (uint[] memory amountsConsumed, uint value)
    {
        return _previewDepositAssets(amountsMax);
    }
    //endregion -------------------- Must be implemented by derived contracts

    //region -------------------- Internal logic
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       INTERNAL LOGIC                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _getStrategyBaseStorage() internal pure returns (StrategyBaseStorage storage $) {
        //slither-disable-next-line assembly
        assembly {
            $.slot := STRATEGYBASE_STORAGE_LOCATION
        }
    }

    function _requireVault() internal view {
        if (msg.sender != _getStrategyBaseStorage().vault) {
            revert IControllable.NotVault();
        }
    }
    //endregion -------------------- Internal logic
}

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

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {StrategyBase} from "./StrategyBase.sol";
import {VaultTypeLib} from "../../core/libs/VaultTypeLib.sol";
import {CommonLib} from "../../core/libs/CommonLib.sol";
import {ILeverageLendingStrategy} from "../../interfaces/ILeverageLendingStrategy.sol";
import {IStrategy} from "../../interfaces/IStrategy.sol";
import {IHardWorker} from "../../interfaces/IHardWorker.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";
import {IControllable} from "../../interfaces/IControllable.sol";

/// @notice Base strategy for leverage lending
/// Changelog:
///   1.2.3: liquidateRewards is virtual, use StrategyBase 2.5.0
///   1.2.2: add universalAddress1 and withdrawParam2 to universal params
///   1.2.1: rebalanceDebt reverts if result share price less #277
///   1.2.0: feat: return new share price by rebalanceDebt #256; feat: use BeetsV3 OR UniswapV3-like DeX free flash loans #268
///   1.1.1: StrategyBase 2.1.3
///   1.1.0: targetLeveragePercent setup in strategy initializer; 8 universal configurable params
/// @author Alien Deployer (https://github.com/a17)
/// @author dvpublic (https://github.com/dvpublic)
abstract contract LeverageLendingBase is StrategyBase, ILeverageLendingStrategy {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Version of FarmingStrategyBase implementation
    string public constant VERSION_LEVERAGE_LENDING_STRATEGY_BASE = "1.2.3";

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

    // keccak256(abi.encode(uint256(keccak256("erc7201:stability.LeverageLendingBase")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 private constant LEVERAGE_LENDING_STRATEGY_STORAGE_LOCATION =
        0xbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f700;

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

    //slither-disable-next-line naming-convention
    function __LeverageLendingBase_init(LeverageLendingStrategyBaseInitParams memory params)
        internal
        onlyInitializing
    {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        $.collateralAsset = params.collateralAsset;
        $.borrowAsset = params.borrowAsset;
        $.lendingVault = params.lendingVault;
        $.borrowingVault = params.borrowingVault;
        $.flashLoanVault = params.flashLoanVault;
        $.helper = params.helper;
        $.targetLeveragePercent = params.targetLeveragePercent;
        emit TargetLeveragePercent(params.targetLeveragePercent);
        address[] memory _assets = new address[](1);
        _assets[0] = params.collateralAsset;
        __StrategyBase_init(params.platform, params.strategyId, params.vault, _assets, address(0), type(uint).max);
    }

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

    /// @inheritdoc ILeverageLendingStrategy
    function rebalanceDebt(uint newLtv, uint minSharePrice) external returns (uint resultLtv, uint resultSharePrice) {
        IPlatform _platform = IPlatform(platform());
        IHardWorker hardworker = IHardWorker(_platform.hardWorker());
        address rebalancer = _platform.rebalancer();
        if (
            msg.sender != rebalancer && !_platform.isOperator(msg.sender)
                && !hardworker.dedicatedServerMsgSender(msg.sender)
        ) {
            revert IControllable.IncorrectMsgSender();
        }

        resultLtv = _rebalanceDebt(newLtv);
        (resultSharePrice,) = _realSharePrice();
        require(resultSharePrice >= minSharePrice, IControllable.TooLowValue(resultSharePrice));
    }

    /// @inheritdoc ILeverageLendingStrategy
    function realSharePrice() external view returns (uint sharePrice, bool trusted) {
        return _realSharePrice();
    }

    /// @inheritdoc ILeverageLendingStrategy
    function setTargetLeveragePercent(uint value) external onlyOperator {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        $.targetLeveragePercent = value;
        emit TargetLeveragePercent(value);
    }

    /// @inheritdoc ILeverageLendingStrategy
    function setUniversalParams(uint[] memory params, address[] memory addresses) external onlyOperator {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        $.depositParam0 = params[0];
        $.depositParam1 = params[1];
        $.withdrawParam0 = params[2];
        $.withdrawParam1 = params[3];
        $.increaseLtvParam0 = params[4];
        $.increaseLtvParam1 = params[5];
        $.decreaseLtvParam0 = params[6];
        $.decreaseLtvParam1 = params[7];
        $.swapPriceImpactTolerance0 = params[8];
        $.swapPriceImpactTolerance1 = params[9];
        $.flashLoanKind = params[10];
        $.withdrawParam2 = params[11];

        $.flashLoanVault = addresses[0];
        $.universalAddress1 = addresses[1];

        emit UniversalParams(params);
        emit UniversalAddresses(addresses);
    }

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

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(ILeverageLendingStrategy).interfaceId || super.supportsInterface(interfaceId);
    }

    /// @inheritdoc IStrategy
    function supportedVaultTypes() external view virtual override returns (string[] memory types) {
        types = new string[](1);
        types[0] = VaultTypeLib.COMPOUNDING;
    }

    /// @inheritdoc IStrategy
    function getAssetsProportions() public pure returns (uint[] memory proportions) {
        proportions = new uint[](1);
        proportions[0] = 1e18;
    }

    /// @inheritdoc IStrategy
    function isReadyForHardWork() external pure virtual returns (bool isReady) {
        return true;
    }

    /// @inheritdoc IStrategy
    function extra() external pure returns (bytes32) {
        //slither-disable-next-line too-many-digits
        return CommonLib.bytesToBytes32(abi.encodePacked(bytes3(0xffffff), bytes3(0x000000)));
    }

    /// @inheritdoc IStrategy
    function autoCompoundingByUnderlyingProtocol() public view virtual override returns (bool) {
        return true;
    }

    /// @inheritdoc IStrategy
    function getRevenue() external pure virtual returns (address[] memory assets_, uint[] memory amounts) {}

    /// @inheritdoc ILeverageLendingStrategy
    function getUniversalParams() external view returns (uint[] memory params, address[] memory addresses) {
        LeverageLendingBaseStorage storage $ = _getLeverageLendingBaseStorage();
        params = new uint[](12);
        params[0] = $.depositParam0;
        params[1] = $.depositParam1;
        params[2] = $.withdrawParam0;
        params[3] = $.withdrawParam1;
        params[4] = $.increaseLtvParam0;
        params[5] = $.increaseLtvParam1;
        params[6] = $.decreaseLtvParam0;
        params[7] = $.decreaseLtvParam1;
        params[8] = $.swapPriceImpactTolerance0;
        params[9] = $.swapPriceImpactTolerance1;
        params[10] = $.flashLoanKind;
        params[11] = $.withdrawParam2;

        addresses = new address[](2);
        addresses[0] = $.flashLoanVault;
        addresses[1] = $.universalAddress1;
    }
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       STRATEGY BASE                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @inheritdoc StrategyBase
    function _compound() internal virtual override {}

    /// @inheritdoc StrategyBase
    function _processRevenue(
        address[] memory, /*assets_*/
        uint[] memory /*amountsRemaining*/
    ) internal pure virtual override returns (bool needCompound) {
        needCompound = true;
    }

    /// @inheritdoc StrategyBase
    function _previewDepositAssets(
        address[] memory, /*assets_*/
        uint[] memory amountsMax
    ) internal view override(StrategyBase) returns (uint[] memory amountsConsumed, uint value) {
        return _previewDepositAssets(amountsMax);
    }

    function _withdrawAssets(
        address[] memory, /*assets_*/
        uint value,
        address receiver
    ) internal virtual override returns (uint[] memory amountsOut) {
        return _withdrawAssets(value, receiver);
    }

    /// @inheritdoc StrategyBase
    function _liquidateRewards(
        address exchangeAsset,
        address[] memory rewardAssets_,
        uint[] memory rewardAmounts_
    ) internal virtual override returns (uint earnedExchangeAsset) {}

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*         Must be implemented by derived contracts           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _rebalanceDebt(uint newLtv) internal virtual returns (uint resultLtv);

    function _realSharePrice() internal view virtual returns (uint sharePrice, bool trusted);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       INTERNAL LOGIC                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _getLeverageLendingBaseStorage() internal pure returns (LeverageLendingBaseStorage storage $) {
        //slither-disable-next-line assembly
        assembly {
            $.slot := LEVERAGE_LENDING_STRATEGY_STORAGE_LOCATION
        }
    }
}

File 10 of 56 : StrategyIdLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

library StrategyIdLib {
    string internal constant DEV = "Dev Alpha DeepSpaceSwap Farm";
    string internal constant QUICKSWAPV3_STATIC_FARM = "QuickSwapV3 Static Farm";
    string internal constant GAMMA_QUICKSWAP_MERKL_FARM = "Gamma QuickSwap Merkl Farm";
    string internal constant GAMMA_RETRO_MERKL_FARM = "Gamma Retro Merkl Farm";
    string internal constant GAMMA_UNISWAPV3_MERKL_FARM = "Gamma UniswapV3 Merkl Farm";
    string internal constant COMPOUND_FARM = "Compound Farm";
    string internal constant DEFIEDGE_QUICKSWAP_MERKL_FARM = "DefiEdge QuickSwap Merkl Farm";
    string internal constant STEER_QUICKSWAP_MERKL_FARM = "Steer QuickSwap Merkl Farm";
    string internal constant ICHI_QUICKSWAP_MERKL_FARM = "Ichi QuickSwap Merkl Farm";
    string internal constant ICHI_RETRO_MERKL_FARM = "Ichi Retro Merkl Farm";
    string internal constant QUICKSWAP_STATIC_MERKL_FARM = "QuickSwap Static Merkl Farm";
    string internal constant CURVE_CONVEX_FARM = "Curve Convex Farm";
    string internal constant YEARN = "Yearn";
    string internal constant TRIDENT_PEARL_FARM = "Trident Pearl Farm";
    string internal constant BEETS_STABLE_FARM = "Beets Stable Farm";
    string internal constant BEETS_WEIGHTED_FARM = "Beets Weighted Farm";
    string internal constant EQUALIZER_FARM = "Equalizer Farm";
    string internal constant ICHI_SWAPX_FARM = "Ichi SwapX Farm";
    string internal constant SWAPX_FARM = "SwapX Farm";
    string internal constant SILO_FARM = "Silo Farm";
    string internal constant ALM_SHADOW_FARM = "ALM Shadow Farm";
    string internal constant SILO_LEVERAGE = "Silo Leverage";
    string internal constant SILO_ADVANCED_LEVERAGE = "Silo Advanced Leverage";
    string internal constant GAMMA_EQUALIZER_FARM = "Gamma Equalizer Farm";
    string internal constant ICHI_EQUALIZER_FARM = "Ichi Equalizer Farm";
    string internal constant EULER_MERKL_FARM = "Euler Merkl Farm";
    string internal constant SILO = "Silo";
    string internal constant AAVE = "Aave";
    string internal constant EULER = "Euler"; // https://euler.finance/
    string internal constant SILO_MANAGED_FARM = "Silo Managed Farm";
    string internal constant SILO_ALMF_FARM = "Silo Advanced Leverage Merkl Farm";
    string internal constant AAVE_MERKL_FARM = "Aave Merkl Farm";
    string internal constant COMPOUND_V2 = "Compound V2";
    string internal constant SILO_MANAGED_MERKL_FARM = "Silo Managed Merkl Farm";
    string internal constant SILO_MERKL_FARM = "Silo Merkl Farm"; // SiMerklF
}

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

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 {IPlatform} from "../../interfaces/IPlatform.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;
    }

    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]).safeTransfer(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});

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

        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
                }
                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;
    }
}

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

import {IStrategy} from "../../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";

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
}

File 13 of 56 : IStrategy.sol
// 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 StrategyProtocols(string[]);
    event SpecificName(string);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       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;
        /// @inheritdoc IStrategy
        string[] protocols;
        string specific;
    }

    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);

    /// @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
    /// @dev This function is replaced by more flexible maxWithdrawAssets(uint mode) function.
    function maxWithdrawAssets() external view returns (uint[] memory amounts);

    /// @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
    /// @param mode 0 - Return amount that can be withdrawn in assets
    ///             1 - Return amount that can be withdrawn in underlying
    /// @return amounts Empty array (zero length) is returned if all available amount can be withdrawn
    function maxWithdrawAssets(uint mode) 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);

    /// @notice Show strategy protocols
    function protocols() external view returns (string[] memory);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      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 Set custom strategy protocols
    /// @param protocols_ Row format is: defi_organization_id:protocol_id from Stability Library.
    function setProtocols(string[] calldata protocols_) external;

    /// @notice Set custom specific name
    function setSpecificName(string memory specific) external;
}

// 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
pragma solidity ^0.8.28;

import {EnumerableSet} from "@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 StrategyImplementationIsNotAvailable();
    error YouDontHaveEnoughTokens(uint userBalance, uint requireBalance, address payToken);
    error SuchVaultAlreadyDeployed(bytes32 key);
    error NotActiveVault();
    error UpgradeDenied(bytes32 _hash);
    error AlreadyLastVersion(bytes32 _hash);
    error NotStrategy();

    //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 => mapping(uint => uint)) __deprecated1;
        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
    )
        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 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 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);

    //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 implementation
    /// Operator can add new vault type. Governance or multisig can change existing vault type config.
    /// @param vaultType Vault type string ID (Compounding, etc)
    /// @param implementation Address of vault implementation
    function setVaultImplementation(string memory vaultType, address implementation) 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 Set new implementation of the strategy
    /// @dev Initial addition or change of strategy logic implementation.
    /// Operator can add new strategy logic. Governance or multisig can change existing logic config.
    /// @param strategyId Strategy logic ID string
    /// @param implementation Address of strategy implementation
    function setStrategyImplementation(string memory strategyId, address implementation) external;

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

File 16 of 56 : 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)
/// @author ruby (https://github.com/alexandersazonof)
interface IPlatform {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error AlreadyAnnounced();
    error SameVersion();
    error NoNewVersion();
    error UpgradeTimerIsNotOver(uint TimerTimestamp);
    error IncorrectFee(uint minFee, uint maxFee);
    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,
        address vaultManager_,
        address strategyLogic_,
        address,
        address hardWorker,
        address rebalancer,
        address zap,
        address bridge
    );
    event OperatorAdded(address operator);
    event OperatorRemoved(address operator);
    event FeesChanged(uint fee, uint, uint, uint);
    event NewAmmAdapter(string id, address proxy);
    event EcosystemRevenueReceiver(address receiver);
    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);
    event VaultPriceOracle(address vaultPriceOracle_);
    event Recovery(address recovery_);

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

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

    struct PlatformSettings {
        uint fee;
    }

    struct AmmAdapter {
        string id;
        address proxy;
    }

    struct SetupAddresses {
        address factory;
        address priceReader;
        address swapper;
        address vaultManager;
        address strategyLogic;
        address targetExchangeAsset;
        address hardWorker;
        address zap;
        address revenueRouter;
        address metaVaultFactory;
        address vaultPriceOracle;
    }
    // recovery is not configured by default, use setupRecovery function

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      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 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 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 vaultPriceOracle
    /// @return Address of the vault price oracle
    function vaultPriceOracle() external view returns (address);

    /// @notice Contract for redeeming recovery tokens
    /// @return Address of the recovery contract
    function recovery() external view returns (address);

    /// @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);

    /// @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.
    function getFees() external view returns (uint fee, uint, uint, uint);

    /// @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 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 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] deprecated
    ///        platformAddresses[4] deprecated
    ///        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 execute pending platform upgrade
    function upgrade() external;

    /// @notice Cancel pending platform upgrade
    /// Only operator (multisig is operator too) can execute 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;

    /// @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 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;

    /// @notice Set vault price oracle
    /// @param vaultPriceOracle_ Address of the vault price oracle
    function setupVaultPriceOracle(address vaultPriceOracle_) external;

    /// @notice Set recovery contract
    /// @param recovery_ Address of the recovery contract
    function setupRecovery(address recovery_) 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 -----

    //region --------------------------- Errors
    error NotWhitelistedTransientCache();
    //endregion --------------------------- Errors

    /// @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;

    /// @notice Check if the user is whitelisted for using transient cache
    function whitelistTransientCache(address user_) external view returns (bool);

    /// @notice Add user to whitelist of users allowed to use the transient cache
    function changeWhitelistTransientCache(address user, bool add) external;

    /// @notice Save asset price to transient cache
    /// @param asset Pass 0 to clear the cache
    function preCalculatePriceTx(address asset) external;

    /// @notice Save vault price to transient cache
    /// Second call with the same vault will be ignored and won't not change the price
    /// @param vault Pass 0 to clear the cache
    function preCalculateVaultPriceTx(address vault) external;
}

// 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);
}

// 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 convertToAssets(uint256 _shares, CollateralType _assetType) external view returns (uint256 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);

    function maxWithdraw(address _owner, CollateralType _collateralType) external view returns (uint256 maxAssets);
}

// 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: GPL-3.0-or-later

pragma solidity ^0.8.24;

/// @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;
}

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

interface IFlashLoanRecipient {
    /**
     * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
     *
     * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
     * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
     * Vault, or else the entire flash loan will revert.
     *
     * `userData` is the same value passed in the `IVault.flashLoan` call.
     */
    function receiveFlashLoan(
        address[] memory tokens,
        uint256[] memory amounts,
        uint256[] memory feeAmounts,
        bytes memory userData
    ) external;
}

File 24 of 56 : IUniswapV3FlashCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#flash
/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface
interface IUniswapV3FlashCallback {
  /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.
  /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
  /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
  /// @param fee0 The fee amount in token0 due to the pool by the end of the flash
  /// @param fee1 The fee amount in token1 due to the pool by the end of the flash
  /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call
  function uniswapV3FlashCallback(
    uint256 fee0,
    uint256 fee1,
    bytes calldata data
  ) external;
}

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

interface IBalancerV3FlashCallback {

  /// @notice This callback is called inside IVaultMainV3.unlock (balancer v3)
  /// @dev Support of FLASH_LOAN_KIND_BALANCER_V3
  /// @param token Token of flash loan
  /// @param amount Required amount of the flash loan
  function receiveFlashLoanV3(address token, uint amount, bytes memory userData) external;
}

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

/// @title Callback for IAlgebraPoolActions#flash
/// @notice Any contract that calls IAlgebraPoolActions#flash must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraFlashCallback {
  /// @notice Called to `msg.sender` after transferring to the recipient from IAlgebraPool#flash.
  /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
  /// The caller of this method _must_ be checked to be a AlgebraPool deployed by the canonical AlgebraFactory.
  /// @param fee0 The fee amount in token0 due to the pool by the end of the flash
  /// @param fee1 The fee amount in token1 due to the pool by the end of the flash
  /// @param data Any data passed through by the caller via the IAlgebraPoolActions#flash call
  function algebraFlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) external;
}

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

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        (1 << 0x08) | // backspace
            (1 << 0x09) | // tab
            (1 << 0x0a) | // newline
            (1 << 0x0c) | // form feed
            (1 << 0x0d) | // carriage return
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

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

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @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;
            assembly ("memory-safe") {
                ptr := add(add(buffer, 0x20), length)
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    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 Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @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));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress-string} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress-string-uint256-uint256} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
     *
     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
     *
     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
     * characters that are not in this range, but other tooling may provide different results.
     */
    function escapeJSON(string memory input) internal pure returns (string memory) {
        bytes memory buffer = bytes(input);
        bytes memory output = new bytes(2 * buffer.length); // worst case scenario
        uint256 outputLength = 0;

        for (uint256 i; i < buffer.length; ++i) {
            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
                output[outputLength++] = "\\";
                if (char == 0x08) output[outputLength++] = "b";
                else if (char == 0x09) output[outputLength++] = "t";
                else if (char == 0x0a) output[outputLength++] = "n";
                else if (char == 0x0c) output[outputLength++] = "f";
                else if (char == 0x0d) output[outputLength++] = "r";
                else if (char == 0x5c) output[outputLength++] = "\\";
                else if (char == 0x22) {
                    // solhint-disable-next-line quotes
                    output[outputLength++] = '"';
                }
            } else {
                output[outputLength++] = char;
            }
        }
        // write the actual length and deallocate unused memory
        assembly ("memory-safe") {
            mstore(output, outputLength)
            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
        }

        return string(output);
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(add(buffer, 0x20), offset))
        }
    }
}

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

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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
pragma solidity ^0.8.28;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SlotsLib} from "../libs/SlotsLib.sol";
import {IControllable} from "../../interfaces/IControllable.sol";
import {IPlatform} from "../../interfaces/IPlatform.sol";

/// @dev Base core contract.
///      It store an immutable platform proxy address in the storage and provides access control to inherited contracts.
/// @author Alien Deployer (https://github.com/a17)
/// @author 0xhokugava (https://github.com/0xhokugava)
abstract contract Controllable is Initializable, IControllable, ERC165 {
    using SlotsLib for bytes32;

    string public constant CONTROLLABLE_VERSION = "1.0.1";
    bytes32 internal constant _PLATFORM_SLOT = bytes32(uint(keccak256("eip1967.controllable.platform")) - 1);
    bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint(keccak256("eip1967.controllable.created_block")) - 1);

    /// @dev Prevent implementation init
    constructor() {
        _disableInitializers();
    }

    /// @notice Initialize contract after setup it as proxy implementation
    ///         Save block.timestamp in the "created" variable
    /// @dev Use it only once after first logic setup
    /// @param platform_ Platform address
    //slither-disable-next-line naming-convention
    function __Controllable_init(address platform_) internal onlyInitializing {
        require(platform_ != address(0) && IPlatform(platform_).multisig() != address(0), IncorrectZeroArgument());
        SlotsLib.set(_PLATFORM_SLOT, platform_); // syntax for forge coverage
        _CREATED_BLOCK_SLOT.set(block.number);
        emit ContractInitialized(platform_, block.timestamp, block.number);
    }

    modifier onlyGovernance() {
        _requireGovernance();
        _;
    }

    modifier onlyMultisig() {
        _requireMultisig();
        _;
    }

    modifier onlyGovernanceOrMultisig() {
        _requireGovernanceOrMultisig();
        _;
    }

    modifier onlyOperator() {
        _requireOperator();
        _;
    }

    modifier onlyFactory() {
        _requireFactory();
        _;
    }

    // ************* SETTERS/GETTERS *******************

    /// @inheritdoc IControllable
    function platform() public view override returns (address) {
        return _PLATFORM_SLOT.getAddress();
    }

    /// @inheritdoc IControllable
    function createdBlock() external view override returns (uint) {
        return _CREATED_BLOCK_SLOT.getUint();
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IControllable).interfaceId || super.supportsInterface(interfaceId);
    }

    function _requireGovernance() internal view {
        require(IPlatform(platform()).governance() == msg.sender, NotGovernance());
    }

    function _requireMultisig() internal view {
        require(IPlatform(platform()).multisig() == msg.sender, NotMultisig());
    }

    function _requireGovernanceOrMultisig() internal view {
        IPlatform _platform = IPlatform(platform());
        require(
            _platform.governance() == msg.sender || _platform.multisig() == msg.sender, NotGovernanceAndNotMultisig()
        );
    }

    function _requireOperator() internal view {
        require(IPlatform(platform()).isOperator(msg.sender), NotOperator());
    }

    function _requireFactory() internal view {
        require(IPlatform(platform()).factory() == msg.sender, NotFactory());
    }
}

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

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

/// @notice Vault core interface.
/// Derived implementations can be effective for building tokenized vaults with single or multiple underlying liquidity mining position.
/// Fungible, static non-fungible and actively re-balancing liquidity is supported, as well as single token liquidity provided to lending protocols.
/// Vaults can be used for active concentrated liquidity management and market making.
/// @author Jude (https://github.com/iammrjude)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IVault is IERC165, IStabilityVault {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error NotEnoughBalanceToPay();
    error FuseTrigger();
    error ExceedSlippageExactAsset(address asset, uint mintToUser, uint minToMint);
    error NotEnoughAmountToInitSupply(uint mintAmount, uint initialShares);
    error StrategyZeroDeposit();

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

    event HardWorkGas(uint gasUsed, uint gasCost, bool compensated);
    event DoHardWorkOnDepositChanged(bool oldValue, bool newValue);
    event MintFees(
        uint vaultManagerReceiverFee,
        uint strategyLogicReceiverFee,
        uint ecosystemRevenueReceiverFee,
        uint multisigReceiverFee
    );

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

    /// @custom:storage-location erc7201:stability.VaultBase
    struct VaultBaseStorage {
        /// @dev Prevents manipulations with deposit and withdraw in short time.
        ///      For simplification we are setup new withdraw request on each deposit/transfer.
        mapping(address msgSender => uint blockNumber) withdrawRequests;
        /// @inheritdoc IVault
        IStrategy strategy;
        /// @inheritdoc IVault
        uint maxSupply;
        /// @inheritdoc IVault
        uint tokenId;
        /// @inheritdoc IVault
        bool doHardWorkOnDeposit;
        /// @dev Immutable vault type ID
        string _type;
        /// @dev Changed ERC20 name
        string changedName;
        /// @dev Changed ERC20 symbol
        string changedSymbol;
        /// @inheritdoc IStabilityVault
        bool lastBlockDefenseDisabled;
    }

    /// @title Vault Initialization Data
    /// @notice Data structure containing parameters for initializing a new vault.
    /// @dev This struct is commonly used as a parameter for the `initialize` function in vault contracts.
    /// @param platform Platform address providing access control, infrastructure addresses, fee settings, and upgrade capability.
    /// @param strategy Immutable strategy proxy used by the vault.
    /// @param name ERC20 name for the vault token.
    /// @param symbol ERC20 symbol for the vault token.
    /// @param tokenId NFT ID associated with the VaultManager.
    /// @param vaultInitAddresses Array of addresses used during vault initialization.
    /// @param vaultInitNums Array of uint values corresponding to initialization parameters.
    struct VaultInitializationData {
        address platform;
        address strategy;
        string name;
        string symbol;
        uint tokenId;
        address[] vaultInitAddresses;
        uint[] vaultInitNums;
    }

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

    /// @return uniqueInitAddresses Return required unique init addresses
    /// @return uniqueInitNums Return required unique init nums
    function getUniqueInitParamLength() external view returns (uint uniqueInitAddresses, uint uniqueInitNums);

    /// @notice Vault type extra data
    /// @return Vault type color, background color and other extra data
    function extra() external view returns (bytes32);

    /// @notice Immutable strategy proxy used by the vault
    /// @return Linked strategy
    function strategy() external view returns (IStrategy);

    /// @notice Max supply of shares in the vault.
    /// Since the starting share price is $1, this ceiling can be considered as an approximate TVL limit.
    /// @return Max total supply of vault
    function maxSupply() external view returns (uint);

    /// @dev VaultManager token ID. This tokenId earn feeVaultManager provided by Platform.
    function tokenId() external view returns (uint);

    /// @dev Trigger doHardwork on invest action. Enabled by default.
    function doHardWorkOnDeposit() external view returns (bool);

    /// @notice All available data on the latest declared APR (annual percentage rate)
    /// @return totalApr Total APR of investing money to vault. 18 decimals: 1e18 - +100% per year.
    /// @return strategyApr Strategy investmnt APR declared on last HardWork.
    /// @return assetsWithApr Assets with underlying APR
    /// @return assetsAprs Underlying APR of asset
    function getApr()
        external
        view
        returns (uint totalApr, uint strategyApr, address[] memory assetsWithApr, uint[] memory assetsAprs);

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

    /// @notice Write version of previewDepositAssets
    /// @param assets_ Assets suitable for vault strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountsMax Available amounts of assets_ that user wants to invest in vault
    /// @return amountsConsumed Amounts of strategy assets that can be deposited by providing amountsMax
    /// @return sharesOut Amount of vault shares that will be minted
    /// @return valueOut Liquidity value or underlying token amount that will be received by the strategy
    function previewDepositAssetsWrite(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external returns (uint[] memory amountsConsumed, uint sharesOut, uint valueOut);

    /// @dev Mint fee shares callback
    /// @param revenueAssets Assets returned by _claimRevenue function that was earned during HardWork
    /// @param revenueAmounts Assets amounts returned from _claimRevenue function that was earned during HardWork
    /// Only strategy can call this
    function hardWorkMintFeeCallback(address[] memory revenueAssets, uint[] memory revenueAmounts) external;

    /// @dev Setting of vault capacity
    /// @param maxShares If totalSupply() exceeds this value, deposits will not be possible
    function setMaxSupply(uint maxShares) external;

    /// @dev If activated will call doHardWork on strategy on some deposit actions
    /// @param value HardWork on deposit is enabled
    function setDoHardWorkOnDeposit(bool value) external;

    /// @notice Initialization function for the vault.
    /// @dev This function is usually called by the Factory during the creation of a new vault.
    /// @param vaultInitializationData Data structure containing parameters for vault initialization.
    function initialize(VaultInitializationData memory vaultInitializationData) external;

    /// @dev Calling the strategy HardWork by operator with optional compensation for spent gas from the vault balance
    function doHardWork() external;
}

File 32 of 56 : VaultTypeLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

library VaultTypeLib {
    string internal constant COMPOUNDING = "Compounding";
    //string internal constant REWARDING = "Rewarding";
    //string internal constant REWARDING_MANAGED = "Rewarding Managed";
    string internal constant MULTIVAULT = "MultiVault";
    string internal constant METAVAULT = "MetaVault";
}

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

/// @dev HardWork resolver and caller. Executor is server script.
/// Hardwork is important task of any vault - claiming revenue and processing it by strategy, updating rewarding,
/// compounding, declaring income and losses, related things.
/// @author Alien Deployer (https://github.com/a17)
/// @author JodsMigel (https://github.com/JodsMigel)
interface IHardWorker {
    //region ----- Custom Errors -----
    error NotExistWithObject(address notExistObject);
    error AlreadyExclude(address alreadyExcludedObject);
    error NotServer();
    error NotEnoughETH();
    //endregion ----- Custom Errors -----

    event Call(uint hardworks, uint gasUsed, uint gasCost, bool server);
    event DedicatedServerMsgSender(address indexed sender, bool allowed);
    event Delays(uint delayServer, uint);
    event MaxHwPerCall(uint maxHwPerCall_);
    event VaultExcludeStatusChanged(address vault, bool status);

    /// @notice Default delay between HardWorks
    function getDelay() external view returns (uint delayServer);

    /// @notice Vaults that excluded from HardWork execution
    function excludedVaults(address vault) external view returns (bool);

    /// @notice Maximum vault HardWork calls per execution
    function maxHwPerCall() external view returns (uint);

    /// @notice Check dedicated server address allowance for execute vault HardWorks
    function dedicatedServerMsgSender(address sender) external view returns (bool allowed);

    /// @notice Checker method for calling from server script
    /// @return canExec Hard Work can be executed
    /// @return execPayload Vault addresses for HardWork
    function checkerServer() external view returns (bool canExec, bytes memory execPayload);

    /// @notice Setup allowance status for dedicated server address
    function setDedicatedServerMsgSender(address sender, bool allowed) external;

    /// @notice Setup delays between HardWorks in seconds
    /// @param delayServer_ Delay for server script
    function setDelay(uint delayServer_) external;

    /// @notice Set maximum vault HardWork calls per execution
    /// Only operator cal call this
    /// @param maxHwPerCall_ Max vault HardWorks per call(vaults) execution
    //slither-disable-next-line similar-names
    function setMaxHwPerCall(uint maxHwPerCall_) external;

    /// @notice Changing vault excluding status
    /// @param vaults_ Addresses of vaults
    /// @param status New status
    function changeVaultExcludeStatus(address[] memory vaults_, bool[] memory status) external;

    /// @notice Call vault HardWorks
    /// @param vaults Addresses of vault from checkerServer output
    function call(address[] memory vaults) external;
}

File 34 of 56 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(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.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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 {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 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 low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

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

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, 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 ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

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

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            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⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @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
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;

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

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

    event EpochFlip(uint periodEnded, uint totalStblRevenue);
    event AddedUnit(uint unitIndex, UnitType unitType, string name, address feeTreasury);
    event UpdatedUnit(uint unitIndex, UnitType unitType, 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;
        EnumerableSet.AddressSet vaultsAccumulated;
    }

    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 Update Unit
    function updateUnit(uint unitIndex, 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;

    /// @notice Withdraw assets from accumulated vaults and swap to STBL
    function processAccumulatedVaults(uint maxVaultsForWithdraw) external;

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

    /// @notice Show all Units
    function units() external view returns (Unit[] memory);

    /// @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);

    /// @notice Get vault addresses that contract hold on balance, but not withdrew yet
    function vaultsAccumulated() external view returns (address[] memory);
}

// 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.28;

import {IBVault} from "../../integrations/balancer/IBVault.sol";
import {IControllable} from "../../interfaces/IControllable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ILeverageLendingStrategy} from "../../interfaces/ILeverageLendingStrategy.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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, "");
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @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.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * The following types are supported:
 *
 * - `bytes32` (`Bytes32Set`) since v3.3.0
 * - `address` (`AddressSet`) since v3.3.0
 * - `uint256` (`UintSet`) since v3.3.0
 * - `string` (`StringSet`) since v5.4.0
 * - `bytes` (`BytesSet`) since v5.4.0
 *
 * [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 Removes all the values from a set. O(n).
     *
     * WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
     * using it may render the function uncallable if the set grows to the point where clearing it consumes too much
     * gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @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;
    }

    /**
     * @dev Return a slice of the 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, uint256 start, uint256 end) private view returns (bytes32[] memory) {
        unchecked {
            end = Math.min(end, _length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes32[] memory result = new bytes32[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    // 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 Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @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;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        bytes32[] memory result;

        assembly ("memory-safe") {
            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 Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @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;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        address[] memory result;

        assembly ("memory-safe") {
            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 Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @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;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    struct StringSet {
        // Storage of set values
        string[] _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(string 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(StringSet storage set, string memory value) internal 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(StringSet storage set, string memory value) internal 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) {
                string memory 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 Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(StringSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(StringSet storage set, string memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(StringSet storage set) internal 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(StringSet storage set, uint256 index) internal view returns (string memory) {
        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(StringSet storage set) internal view returns (string[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the 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(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            string[] memory result = new string[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    struct BytesSet {
        // Storage of set values
        bytes[] _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(bytes 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(BytesSet storage set, bytes memory value) internal 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(BytesSet storage set, bytes memory value) internal 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) {
                bytes memory 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 Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(BytesSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(BytesSet storage set) internal 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(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
        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(BytesSet storage set) internal view returns (bytes[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the 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(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes[] memory result = new bytes[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }
}

File 41 of 56 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

File 42 of 56 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

File 43 of 56 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

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

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(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 {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 reinitialization) 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 Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

/// @title Minimal library for setting / getting slot variables (used in upgradable proxy contracts)
library SlotsLib {
    /// @dev Gets a slot as an address
    function getAddress(bytes32 slot) internal view returns (address result) {
        assembly {
            result := sload(slot)
        }
    }

    /// @dev Gets a slot as uint256
    function getUint(bytes32 slot) internal view returns (uint result) {
        assembly {
            result := sload(slot)
        }
    }

    /// @dev Sets a slot with address
    /// @notice Check address for 0 at the setter
    function set(bytes32 slot, address value) internal {
        assembly {
            sstore(slot, value)
        }
    }

    /// @dev Sets a slot with uint
    function set(bytes32 slot, uint value) internal {
        assembly {
            sstore(slot, value)
        }
    }
}

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

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

/// @notice Base interface of Stability Vault
interface IStabilityVault is IERC20, IERC20Metadata {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error WaitAFewBlocks();
    error ExceedSlippage(uint mintToUser, uint minToMint);
    error ExceedMaxSupply(uint maxSupply);
    error NotSupported();

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

    event DepositAssets(address indexed account, address[] assets, uint[] amounts, uint mintAmount);
    event WithdrawAssets(
        address indexed sender, address indexed owner, address[] assets, uint sharesAmount, uint[] amountsOut
    );
    event MaxSupply(uint maxShares);
    event VaultName(string newName);
    event VaultSymbol(string newSymbol);
    event LastBlockDefenseDisabled(bool isDisabled);

    //region --------------------------------------- View functions
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       VIEW FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @notice Underlying assets
    function assets() external view returns (address[] memory);

    /// @notice Immutable vault type ID
    function vaultType() external view returns (string memory);

    /// @dev Calculation of consumed amounts, shares amount and liquidity/underlying value for provided available amounts of strategy assets
    /// @param assets_ Assets suitable for vault strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountsMax Available amounts of assets_ that user wants to invest in vault
    /// @return amountsConsumed Amounts of strategy assets that can be deposited by providing amountsMax
    /// @return sharesOut Amount of vault shares that will be minted
    /// @return valueOut Liquidity value or underlying token amount that will be received by the strategy
    function previewDepositAssets(
        address[] memory assets_,
        uint[] memory amountsMax
    ) external view returns (uint[] memory amountsConsumed, uint sharesOut, uint valueOut);

    /// @dev USD price of share with 18 decimals.
    ///      Not trusted vault share price can be manipulated, used only OFF-CHAIN.
    /// @return price_ Price of 1e18 shares with 18 decimals precision
    /// @return trusted True means oracle price, false means AMM spot price
    function price() external view returns (uint price_, bool trusted);

    /// @dev USD price of assets managed by strategy with 18 decimals
    ///      Not trusted vault share price can be manipulated, used only OFF-CHAIN.
    /// @return tvl_ Total USD value of final assets in vault
    /// @return trusted True means TVL calculated based only on oracle prices, false means AMM spot price was used.
    function tvl() external view returns (uint tvl_, bool trusted);

    /// @dev Minimum 6 blocks between deposit and withdraw check disabled
    function lastBlockDefenseDisabled() external view returns (bool);

    /// @return amount Maximum amount that can be withdrawn from the vault for the given account.
    /// This is max amount that can be passed to `withdraw` function.
    /// The implementation should take into account IStrategy.maxWithdrawAssets
    /// @dev It's alias of IStabilityVault.maxWithdraw(account, 0) for backwords compatibility.
    function maxWithdraw(address account) external view returns (uint amount);

    /// @return amount Maximum amount that can be withdrawn from the vault for the given account.
    /// This is max amount that can be passed to `withdraw` function.
    /// The implementation should take into account IStrategy.maxWithdrawAssets
    /// @param mode 0 - Return amount that can be withdrawn in assets
    ///             1 - Return amount that can be withdrawn in underlying
    function maxWithdraw(address account, uint mode) external view returns (uint amount);

    /// @return maxAmounts Maximum amounts that can be deposited to the vault for the given account.
    /// This is max amounts of {assets} that can be passed to `depositAssets` function as {amountsMax}.
    /// The implementation should take into account IStrategy.maxDepositAssets
    /// Return type(uint).max if there is no limit for the asset.
    function maxDeposit(address account) external view returns (uint[] memory maxAmounts);
    //endregion --------------------------------------- View functions

    //region --------------------------------------- Write functions
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      WRITE FUNCTIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deposit final assets (pool assets) to the strategy and minting of vault shares.
    ///      If the strategy interacts with a pool or farms through an underlying token, then it will be minted.
    ///      Emits a {DepositAssets} event with consumed amounts.
    /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountsMax Available amounts of assets_ that user wants to invest in vault
    /// @param minSharesOut Slippage tolerance. Minimal shares amount which must be received by user.
    /// @param receiver Receiver of deposit. If receiver is zero address, receiver is msg.sender.
    function depositAssets(
        address[] memory assets_,
        uint[] memory amountsMax,
        uint minSharesOut,
        address receiver
    ) external;

    /// @dev Burning shares of vault and obtaining strategy assets.
    /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountShares Shares amount for burning
    /// @param minAssetAmountsOut Slippage tolerance. Minimal amounts of strategy assets that user must receive.
    /// @return Amount of assets for withdraw. It's related to assets_ one-by-one.
    function withdrawAssets(
        address[] memory assets_,
        uint amountShares,
        uint[] memory minAssetAmountsOut
    ) external returns (uint[] memory);

    /// @dev Burning shares of vault and obtaining strategy assets.
    /// @param assets_ Assets suitable for the strategy. Can be strategy assets, underlying asset or specific set of assets depending on strategy logic.
    /// @param amountShares Shares amount for burning
    /// @param minAssetAmountsOut Slippage tolerance. Minimal amounts of strategy assets that user must receive.
    /// @param receiver Receiver of assets
    /// @param owner Owner of vault shares
    /// @return Amount of assets for withdraw. It's related to assets_ one-by-one.
    function withdrawAssets(
        address[] memory assets_,
        uint amountShares,
        uint[] memory minAssetAmountsOut,
        address receiver,
        address owner
    ) external returns (uint[] memory);

    /// @dev Changing ERC20 name of vault
    function setName(string calldata newName) external;

    /// @dev Changing ERC20 symbol of vault
    function setSymbol(string calldata newSymbol) external;

    /// @dev Enable or disable last block check
    function setLastBlockDefenseDisabled(bool isDisabled) external;
    //endregion --------------------------------------- Write functions
}

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

// 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-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);
}

File 53 of 56 : Arrays.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.

pragma solidity ^0.8.20;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            if (end - begin < 0x40) return;

            // Use first element as pivot
            uint256 pivot = _mload(begin);
            // Position where the pivot should be at the end of the loop
            uint256 pos = begin;

            for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                if (comp(_mload(it), pivot)) {
                    // If the value stored at the iterator's position comes before the pivot, we increment the
                    // position of the pivot and move the value there.
                    pos += 0x20;
                    _swap(pos, it);
                }
            }

            _swap(begin, pos); // Swap pivot into place
            _quickSort(begin, pos, comp); // Sort the left side of the pivot
            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytesSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getStringSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(string[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for bytes32;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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/strategies/SiloLeverageStrategy.sol": {
      "CommonLib": "0xcb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697",
      "SiloLib": "0x9247f6d0cb46057d26193634d5a9ab8bdc9c3781",
      "StrategyLib": "0xa79909da6a7b1f9ec66fd08074bc7d145de64ccd"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"name":"AlreadyExist","type":"error"},{"inputs":[],"name":"ETHTransferFailed","type":"error"},{"inputs":[],"name":"IncorrectArrayLength","type":"error"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"address[]","name":"expectedAssets_","type":"address[]"}],"name":"IncorrectAssetsList","type":"error"},{"inputs":[],"name":"IncorrectBalance","type":"error"},{"inputs":[],"name":"IncorrectInitParams","type":"error"},{"inputs":[{"internalType":"uint256","name":"ltv","type":"uint256"}],"name":"IncorrectLtv","type":"error"},{"inputs":[],"name":"IncorrectMsgSender","type":"error"},{"inputs":[],"name":"IncorrectZeroArgument","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotExist","type":"error"},{"inputs":[],"name":"NotFactory","type":"error"},{"inputs":[],"name":"NotGovernance","type":"error"},{"inputs":[],"name":"NotGovernanceAndNotMultisig","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NotMultisig","type":"error"},{"inputs":[],"name":"NotOperator","type":"error"},{"inputs":[],"name":"NotPlatform","type":"error"},{"inputs":[],"name":"NotReadyForHardWork","type":"error"},{"inputs":[],"name":"NotTheOwner","type":"error"},{"inputs":[],"name":"NotVault","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"TooLowValue","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"platform","type":"address"},{"indexed":false,"internalType":"uint256","name":"ts","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"block","type":"uint256"}],"name":"ContractInitialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"apr","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"compoundApr","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"earned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tvl","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"duration","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sharePrice","type":"uint256"},{"indexed":false,"internalType":"uint256[]","name":"assetPrices","type":"uint256[]"}],"name":"HardWork","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int256","name":"realApr","type":"int256"},{"indexed":false,"internalType":"int256","name":"earned","type":"int256"},{"indexed":false,"internalType":"uint256","name":"realTvl","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"duration","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"realSharePrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"supplyApr","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"borrowApr","type":"uint256"}],"name":"LeverageLendingHardWork","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ltv","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"leverage","type":"uint256"}],"name":"LeverageLendingHealth","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"","type":"string"}],"name":"SpecificName","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string[]","name":"","type":"string[]"}],"name":"StrategyProtocols","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"TargetLeveragePercent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address[]","name":"addresses","type":"address[]"}],"name":"UniversalAddresses","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256[]","name":"params","type":"uint256[]"}],"name":"UniversalParams","type":"event"},{"inputs":[],"name":"CONTROLLABLE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION_LEVERAGE_LENDING_STRATEGY_BASE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION_STRATEGY_BASE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee0","type":"uint256"},{"internalType":"uint256","name":"fee1","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"name":"algebraFlashCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"assets","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"assetsAmounts","outputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256[]","name":"amounts_","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"autoCompoundingByUnderlyingProtocol","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"createdBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"customPriceImpactTolerance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"depositAssets","outputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositUnderlying","outputs":[{"internalType":"uint256[]","name":"amountsConsumed","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"doHardWork","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"emergencyStopInvesting","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"extra","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"fuseMode","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAssetsProportions","outputs":[{"internalType":"uint256[]","name":"proportions","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getRevenue","outputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getSpecificName","outputs":[{"internalType":"string","name":"","type":"string"},{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getSupplyAndBorrowAprs","outputs":[{"internalType":"uint256","name":"supplyApr","type":"uint256"},{"internalType":"uint256","name":"borrowApr","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUniversalParams","outputs":[{"internalType":"uint256[]","name":"params","type":"uint256[]"},{"internalType":"address[]","name":"addresses","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"health","outputs":[{"internalType":"uint256","name":"ltv","type":"uint256"},{"internalType":"uint256","name":"maxLtv","type":"uint256"},{"internalType":"uint256","name":"leverage","type":"uint256"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"debtAmount","type":"uint256"},{"internalType":"uint256","name":"targetLeveragePercent","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"platform_","type":"address"}],"name":"initVariants","outputs":[{"internalType":"string[]","name":"variants","type":"string[]"},{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"nums","type":"uint256[]"},{"internalType":"int24[]","name":"ticks","type":"int24[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"addresses","type":"address[]"},{"internalType":"uint256[]","name":"nums","type":"uint256[]"},{"internalType":"int24[]","name":"ticks","type":"int24[]"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isHardWorkOnDepositAllowed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"isReadyForHardWork","outputs":[{"internalType":"bool","name":"isReady","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"lastApr","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastAprCompound","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastHardWork","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxDepositAssets","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxWithdrawAssets","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"maxWithdrawAssets","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"platform","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolTvl","outputs":[{"internalType":"uint256","name":"tvlUsd","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256[]","name":"amountsMax","type":"uint256[]"}],"name":"previewDepositAssets","outputs":[{"internalType":"uint256[]","name":"amountsConsumed","type":"uint256[]"},{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256[]","name":"amountsMax","type":"uint256[]"}],"name":"previewDepositAssetsWrite","outputs":[{"internalType":"uint256[]","name":"amountsConsumed","type":"uint256[]"},{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"protocols","outputs":[{"internalType":"string[]","name":"","type":"string[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"realSharePrice","outputs":[{"internalType":"uint256","name":"sharePrice","type":"uint256"},{"internalType":"bool","name":"trusted","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"realTvl","outputs":[{"internalType":"uint256","name":"tvl","type":"uint256"},{"internalType":"bool","name":"trusted","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"newLtv","type":"uint256"},{"internalType":"uint256","name":"minSharePrice","type":"uint256"}],"name":"rebalanceDebt","outputs":[{"internalType":"uint256","name":"resultLtv","type":"uint256"},{"internalType":"uint256","name":"resultSharePrice","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"tokens","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"uint256[]","name":"feeAmounts","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"receiveFlashLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"receiveFlashLoanV3","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"priceImpactTolerance","type":"uint256"}],"name":"setCustomPriceImpactTolerance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string[]","name":"protocols_","type":"string[]"}],"name":"setProtocols","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"specific","type":"string"}],"name":"setSpecificName","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"setTargetLeveragePercent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"params","type":"uint256[]"},{"internalType":"address[]","name":"addresses","type":"address[]"}],"name":"setUniversalParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"strategyLogicId","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"supportedVaultTypes","outputs":[{"internalType":"string[]","name":"types","type":"string[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"total","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"total_","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"transferAssets","outputs":[{"internalType":"uint256[]","name":"amountsOut","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"underlying","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"fee0","type":"uint256"},{"internalType":"uint256","name":"fee1","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"name":"uniswapV3FlashCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"assets_","type":"address[]"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"withdrawAssets","outputs":[{"internalType":"uint256[]","name":"amountsOut","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"withdrawUnderlying","outputs":[],"stateMutability":"nonpayable","type":"function"}]

6080604052348015600e575f5ffd5b5060156019565b60c9565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff161560685760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b039081161460c65780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b615a0f806100d65f395ff3fe608060405234801561000f575f5ffd5b506004361061037d575f3560e01c80637633a22c116101d4578063c1ec4eb411610109578063f1faf050116100a9578063fb2f292711610079578063fb2f29271461075e578063fbfa77cf14610774578063fdff667c1461077c578063ffa1ad7414610784575f5ffd5b8063f1faf05014610726578063f55dd6c11461072e578063f815c4ff14610743578063f985b0bc1461074b575f5ffd5b8063e9cbafb0116100e4578063e9cbafb01461064b578063ead0bc47146106f7578063eb42d0f31461070b578063f04f270714610713575f5ffd5b8063c1ec4eb4146106bf578063c3220045146106d2578063d91c8f65146106da575f5ffd5b8063a2b7722c11610174578063b600585a1161014f578063b600585a14610686578063b6c8cdef146105b7578063b9f5be4114610699578063bd5a7468146106ac575f5ffd5b8063a2b7722c14610638578063a60b0d3c1461064b578063a83473001461065e575f5ffd5b80638c3aefa7116101af5780638c3aefa7146105f3578063936725ec146106015780639736374e146105b757806399f428cf14610625575f5ffd5b80637633a22c146105be57806383ecf653146105f357806389816e30146105fa575f5ffd5b80634bde38c8116102b557806367cf905a116102555780636f307dc3116102255780636f307dc31461059257806371a973051461059a5780637284e416146105af57806374bac429146105b7575f5ffd5b806367cf905a1461054e57806367fde573146105565780636a9085fe1461055e5780636d98943914610571575f5ffd5b80634fa5d854116102905780634fa5d854146104fa57806350f4e4191461050257806359498ab7146105225780635b0f088a1461052a575f5ffd5b80634bde38c8146104b45780634bec0a45146104d45780634d8f1277146104e7575f5ffd5b80632d433b281161032057806341affeb8116102fb57806341affeb81461045e5780634593144c146104715780634875c9681461047957806348d7d9eb146104a2575f5ffd5b80632d433b281461042b5780632ddbd13a1461044e57806341760fe614610456575f5ffd5b8063186663571161035b57806318666357146103c7578063190024e0146103f85780631ec71e051461040057806323a2f9e014610416575f5ffd5b806301ffc9a71461038157806313e63180146103a95780631639ba98146103bf575b5f5ffd5b61039461038f3660046146a9565b6107a8565b60405190151581526020015b60405180910390f35b6103b16107d2565b6040519081526020016103a0565b6103b16107e4565b6103eb60405180604001604052806005815260200164312e322e3360d81b81525081565b6040516103a091906146fe565b6103b16107f6565b61040861089a565b6040516103a0929190614710565b610429610424366004614733565b610b42565b005b61043e61043936600461475e565b610bb5565b6040516103a09493929190614846565b6103b16110c8565b6103b16110da565b61042961046c366004614a31565b6110ec565b6103b161158a565b60408051808201909152600d81526c53696c6f204c6576657261676560981b60208201526103eb565b6060805b6040516103a0929190614b1e565b6104bc6115bd565b6040516001600160a01b0390911681526020016103a0565b6104296104e2366004614b42565b6115ec565b6104296104f5366004614c1a565b61189e565b6104296118f7565b610515610510366004614cc9565b611c29565b6040516103a09190614d1f565b6104a6611c46565b6103eb604051806040016040528060058152602001640c8b8d8b8d60da1b81525081565b610515611cd8565b610429611d24565b61042961056c366004614d31565b611d4e565b61058461057f366004614d85565b611f3f565b6040516103a0929190614dde565b6104bc612044565b6105a261205f565b6040516103a09190614dff565b6103eb6120c8565b6001610394565b6105c661212c565b604080519687526020870195909552938501929092526060840152608083015260a082015260c0016103a0565b6060610515565b5f196103b1565b6103eb60405180604001604052806005815260200164312e302e3160d81b81525081565b610429610633366004614e11565b6121e3565b6103b1610646366004614e3f565b6121f9565b610429610659366004614e70565b612231565b61067161066c366004614eea565b612243565b604080519283526020830191909152016103a0565b610584610694366004614d85565b61246e565b6105156106a7366004614733565b61255b565b6104296106ba366004614733565b61256e565b6104296106cd366004614f0a565b612589565b6106716125da565b6106e2612662565b604080519283529015156020830152016103a0565b610515610705366004614733565b50606090565b6106e2612700565b610429610721366004614f3b565b61270a565b6103b16127dc565b6107366127ee565b6040516103a09190614ff0565b6103b16128cb565b610515610759366004615002565b6128dd565b610766612986565b6040516103a092919061502d565b6104bc612c06565b610736612c1e565b6103eb604051806040016040528060058152602001640645c625c760db1b81525081565b5f6001600160e01b0319821663bc1a547d60e01b14806107cc57506107cc82612c90565b92915050565b5f6107db612cb4565b60020154905090565b5f6107ed612cb4565b60090154905090565b604080516001600160e81b031960208201525f6023820181905282516006818403018152602683019384905263bfe370d960e01b9093529173cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979163bfe370d99161085691602a016146fe565b602060405180830381865af4158015610871573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108959190615051565b905090565b5f5160206159ba5f395f51905f5254604080516379502c5560e01b815290516060925f925f51602061599a5f395f51905f52926001600160a01b0390921691849183916379502c55916004808201926020929091908290030181865afa158015610906573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061092a9190615068565b6001600160a01b031663189e17e46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610965573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109899190615051565b90505f836001015f9054906101000a90046001600160a01b03166001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa1580156109dd573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610a049190810190615083565b600885015460405163dd081d8b60e01b81526001600160a01b038616600482015260248101919091529091505f90739247f6d0cb46057d26193634d5a9ab8bdc9c37819063dd081d8b90604401606060405180830381865af4158015610a6c573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a9091906150f7565b60405163be59b50760e01b81526004810187905290935073cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697925063be59b50791506024015f60405180830381865af4158015610ae2573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610b099190810190615083565b82610b1383612cd8565b604051602001610b2593929190615139565b6040516020818303038152906040525f9650965050505050509091565b610b4a612e21565b7fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f7088190556040518181525f51602061599a5f395f51905f52907f2bdd781a443b30701c9ab6bf87f6cb0d8424bf4f343f2eb4bb49e815193d80d2906020015b60405180910390a15050565b6060806060805f856001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bf8573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c1c9190615068565b6001600160a01b0316639ad87ce4610c5460408051808201909152600d81526c53696c6f204c6576657261676560981b602082015290565b805190602001206040518263ffffffff1660e01b8152600401610c7991815260200190565b5f60405180830381865afa158015610c93573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610cba919081019061522d565b90505f81602001515f81518110610cd357610cd361534f565b60200260200101519050806001600160401b03811115610cf557610cf56148c7565b604051908082528060200260200182016040528015610d2857816020015b6060815260200190600190039081610d135790505b509550610d36816004615377565b6001600160401b03811115610d4d57610d4d6148c7565b604051908082528060200260200182016040528015610d76578160200160208202803683370190505b50604080515f80825260208201818152828401909352929750955093505b818110156110be5782515f90610dab836002615377565b81518110610dbb57610dbb61534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610dfe573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e229190615068565b84519091505f90610e34846002615377565b610e3f90600161538e565b81518110610e4f57610e4f61534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e92573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610eb69190615068565b8551909150610ee990610eca856002615377565b81518110610eda57610eda61534f565b60200260200101518383612eb0565b898481518110610efb57610efb61534f565b60209081029190910101528451610f13846002615377565b81518110610f2357610f2361534f565b602002602001015188846002610f399190615377565b81518110610f4957610f4961534f565b6001600160a01b03909216602092830291909101909101528451610f6e846002615377565b610f7990600161538e565b81518110610f8957610f8961534f565b602002602001015188846002610f9f9190615377565b610faa90600161538e565b81518110610fba57610fba61534f565b6001600160a01b03909216602092830291909101909101528451610fdf846002615377565b610fea90600261538e565b81518110610ffa57610ffa61534f565b6020026020010151888460026110109190615377565b61101b90600261538e565b8151811061102b5761102b61534f565b6001600160a01b03909216602092830291909101909101528451611050846002615377565b61105b90600361538e565b8151811061106b5761106b61534f565b6020026020010151888460026110819190615377565b61108c90600361538e565b8151811061109c5761109c61534f565b6001600160a01b03909216602092830291909101909101525050600101610d94565b5050509193509193565b5f6110d1612cb4565b60010154905090565b5f6110e3612cb4565b600a0154905090565b5f6110f56130d7565b805490915060ff600160401b82041615906001600160401b03165f8115801561111b5750825b90505f826001600160401b031660011480156111365750303b155b905081158015611144575080155b156111625760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561118c57845460ff60401b1916600160401b1785555b8751600614158061119d5750865115155b806111a85750855115155b156111c6576040516363cf6b6160e01b815260040160405180910390fd5b604080516101408101825260608082525f6020830181905292820183905281018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810191909152885f815181106112285761122861534f565b6020908102919091018101516001600160a01b0316908201528851899060019081106112565761125661534f565b60209081029190910101516001600160a01b031660408201528851899060029081106112845761128461534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112c7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112eb9190615068565b6001600160a01b0316606082015288518990600390811061130e5761130e61534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611351573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113759190615068565b6001600160a01b031660808201528851899060029081106113985761139861534f565b60209081029190910101516001600160a01b031660a08201528851899060039081106113c6576113c661534f565b60209081029190910101516001600160a01b031660c08201528851899060049081106113f4576113f461534f565b60209081029190910101516001600160a01b031660e08201528851899060059081106114225761142261534f565b60209081029190910101516001600160a01b03166101008201526121fc61012082015261144e816130ff565b6114758160a001515f1983606001516001600160a01b03166132e99092919063ffffffff16565b61149c8160c001515f1983608001516001600160a01b03166132e99092919063ffffffff16565b5f81602001516001600160a01b0316632b3297f96040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114dd573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115019190615068565b606083015190915061151e906001600160a01b0316825f196132e9565b6080820151611538906001600160a01b0316825f196132e9565b5050831561158057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6108956115b960017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16153a1565b5490565b5f6108956115b960017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66153a1565b6115f4612e21565b5f5f51602061599a5f395f51905f529050825f815181106116175761161761534f565b602002602001015181600901819055508260018151811061163a5761163a61534f565b602002602001015181600a01819055508260028151811061165d5761165d61534f565b602002602001015181600b0181905550826003815181106116805761168061534f565b602002602001015181600c0181905550826004815181106116a3576116a361534f565b602002602001015181600d0181905550826005815181106116c6576116c661534f565b602002602001015181600e0181905550826006815181106116e9576116e961534f565b602002602001015181600f01819055508260078151811061170c5761170c61534f565b602002602001015181601001819055508260088151811061172f5761172f61534f565b60200260200101518160110181905550826009815181106117525761175261534f565b6020026020010151816012018190555082600a815181106117755761177561534f565b6020026020010151816013018190555082600b815181106117985761179861534f565b60200260200101518160150181905550815f815181106117ba576117ba61534f565b6020026020010151816004015f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550816001815181106117fc576117fc61534f565b6020026020010151816014015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055507f108a9433cbd0bc99fd766b6026503c733edf97f6052da62a8c299e2cd9fb73ee8360405161185a9190614d1f565b60405180910390a17f07e5bcb7386028d69cabb7fdefd35ab5253b2a53ce90e0d86f7bea9e979c77ec826040516118919190614dff565b60405180910390a1505050565b6118a6612e21565b5f6118af612cb4565b82519091506118c790600b830190602085019061458f565b507fd319c6758f17094777edee94fbe0651a574464c07a5167e481d19cc2e0acf13382604051610ba99190614ff0565b6118ff61339c565b6119076133cd565b5f611910612cb4565b805460408051637299470360e11b815281519394506001600160a01b03909216925f92849263e5328e06926004808401938290030181865afa158015611958573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061197c91906153c1565b5090508015611c24575f61198e6115bd565b60088501549091505f8080806119a261344a565b93509350935093505f6119b3600190565b611a89576119d38587815181106119cc576119cc61534f565b505f919050565b8487815181106119e5576119e561534f565b602002602001018181516119f9919061538e565b9052506040516308dc79a160e01b81525f9073a79909da6a7b1f9ec66fd08074bc7d145de64ccd906308dc79a190611a3b908b908e908b908b906004016153e5565b5f60405180830381865af4158015611a55573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611a7c919081019061542d565b5050506001890154611baf565b5f611a92611c46565b9150505f86516001600160401b03811115611aaf57611aaf6148c7565b604051908082528060200260200182016040528015611ad8578160200160208202803683370190505b50905063018b82008c6002015442611af091906153a1565b835f81518110611b0257611b0261534f565b6020026020010151611b149190615377565b611b1e9190615472565b815f81518110611b3057611b3061534f565b60209081029190910101526040516336ac731760e11b81526001600160a01b038c1690636d58e62e90611b69908a908590600401614b1e565b5f604051808303815f87803b158015611b80575f5ffd5b505af1158015611b92573d5f5f3e3d5ffd5b50505050611bab875f815181106119cc576119cc61534f565b5050505b60405163640f244560e01b815273a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063640f244590611bf0908d908b908a908a908f908990600401615485565b5f6040518083038186803b158015611c06575f5ffd5b505af4158015611c18573d5f5f3e3d5ffd5b50505050505050505050505b505050565b6060611c3361339c565b611c3e848484613aa1565b949350505050565b606080611c51613aad565b604051633f8b51a560e21b8152919350915073a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063fe2d469490611c8f9085908590600401614b1e565b5f60405180830381865af4158015611ca9573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611cd091908101906154d6565b915091509091565b60408051600180825281830190925260609160208083019080368337019050509050670de0b6b3a7640000815f81518110611d1557611d1561534f565b60200260200101818152505090565b611d2c613b8f565b611d3d611d376110c8565b30613ca9565b506001611d48612cb4565b600a0155565b5f5f51602061599a5f395f51905f526004818101546040516370a0823160e01b81526001600160a01b03918216928101839052929350909185918716906370a0823190602401602060405180830381865afa158015611daf573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dd39190615051565b1015611df257604051631e9acf1760e31b815260040160405180910390fd5b60405163ae63932960e01b81526001600160a01b0386811660048301523060248301526044820186905282169063ae639329906064015f604051808303815f87803b158015611e3f575f5ffd5b505af1158015611e51573d5f5f3e3d5ffd5b50505050739247f6d0cb46057d26193634d5a9ab8bdc9c3781630dcd3d68611e776115bd565b8488885f6040518663ffffffff1660e01b8152600401611e9b95949392919061552f565b5f6040518083038186803b158015611eb1575f5ffd5b505af4158015611ec3573d5f5f3e3d5ffd5b50506040516315afd40960e01b81526001600160a01b03888116600483015260248201889052841692506315afd40991506044016020604051808303815f875af1158015611f13573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f379190615051565b505050505050565b60605f83516001148015611f8b5750611f56612cb4565b6006015484516001600160a01b039091169085905f90611f7857611f7861534f565b60200260200101516001600160a01b0316145b8015611fc257505f6001600160a01b0316845f81518110611fae57611fae61534f565b60200260200101516001600160a01b031614155b1561202e578251600114611fe957604051630ef9926760e21b815260040160405180910390fd5b825f81518110611ffb57611ffb61534f565b60200260200101519050612027835f8151811061201a5761201a61534f565b6020026020010151613d74565b915061203d565b6120388484613d7c565b915091505b9250929050565b5f61204d612cb4565b600601546001600160a01b0316919050565b6060612069612cb4565b6005018054806020026020016040519081016040528092919081815260200182805480156120be57602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116120a0575b5050505050905090565b5f5160206159ba5f395f51905f52545f51602061599a5f395f51905f5280547fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70154606093612126926001600160a01b03918216929082169116612eb0565b91505090565b5f80808080805f51602061599a5f395f51905f52739247f6d0cb46057d26193634d5a9ab8bdc9c3781630f0b05946121626115bd565b6040516001600160e01b031960e084901b1681526001600160a01b0390911660048201526024810184905260440160c060405180830381865af41580156121ab573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121cf9190615563565b949c939b5091995097509550909350915050565b6121eb61339c565b6121f58282613d89565b5050565b5f61220261339c565b5f61220b612cb4565b905080600201545f0361221f574260028201555b61222a836001613e11565b9392505050565b61223d84848484613eae565b50505050565b5f5f5f61224e6115bd565b90505f816001600160a01b031663396656406040518163ffffffff1660e01b8152600401602060405180830381865afa15801561228d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906122b19190615068565b90505f826001600160a01b03166301d22ccd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156122f0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123149190615068565b9050336001600160a01b0382161480159061239257506040516336b87bd760e11b81523360048201526001600160a01b03841690636d70f7ae90602401602060405180830381865afa15801561236c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061239091906155a9565b155b80156124015750604051630e19abf360e01b81523360048201526001600160a01b03831690630e19abf390602401602060405180830381865afa1580156123db573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123ff91906155a9565b155b1561241f576040516370a8bfcd60e11b815260040160405180910390fd5b61242887613f62565b9450612432614007565b5093508386811015612463576040516314715aa160e11b815260040161245a91815260200190565b60405180910390fd5b505050509250929050565b60605f835160011480156124ba5750612485612cb4565b6006015484516001600160a01b039091169085905f906124a7576124a761534f565b60200260200101516001600160a01b0316145b80156124f157505f6001600160a01b0316845f815181106124dd576124dd61534f565b60200260200101516001600160a01b031614155b1561255157825160011461251857604051630ef9926760e21b815260040160405180910390fd5b825f8151811061252a5761252a61534f565b60200260200101519050612027835f815181106125495761254961534f565b506060919050565b61203884846140ac565b606061256561339c565b6107cc826140b8565b612576612e21565b5f61257f612cb4565b6009019190915550565b612591612e21565b5f61259a612cb4565b9050600c81016125aa8382615647565b507fd65900dd44764cfc9d7d6f6a36f82c15f38955a604922fa324ed9516e26e186f82604051610ba991906146fe565b7fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f705545f5160206159ba5f395f51905f52547fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f703545f9283925f51602061599a5f395f51905f5292612659926001600160a01b0390811692811691166140c3565b92509250509091565b5f805f51602061599a5f395f51905f52739247f6d0cb46057d26193634d5a9ab8bdc9c3781635bd923f56126946115bd565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602481018490526044016040805180830381865af41580156126dc573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061265991906153c1565b5f5f611cd0614007565b5f51602061599a5f395f51905f52739247f6d0cb46057d26193634d5a9ab8bdc9c3781630dcd3d6861273a6115bd565b83885f8151811061274d5761274d61534f565b6020026020010151885f815181106127675761276761534f565b6020026020010151885f815181106127815761278161534f565b60200260200101516040518663ffffffff1660e01b81526004016127a995949392919061552f565b5f6040518083038186803b1580156127bf575f5ffd5b505af41580156127d1573d5f5f3e3d5ffd5b505050505050505050565b5f6127e5612cb4565b60040154905090565b60606127f8612cb4565b600b01805480602002602001604051908101604052809291908181526020015f905b828210156128c2578382905f5260205f20018054612837906155c4565b80601f0160208091040260200160405190810160405280929190818152602001828054612863906155c4565b80156128ae5780601f10612885576101008083540402835291602001916128ae565b820191905f5260205f20905b81548152906001019060200180831161289157829003601f168201915b50505050508152602001906001019061281a565b50505050905090565b5f6128d4612cb4565b60030154905090565b60606128e761339c565b73a79909da6a7b1f9ec66fd08074bc7d145de64ccd6325567aef612909612cb4565b6040516001600160e01b031960e084901b168152600481019190915260248101879052604481018690526001600160a01b03851660648201526084015f60405180830381865af415801561295f573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611c3e919081019061542d565b60408051600c8082526101a0820190925260609182915f51602061599a5f395f51905f529160208201610180803683370190505092508060090154835f815181106129d3576129d361534f565b60200260200101818152505080600a0154836001815181106129f7576129f761534f565b60200260200101818152505080600b015483600281518110612a1b57612a1b61534f565b60200260200101818152505080600c015483600381518110612a3f57612a3f61534f565b60200260200101818152505080600d015483600481518110612a6357612a6361534f565b60200260200101818152505080600e015483600581518110612a8757612a8761534f565b60200260200101818152505080600f015483600681518110612aab57612aab61534f565b602002602001018181525050806010015483600781518110612acf57612acf61534f565b602002602001018181525050806011015483600881518110612af357612af361534f565b602002602001018181525050806012015483600981518110612b1757612b1761534f565b602002602001018181525050806013015483600a81518110612b3b57612b3b61534f565b602002602001018181525050806015015483600b81518110612b5f57612b5f61534f565b60209081029190910101526040805160028082526060820190925290816020016020820280368337505050600482015481519193506001600160a01b03169083905f90612bae57612bae61534f565b6001600160a01b0392831660209182029290920101526014820154835191169083906001908110612be157612be161534f565b60200260200101906001600160a01b031690816001600160a01b031681525050509091565b5f612c0f612cb4565b546001600160a01b0316919050565b604080516001808252818301909252606091816020015b6060815260200190600190039081612c355790505090506040518060400160405280600b81526020016a436f6d706f756e64696e6760a81b815250815f81518110612c8257612c8261534f565b602002602001018190525090565b5f6001600160e01b03198216637a2a253160e01b14806107cc57506107cc826141e9565b7fb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba0090565b60605f612ce761271084615472565b90505f6103e8612cf983612710615377565b612d0390866153a1565b612d0d9190615472565b60405163be59b50760e01b81526004810184905290915073cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979063be59b507906024015f60405180830381865af4158015612d5d573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612d849190810190615083565b60405163be59b50760e01b81526004810183905273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979063be59b507906024015f60405180830381865af4158015612dd1573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612df89190810190615083565b604051602001612e09929190615701565b60405160208183030381529060405292505050919050565b612e296115bd565b6040516336b87bd760e11b81523360048201526001600160a01b039190911690636d70f7ae90602401602060405180830381865afa158015612e6d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e9191906155a9565b612eae57604051631f0853c160e21b815260040160405180910390fd5b565b60605f846001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612eef573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f139190615068565b6001600160a01b031663189e17e46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612f4e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f729190615051565b9050836001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015612faf573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612fd69190810190615083565b836001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015613011573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526130389190810190615083565b60405163be59b50760e01b81526004810184905273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979063be59b507906024015f60405180830381865af4158015613085573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526130ac9190810190615083565b6040516020016130be9392919061572a565b6040516020818303038152906040529150509392505050565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a006107cc565b61310761421d565b60608101515f51602061599a5f395f51905f5280546001600160a01b03199081166001600160a01b0393841617825560808401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f7018054831691851691909117905560a08401515f5160206159ba5f395f51905f528054831691851691909117905560c08401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f7038054831691851691909117905560e08401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f704805483169185169190911790556101008401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70580549092169316929092179091556101208201517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70881905560408051918252517f2bdd781a443b30701c9ab6bf87f6cb0d8424bf4f343f2eb4bb49e815193d80d2916020908290030190a16040805160018082528183019092525f91602080830190803683370190505090508260600151815f815181106132b9576132b961534f565b6001600160a01b0390921660209283029190910182015283015183516040850151611c24929190845f5f19614242565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261333a84826142e6565b61223d57604080516001600160a01b03851660248201525f6044808301919091528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261339290859061432f565b61223d848261432f565b6133a4612cb4565b546001600160a01b03163314612eae576040516362df054560e01b815260040160405180910390fd5b306001600160a01b03166374bac4296040518163ffffffff1660e01b8152600401602060405180830381865afa158015613409573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061342d91906155a9565b612eae576040516309ea311f60e11b815260040160405180910390fd5b60608060608061345861205f565b604080515f80825260208083019182526001838501818152608085019095529498509195509350909190606085019080368337505060408051608080820183525f80835260208084018290528385018290526060938401829052845192830185525f51602061599a5f395f51905f5280546001600160a01b0390811685527fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f701548116928501929092525f5160206159ba5f395f51905f52548216958401959095527fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70354169282019290925293965090929150613552612cb4565b90505f8160010154905082604001516001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303815f875af115801561359d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135c19190615051565b5082606001516001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303815f875af1158015613603573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136279190615051565b506040805163f91afc8760e01b815284516001600160a01b0390811660048301526020860151811660248301529185015182166044820152606085015190911660648201525f90739247f6d0cb46057d26193634d5a9ab8bdc9c37819063f91afc8790608401602060405180830381865af41580156136a8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136cc9190615051565b845160405163e3d670d760e01b81526001600160a01b03909116600482015273a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063e3d670d790602401602060405180830381865af4158015613725573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137499190615051565b613753919061538e565b9050818111156137865761376782826153a1565b885f815181106137795761377961534f565b6020026020010181815250505b600183018190555f61379883836157b5565b90505f6137a3612662565b5090505f8560020154426137b791906153a1565b90505f6137c26115bd565b6001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137fd573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138219190615068565b88516040516341976e0960e01b81526001600160a01b0391821660048201529192505f91908316906341976e09906024016040805180830381865afa15801561386c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061389091906153c1565b5090505f895f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138d3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138f791906157db565b61390290600a6158de565b61390c83886158ec565b613916919061591b565b6040516377d6938160e11b81526004810187905260248101829052604481018690529091505f9073a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063efad270290606401602060405180830381865af4158015613977573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061399b9190615051565b90505f5f6139c88e6005015f9054906101000a90046001600160a01b03168e604001518f606001516140c3565b915091505f6139d5614007565b5060408051868152602081018d90529081018b9052606081018a90526080810182905260a0810185905260c081018490529091507f55b344f7779d44f14b50a9ae3eb0959de12c0956ec73aeddb89c62c0bfce3aad9060e00160405180910390a1505050505050505050505f5f613a4a61212c565b50505092505091507fb83dc6ff11ec1f33d17651f75f3998b69e170ade8f9072b116beaa5e6d037e1e8282604051613a8c929190918252602082015260400190565b60405180910390a15050505050505090919293565b6060611c3e8383613ca9565b606080613ab861205f565b604080516001808252818301909252919350602080830190803683370190505090505f5f51602061599a5f395f51905f526002810154604051633f02cd9160e11b81526001600160a01b039091166004820152909150739247f6d0cb46057d26193634d5a9ab8bdc9c378190637e059b2290602401602060405180830381865af4158015613b48573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b6c9190615051565b825f81518110613b7e57613b7e61534f565b602002602001018181525050509091565b5f613b986115bd565b9050336001600160a01b0316816001600160a01b0316635aa6e6756040518163ffffffff1660e01b8152600401602060405180830381865afa158015613be0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c049190615068565b6001600160a01b03161480613c895750336001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613c5a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c7e9190615068565b6001600160a01b0316145b613ca6576040516354299b6f60e01b815260040160405180910390fd5b50565b60605f51602061599a5f395f51905f525f613cc2612cb4565b9050739247f6d0cb46057d26193634d5a9ab8bdc9c37816357477647613ce66115bd565b6040516001600160e01b031960e084901b1681526001600160a01b039182166004820152602481018690526044810185905260648101899052908716608482015260a4015f60405180830381865af4158015613d44573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613d6b919081019061542d565b95945050505050565b6060806107cc565b60605f61203884846140ac565b5f613d92612cb4565b600601546001600160a01b031614613dd1576040518060400160405280600f81526020016e1b9bdd081a5b5c1b195b595b9d1959608a1b815250613df8565b6040518060400160405280600d81526020016c6e6f20756e6465726c79696e6760981b8152505b60405162461bcd60e51b815260040161245a91906146fe565b5f5f51602061599a5f395f51905f5281613e29612cb4565b9050739247f6d0cb46057d26193634d5a9ab8bdc9c378163f1d7a9938383613e4f61205f565b896040518563ffffffff1660e01b8152600401613e6f9493929190615947565b602060405180830381865af4158015613e8a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613d6b9190615051565b5f8080613ebd84860186615965565b9250925092505f613ed85f51602061599a5f395f51905f5290565b9050739247f6d0cb46057d26193634d5a9ab8bdc9c3781630dcd3d68613efc6115bd565b83878787613f0a578c613f0c565b8d5b6040518663ffffffff1660e01b8152600401613f2c95949392919061552f565b5f6040518083038186803b158015613f42575f5ffd5b505af4158015613f54573d5f5f3e3d5ffd5b505050505050505050505050565b5f739247f6d0cb46057d26193634d5a9ab8bdc9c378163b86c2a78613f856115bd565b845f51602061599a5f395f51905f526040516001600160e01b031960e086901b1681526001600160a01b03909316600484015260248301919091526044820152606401602060405180830381865af4158015613fe3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107cc9190615051565b5f5f5f614012612662565b925090505f61401f612c06565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561405a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061407e9190615051565b905080156140a6578061409983670de0b6b3a7640000615377565b6140a39190615472565b93505b50509091565b60605f6120388361439b565b60605f613d92612cb4565b6040516327b52bdb60e11b81526001600160a01b0383811660048301525f918291670de0b6b3a764000091620186a091881690634f6a57b690602401602060405180830381865afa15801561411a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061413e9190615051565b6141489190615377565b6141529190615472565b604051620707bd60e51b81526001600160a01b038581166004830152919350670de0b6b3a764000091620186a0919088169062e0f7a090602401602060405180830381865afa1580156141a7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906141cb9190615051565b6141d59190615377565b6141df9190615472565b9050935093915050565b5f6001600160e01b03198216630f1ec81f60e41b14806107cc57506301ffc9a760e01b6001600160e01b03198316146107cc565b614225614419565b612eae57604051631afcd79f60e31b815260040160405180910390fd5b61424a61421d565b61425386614432565b5f61425c612cb4565b600881018390556006810180546001600160a01b0319166001600160a01b03861617905584519091508690869086908690869060078701905f90889082906142ad90600584019060208a01906145e3565b5081546001600160a01b03808a166101009390930a92830292021916179055506142d78682615647565b50505050505050505050505050565b5f5f5f5f60205f8651602088015f8a5af192503d91505f519050828015614325575081156143175780600114614325565b5f866001600160a01b03163b115b9695505050505050565b5f5f60205f8451602086015f885af18061434e576040513d5f823e3d81fd5b50505f513d91508115614365578060011415614372565b6001600160a01b0384163b155b1561223d57604051635274afe760e01b81526001600160a01b038516600482015260240161245a565b6040805160018082528183019092526060915f919060208083019080368337019050509150825f815181106143d2576143d261534f565b6020026020010151825f815181106143ec576143ec61534f565b602002602001018181525050815f8151811061440a5761440a61534f565b60200260200101519050915091565b5f6144226130d7565b54600160401b900460ff16919050565b61443a61421d565b6001600160a01b038116158015906144c357505f6001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015614493573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906144b79190615068565b6001600160a01b031614155b6144e0576040516371c42ac360e01b815260040160405180910390fd5b61451361450e60017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66153a1565b829055565b6145454361454260017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16153a1565b55565b604080516001600160a01b0383168152426020820152438183015290517f1a2dd071001ebf6e03174e3df5b305795a4ad5d41d8fdb9ba41dbbe2367134269181900360600190a150565b828054828255905f5260205f209081019282156145d3579160200282015b828111156145d357825182906145c39082615647565b50916020019190600101906145ad565b506145df929150614642565b5090565b828054828255905f5260205f20908101928215614636579160200282015b8281111561463657825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190614601565b506145df92915061465e565b808211156145df575f6146558282614672565b50600101614642565b5b808211156145df575f815560010161465f565b50805461467e906155c4565b5f825580601f1061468d575050565b601f0160209004905f5260205f2090810190613ca6919061465e565b5f602082840312156146b9575f5ffd5b81356001600160e01b03198116811461222a575f5ffd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f61222a60208301846146d0565b604081525f61472260408301856146d0565b905082151560208301529392505050565b5f60208284031215614743575f5ffd5b5035919050565b6001600160a01b0381168114613ca6575f5ffd5b5f6020828403121561476e575f5ffd5b813561222a8161474a565b5f82825180855260208501945060208160051b830101602085015f5b838110156147c757601f198584030188526147b18383516146d0565b6020988901989093509190910190600101614795565b50909695505050505050565b5f8151808452602084019350602083015f5b8281101561480c5781516001600160a01b03168652602095860195909101906001016147e5565b5093949350505050565b5f8151808452602084019350602083015f5b8281101561480c578151865260209586019590910190600101614828565b608081525f6148586080830187614779565b828103602084015261486a81876147d3565b9050828103604084015261487e8186614816565b8381036060850152845180825260208087019350909101905f5b818110156148b957835160020b835260209384019390920191600101614898565b509098975050505050505050565b634e487b7160e01b5f52604160045260245ffd5b604051606081016001600160401b03811182821017156148fd576148fd6148c7565b60405290565b604051601f8201601f191681016001600160401b038111828210171561492b5761492b6148c7565b604052919050565b5f6001600160401b0382111561494b5761494b6148c7565b5060051b60200190565b5f82601f830112614964575f5ffd5b813561497761497282614933565b614903565b8082825260208201915060208360051b860101925085831115614998575f5ffd5b602085015b838110156149be5780356149b08161474a565b83526020928301920161499d565b5095945050505050565b5f82601f8301126149d7575f5ffd5b81356149e561497282614933565b8082825260208201915060208360051b860101925085831115614a06575f5ffd5b602085015b838110156149be578035835260209283019201614a0b565b8060020b8114613ca6575f5ffd5b5f5f5f60608486031215614a43575f5ffd5b83356001600160401b03811115614a58575f5ffd5b614a6486828701614955565b93505060208401356001600160401b03811115614a7f575f5ffd5b614a8b868287016149c8565b92505060408401356001600160401b03811115614aa6575f5ffd5b8401601f81018613614ab6575f5ffd5b8035614ac461497282614933565b8082825260208201915060208360051b850101925088831115614ae5575f5ffd5b6020840193505b82841015614b10578335614aff81614a23565b825260209384019390910190614aec565b809450505050509250925092565b604081525f614b3060408301856147d3565b8281036020840152613d6b8185614816565b5f5f60408385031215614b53575f5ffd5b82356001600160401b03811115614b68575f5ffd5b614b74858286016149c8565b92505060208301356001600160401b03811115614b8f575f5ffd5b614b9b85828601614955565b9150509250929050565b5f6001600160401b03821115614bbd57614bbd6148c7565b50601f01601f191660200190565b5f82601f830112614bda575f5ffd5b8135602083015f614bed61497284614ba5565b9050828152858383011115614c00575f5ffd5b828260208301375f92810160200192909252509392505050565b5f60208284031215614c2a575f5ffd5b81356001600160401b03811115614c3f575f5ffd5b8201601f81018413614c4f575f5ffd5b8035614c5d61497282614933565b8082825260208201915060208360051b850101925086831115614c7e575f5ffd5b602084015b83811015614cbe5780356001600160401b03811115614ca0575f5ffd5b614caf89602083890101614bcb565b84525060209283019201614c83565b509695505050505050565b5f5f5f60608486031215614cdb575f5ffd5b83356001600160401b03811115614cf0575f5ffd5b614cfc86828701614955565b935050602084013591506040840135614d148161474a565b809150509250925092565b602081525f61222a6020830184614816565b5f5f5f60608486031215614d43575f5ffd5b8335614d4e8161474a565b92506020840135915060408401356001600160401b03811115614d6f575f5ffd5b614d7b86828701614bcb565b9150509250925092565b5f5f60408385031215614d96575f5ffd5b82356001600160401b03811115614dab575f5ffd5b614db785828601614955565b92505060208301356001600160401b03811115614dd2575f5ffd5b614b9b858286016149c8565b604081525f614df06040830185614816565b90508260208301529392505050565b602081525f61222a60208301846147d3565b5f5f60408385031215614e22575f5ffd5b823591506020830135614e348161474a565b809150509250929050565b5f60208284031215614e4f575f5ffd5b81356001600160401b03811115614e64575f5ffd5b611c3e848285016149c8565b5f5f5f5f60608587031215614e83575f5ffd5b843593506020850135925060408501356001600160401b03811115614ea6575f5ffd5b8501601f81018713614eb6575f5ffd5b80356001600160401b03811115614ecb575f5ffd5b876020828401011115614edc575f5ffd5b949793965060200194505050565b5f5f60408385031215614efb575f5ffd5b50508035926020909101359150565b5f60208284031215614f1a575f5ffd5b81356001600160401b03811115614f2f575f5ffd5b611c3e84828501614bcb565b5f5f5f5f60808587031215614f4e575f5ffd5b84356001600160401b03811115614f63575f5ffd5b614f6f87828801614955565b94505060208501356001600160401b03811115614f8a575f5ffd5b614f96878288016149c8565b93505060408501356001600160401b03811115614fb1575f5ffd5b614fbd878288016149c8565b92505060608501356001600160401b03811115614fd8575f5ffd5b614fe487828801614bcb565b91505092959194509250565b602081525f61222a6020830184614779565b5f5f5f60608486031215615014575f5ffd5b83359250602084013591506040840135614d148161474a565b604081525f61503f6040830185614816565b8281036020840152613d6b81856147d3565b5f60208284031215615061575f5ffd5b5051919050565b5f60208284031215615078575f5ffd5b815161222a8161474a565b5f60208284031215615093575f5ffd5b81516001600160401b038111156150a8575f5ffd5b8201601f810184136150b8575f5ffd5b80516150c661497282614ba5565b8181528560208385010111156150da575f5ffd5b8160208401602083015e5f91810160200191909152949350505050565b5f5f5f60608486031215615109575f5ffd5b5050815160208301516040909301519094929350919050565b5f81518060208401855e5f93019283525090919050565b5f6151448286615122565b600160fd1b81526151586001820186615122565b9050600160fd1b81526143256001820185615122565b5f82601f83011261517d575f5ffd5b815161518b61497282614933565b8082825260208201915060208360051b8601019250858311156151ac575f5ffd5b602085015b838110156149be5780516151c48161474a565b8352602092830192016151b1565b5f82601f8301126151e1575f5ffd5b81516151ef61497282614933565b8082825260208201915060208360051b860101925085831115615210575f5ffd5b602085015b838110156149be578051835260209283019201615215565b5f6020828403121561523d575f5ffd5b81516001600160401b03811115615252575f5ffd5b820160608185031215615263575f5ffd5b61526b6148db565b81516001600160401b03811115615280575f5ffd5b61528c8682850161516e565b82525060208201516001600160401b038111156152a7575f5ffd5b6152b3868285016151d2565b60208301525060408201516001600160401b038111156152d1575f5ffd5b80830192505084601f8301126152e5575f5ffd5b81516152f361497282614933565b8082825260208201915060208360051b860101925087831115615314575f5ffd5b6020850194505b8285101561533f57845161532e81614a23565b82526020948501949091019061531b565b6040840152509095945050505050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176107cc576107cc615363565b808201808211156107cc576107cc615363565b818103818111156107cc576107cc615363565b8015158114613ca6575f5ffd5b5f5f604083850312156153d2575f5ffd5b82516020840151909250614e34816153b4565b6001600160a01b038581168252841660208201526080604082018190525f90615410908301856147d3565b82810360608401526154228185614816565b979650505050505050565b5f6020828403121561543d575f5ffd5b81516001600160401b03811115615452575f5ffd5b611c3e848285016151d2565b634e487b7160e01b5f52601260045260245ffd5b5f826154805761548061545e565b500490565b8681526001600160a01b038616602082015260c0604082018190525f906154ae908301876147d3565b82810360608401526154c08187614816565b6080840195909552505060a00152949350505050565b5f5f604083850312156154e7575f5ffd5b82516001600160401b038111156154fc575f5ffd5b6155088582860161516e565b92505060208301516001600160401b03811115615523575f5ffd5b614b9b858286016151d2565b6001600160a01b03958616815260208101949094529190931660408301526060820192909252608081019190915260a00190565b5f5f5f5f5f5f60c08789031215615578575f5ffd5b50508451602086015160408701516060880151608089015160a090990151939a929950909790965094509092509050565b5f602082840312156155b9575f5ffd5b815161222a816153b4565b600181811c908216806155d857607f821691505b6020821081036155f657634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115611c2457805f5260205f20601f840160051c810160208510156156215750805b601f840160051c820191505b81811015615640575f815560010161562d565b5050505050565b81516001600160401b03811115615660576156606148c7565b6156748161566e84546155c4565b846155fc565b6020601f8211600181146156a6575f831561568f5750848201515b5f19600385901b1c1916600184901b178455615640565b5f84815260208120601f198516915b828110156156d557878501518255602094850194600190920191016156b5565b50848210156156f257868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b600f60fb1b81525f6157166001830185615122565b601760f91b8152613d6b6001820185615122565b66029bab838363c960cd1b81525f6157456007830186615122565b6b01030b732103137b93937bb960a51b8152615764600c820186615122565b90507201037b71029b4b637902b191036b0b935b2ba1606d1b815261578c6013820185615122565b752077697468206c65766572616765206c6f6f70696e6760501b81526016019695505050505050565b8181035f8312801583831316838312821617156157d4576157d4615363565b5092915050565b5f602082840312156157eb575f5ffd5b815160ff8116811461222a575f5ffd5b6001815b60018411156158365780850481111561581a5761581a615363565b600184161561582857908102905b60019390931c9280026157ff565b935093915050565b5f8261584c575060016107cc565b8161585857505f6107cc565b816001811461586e576002811461587857615894565b60019150506107cc565b60ff84111561588957615889615363565b50506001821b6107cc565b5060208310610133831016604e8410600b84101617156158b7575081810a6107cc565b6158c35f1984846157fb565b805f19048211156158d6576158d6615363565b029392505050565b5f61222a60ff84168361583e565b8082025f8212600160ff1b8414161561590757615907615363565b81810583148215176107cc576107cc615363565b5f826159295761592961545e565b600160ff1b82145f198414161561594257615942615363565b500590565b848152836020820152608060408201525f61541060808301856147d3565b5f5f5f60608486031215615977575f5ffd5b83356159828161474a565b9250602084013591506040840135614d14816153b456febcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f700bcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f702a264697066735822122096c872ca507f62e4d57a7ed0c6505978f2f4dfc555d3a84f589186b84390cdab64736f6c634300081c0033

Deployed Bytecode

0x608060405234801561000f575f5ffd5b506004361061037d575f3560e01c80637633a22c116101d4578063c1ec4eb411610109578063f1faf050116100a9578063fb2f292711610079578063fb2f29271461075e578063fbfa77cf14610774578063fdff667c1461077c578063ffa1ad7414610784575f5ffd5b8063f1faf05014610726578063f55dd6c11461072e578063f815c4ff14610743578063f985b0bc1461074b575f5ffd5b8063e9cbafb0116100e4578063e9cbafb01461064b578063ead0bc47146106f7578063eb42d0f31461070b578063f04f270714610713575f5ffd5b8063c1ec4eb4146106bf578063c3220045146106d2578063d91c8f65146106da575f5ffd5b8063a2b7722c11610174578063b600585a1161014f578063b600585a14610686578063b6c8cdef146105b7578063b9f5be4114610699578063bd5a7468146106ac575f5ffd5b8063a2b7722c14610638578063a60b0d3c1461064b578063a83473001461065e575f5ffd5b80638c3aefa7116101af5780638c3aefa7146105f3578063936725ec146106015780639736374e146105b757806399f428cf14610625575f5ffd5b80637633a22c146105be57806383ecf653146105f357806389816e30146105fa575f5ffd5b80634bde38c8116102b557806367cf905a116102555780636f307dc3116102255780636f307dc31461059257806371a973051461059a5780637284e416146105af57806374bac429146105b7575f5ffd5b806367cf905a1461054e57806367fde573146105565780636a9085fe1461055e5780636d98943914610571575f5ffd5b80634fa5d854116102905780634fa5d854146104fa57806350f4e4191461050257806359498ab7146105225780635b0f088a1461052a575f5ffd5b80634bde38c8146104b45780634bec0a45146104d45780634d8f1277146104e7575f5ffd5b80632d433b281161032057806341affeb8116102fb57806341affeb81461045e5780634593144c146104715780634875c9681461047957806348d7d9eb146104a2575f5ffd5b80632d433b281461042b5780632ddbd13a1461044e57806341760fe614610456575f5ffd5b8063186663571161035b57806318666357146103c7578063190024e0146103f85780631ec71e051461040057806323a2f9e014610416575f5ffd5b806301ffc9a71461038157806313e63180146103a95780631639ba98146103bf575b5f5ffd5b61039461038f3660046146a9565b6107a8565b60405190151581526020015b60405180910390f35b6103b16107d2565b6040519081526020016103a0565b6103b16107e4565b6103eb60405180604001604052806005815260200164312e322e3360d81b81525081565b6040516103a091906146fe565b6103b16107f6565b61040861089a565b6040516103a0929190614710565b610429610424366004614733565b610b42565b005b61043e61043936600461475e565b610bb5565b6040516103a09493929190614846565b6103b16110c8565b6103b16110da565b61042961046c366004614a31565b6110ec565b6103b161158a565b60408051808201909152600d81526c53696c6f204c6576657261676560981b60208201526103eb565b6060805b6040516103a0929190614b1e565b6104bc6115bd565b6040516001600160a01b0390911681526020016103a0565b6104296104e2366004614b42565b6115ec565b6104296104f5366004614c1a565b61189e565b6104296118f7565b610515610510366004614cc9565b611c29565b6040516103a09190614d1f565b6104a6611c46565b6103eb604051806040016040528060058152602001640c8b8d8b8d60da1b81525081565b610515611cd8565b610429611d24565b61042961056c366004614d31565b611d4e565b61058461057f366004614d85565b611f3f565b6040516103a0929190614dde565b6104bc612044565b6105a261205f565b6040516103a09190614dff565b6103eb6120c8565b6001610394565b6105c661212c565b604080519687526020870195909552938501929092526060840152608083015260a082015260c0016103a0565b6060610515565b5f196103b1565b6103eb60405180604001604052806005815260200164312e302e3160d81b81525081565b610429610633366004614e11565b6121e3565b6103b1610646366004614e3f565b6121f9565b610429610659366004614e70565b612231565b61067161066c366004614eea565b612243565b604080519283526020830191909152016103a0565b610584610694366004614d85565b61246e565b6105156106a7366004614733565b61255b565b6104296106ba366004614733565b61256e565b6104296106cd366004614f0a565b612589565b6106716125da565b6106e2612662565b604080519283529015156020830152016103a0565b610515610705366004614733565b50606090565b6106e2612700565b610429610721366004614f3b565b61270a565b6103b16127dc565b6107366127ee565b6040516103a09190614ff0565b6103b16128cb565b610515610759366004615002565b6128dd565b610766612986565b6040516103a092919061502d565b6104bc612c06565b610736612c1e565b6103eb604051806040016040528060058152602001640645c625c760db1b81525081565b5f6001600160e01b0319821663bc1a547d60e01b14806107cc57506107cc82612c90565b92915050565b5f6107db612cb4565b60020154905090565b5f6107ed612cb4565b60090154905090565b604080516001600160e81b031960208201525f6023820181905282516006818403018152602683019384905263bfe370d960e01b9093529173cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979163bfe370d99161085691602a016146fe565b602060405180830381865af4158015610871573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108959190615051565b905090565b5f5160206159ba5f395f51905f5254604080516379502c5560e01b815290516060925f925f51602061599a5f395f51905f52926001600160a01b0390921691849183916379502c55916004808201926020929091908290030181865afa158015610906573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061092a9190615068565b6001600160a01b031663189e17e46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610965573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109899190615051565b90505f836001015f9054906101000a90046001600160a01b03166001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa1580156109dd573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610a049190810190615083565b600885015460405163dd081d8b60e01b81526001600160a01b038616600482015260248101919091529091505f90739247f6d0cb46057d26193634d5a9ab8bdc9c37819063dd081d8b90604401606060405180830381865af4158015610a6c573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a9091906150f7565b60405163be59b50760e01b81526004810187905290935073cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee697925063be59b50791506024015f60405180830381865af4158015610ae2573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610b099190810190615083565b82610b1383612cd8565b604051602001610b2593929190615139565b6040516020818303038152906040525f9650965050505050509091565b610b4a612e21565b7fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f7088190556040518181525f51602061599a5f395f51905f52907f2bdd781a443b30701c9ab6bf87f6cb0d8424bf4f343f2eb4bb49e815193d80d2906020015b60405180910390a15050565b6060806060805f856001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bf8573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c1c9190615068565b6001600160a01b0316639ad87ce4610c5460408051808201909152600d81526c53696c6f204c6576657261676560981b602082015290565b805190602001206040518263ffffffff1660e01b8152600401610c7991815260200190565b5f60405180830381865afa158015610c93573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610cba919081019061522d565b90505f81602001515f81518110610cd357610cd361534f565b60200260200101519050806001600160401b03811115610cf557610cf56148c7565b604051908082528060200260200182016040528015610d2857816020015b6060815260200190600190039081610d135790505b509550610d36816004615377565b6001600160401b03811115610d4d57610d4d6148c7565b604051908082528060200260200182016040528015610d76578160200160208202803683370190505b50604080515f80825260208201818152828401909352929750955093505b818110156110be5782515f90610dab836002615377565b81518110610dbb57610dbb61534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610dfe573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e229190615068565b84519091505f90610e34846002615377565b610e3f90600161538e565b81518110610e4f57610e4f61534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e92573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610eb69190615068565b8551909150610ee990610eca856002615377565b81518110610eda57610eda61534f565b60200260200101518383612eb0565b898481518110610efb57610efb61534f565b60209081029190910101528451610f13846002615377565b81518110610f2357610f2361534f565b602002602001015188846002610f399190615377565b81518110610f4957610f4961534f565b6001600160a01b03909216602092830291909101909101528451610f6e846002615377565b610f7990600161538e565b81518110610f8957610f8961534f565b602002602001015188846002610f9f9190615377565b610faa90600161538e565b81518110610fba57610fba61534f565b6001600160a01b03909216602092830291909101909101528451610fdf846002615377565b610fea90600261538e565b81518110610ffa57610ffa61534f565b6020026020010151888460026110109190615377565b61101b90600261538e565b8151811061102b5761102b61534f565b6001600160a01b03909216602092830291909101909101528451611050846002615377565b61105b90600361538e565b8151811061106b5761106b61534f565b6020026020010151888460026110819190615377565b61108c90600361538e565b8151811061109c5761109c61534f565b6001600160a01b03909216602092830291909101909101525050600101610d94565b5050509193509193565b5f6110d1612cb4565b60010154905090565b5f6110e3612cb4565b600a0154905090565b5f6110f56130d7565b805490915060ff600160401b82041615906001600160401b03165f8115801561111b5750825b90505f826001600160401b031660011480156111365750303b155b905081158015611144575080155b156111625760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561118c57845460ff60401b1916600160401b1785555b8751600614158061119d5750865115155b806111a85750855115155b156111c6576040516363cf6b6160e01b815260040160405180910390fd5b604080516101408101825260608082525f6020830181905292820183905281018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810191909152885f815181106112285761122861534f565b6020908102919091018101516001600160a01b0316908201528851899060019081106112565761125661534f565b60209081029190910101516001600160a01b031660408201528851899060029081106112845761128461534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112c7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112eb9190615068565b6001600160a01b0316606082015288518990600390811061130e5761130e61534f565b60200260200101516001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611351573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113759190615068565b6001600160a01b031660808201528851899060029081106113985761139861534f565b60209081029190910101516001600160a01b031660a08201528851899060039081106113c6576113c661534f565b60209081029190910101516001600160a01b031660c08201528851899060049081106113f4576113f461534f565b60209081029190910101516001600160a01b031660e08201528851899060059081106114225761142261534f565b60209081029190910101516001600160a01b03166101008201526121fc61012082015261144e816130ff565b6114758160a001515f1983606001516001600160a01b03166132e99092919063ffffffff16565b61149c8160c001515f1983608001516001600160a01b03166132e99092919063ffffffff16565b5f81602001516001600160a01b0316632b3297f96040518163ffffffff1660e01b8152600401602060405180830381865afa1580156114dd573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115019190615068565b606083015190915061151e906001600160a01b0316825f196132e9565b6080820151611538906001600160a01b0316825f196132e9565b5050831561158057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b5050505050505050565b5f6108956115b960017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16153a1565b5490565b5f6108956115b960017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66153a1565b6115f4612e21565b5f5f51602061599a5f395f51905f529050825f815181106116175761161761534f565b602002602001015181600901819055508260018151811061163a5761163a61534f565b602002602001015181600a01819055508260028151811061165d5761165d61534f565b602002602001015181600b0181905550826003815181106116805761168061534f565b602002602001015181600c0181905550826004815181106116a3576116a361534f565b602002602001015181600d0181905550826005815181106116c6576116c661534f565b602002602001015181600e0181905550826006815181106116e9576116e961534f565b602002602001015181600f01819055508260078151811061170c5761170c61534f565b602002602001015181601001819055508260088151811061172f5761172f61534f565b60200260200101518160110181905550826009815181106117525761175261534f565b6020026020010151816012018190555082600a815181106117755761177561534f565b6020026020010151816013018190555082600b815181106117985761179861534f565b60200260200101518160150181905550815f815181106117ba576117ba61534f565b6020026020010151816004015f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550816001815181106117fc576117fc61534f565b6020026020010151816014015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055507f108a9433cbd0bc99fd766b6026503c733edf97f6052da62a8c299e2cd9fb73ee8360405161185a9190614d1f565b60405180910390a17f07e5bcb7386028d69cabb7fdefd35ab5253b2a53ce90e0d86f7bea9e979c77ec826040516118919190614dff565b60405180910390a1505050565b6118a6612e21565b5f6118af612cb4565b82519091506118c790600b830190602085019061458f565b507fd319c6758f17094777edee94fbe0651a574464c07a5167e481d19cc2e0acf13382604051610ba99190614ff0565b6118ff61339c565b6119076133cd565b5f611910612cb4565b805460408051637299470360e11b815281519394506001600160a01b03909216925f92849263e5328e06926004808401938290030181865afa158015611958573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061197c91906153c1565b5090508015611c24575f61198e6115bd565b60088501549091505f8080806119a261344a565b93509350935093505f6119b3600190565b611a89576119d38587815181106119cc576119cc61534f565b505f919050565b8487815181106119e5576119e561534f565b602002602001018181516119f9919061538e565b9052506040516308dc79a160e01b81525f9073a79909da6a7b1f9ec66fd08074bc7d145de64ccd906308dc79a190611a3b908b908e908b908b906004016153e5565b5f60405180830381865af4158015611a55573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611a7c919081019061542d565b5050506001890154611baf565b5f611a92611c46565b9150505f86516001600160401b03811115611aaf57611aaf6148c7565b604051908082528060200260200182016040528015611ad8578160200160208202803683370190505b50905063018b82008c6002015442611af091906153a1565b835f81518110611b0257611b0261534f565b6020026020010151611b149190615377565b611b1e9190615472565b815f81518110611b3057611b3061534f565b60209081029190910101526040516336ac731760e11b81526001600160a01b038c1690636d58e62e90611b69908a908590600401614b1e565b5f604051808303815f87803b158015611b80575f5ffd5b505af1158015611b92573d5f5f3e3d5ffd5b50505050611bab875f815181106119cc576119cc61534f565b5050505b60405163640f244560e01b815273a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063640f244590611bf0908d908b908a908a908f908990600401615485565b5f6040518083038186803b158015611c06575f5ffd5b505af4158015611c18573d5f5f3e3d5ffd5b50505050505050505050505b505050565b6060611c3361339c565b611c3e848484613aa1565b949350505050565b606080611c51613aad565b604051633f8b51a560e21b8152919350915073a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063fe2d469490611c8f9085908590600401614b1e565b5f60405180830381865af4158015611ca9573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611cd091908101906154d6565b915091509091565b60408051600180825281830190925260609160208083019080368337019050509050670de0b6b3a7640000815f81518110611d1557611d1561534f565b60200260200101818152505090565b611d2c613b8f565b611d3d611d376110c8565b30613ca9565b506001611d48612cb4565b600a0155565b5f5f51602061599a5f395f51905f526004818101546040516370a0823160e01b81526001600160a01b03918216928101839052929350909185918716906370a0823190602401602060405180830381865afa158015611daf573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dd39190615051565b1015611df257604051631e9acf1760e31b815260040160405180910390fd5b60405163ae63932960e01b81526001600160a01b0386811660048301523060248301526044820186905282169063ae639329906064015f604051808303815f87803b158015611e3f575f5ffd5b505af1158015611e51573d5f5f3e3d5ffd5b50505050739247f6d0cb46057d26193634d5a9ab8bdc9c3781630dcd3d68611e776115bd565b8488885f6040518663ffffffff1660e01b8152600401611e9b95949392919061552f565b5f6040518083038186803b158015611eb1575f5ffd5b505af4158015611ec3573d5f5f3e3d5ffd5b50506040516315afd40960e01b81526001600160a01b03888116600483015260248201889052841692506315afd40991506044016020604051808303815f875af1158015611f13573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f379190615051565b505050505050565b60605f83516001148015611f8b5750611f56612cb4565b6006015484516001600160a01b039091169085905f90611f7857611f7861534f565b60200260200101516001600160a01b0316145b8015611fc257505f6001600160a01b0316845f81518110611fae57611fae61534f565b60200260200101516001600160a01b031614155b1561202e578251600114611fe957604051630ef9926760e21b815260040160405180910390fd5b825f81518110611ffb57611ffb61534f565b60200260200101519050612027835f8151811061201a5761201a61534f565b6020026020010151613d74565b915061203d565b6120388484613d7c565b915091505b9250929050565b5f61204d612cb4565b600601546001600160a01b0316919050565b6060612069612cb4565b6005018054806020026020016040519081016040528092919081815260200182805480156120be57602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116120a0575b5050505050905090565b5f5160206159ba5f395f51905f52545f51602061599a5f395f51905f5280547fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70154606093612126926001600160a01b03918216929082169116612eb0565b91505090565b5f80808080805f51602061599a5f395f51905f52739247f6d0cb46057d26193634d5a9ab8bdc9c3781630f0b05946121626115bd565b6040516001600160e01b031960e084901b1681526001600160a01b0390911660048201526024810184905260440160c060405180830381865af41580156121ab573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121cf9190615563565b949c939b5091995097509550909350915050565b6121eb61339c565b6121f58282613d89565b5050565b5f61220261339c565b5f61220b612cb4565b905080600201545f0361221f574260028201555b61222a836001613e11565b9392505050565b61223d84848484613eae565b50505050565b5f5f5f61224e6115bd565b90505f816001600160a01b031663396656406040518163ffffffff1660e01b8152600401602060405180830381865afa15801561228d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906122b19190615068565b90505f826001600160a01b03166301d22ccd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156122f0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123149190615068565b9050336001600160a01b0382161480159061239257506040516336b87bd760e11b81523360048201526001600160a01b03841690636d70f7ae90602401602060405180830381865afa15801561236c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061239091906155a9565b155b80156124015750604051630e19abf360e01b81523360048201526001600160a01b03831690630e19abf390602401602060405180830381865afa1580156123db573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123ff91906155a9565b155b1561241f576040516370a8bfcd60e11b815260040160405180910390fd5b61242887613f62565b9450612432614007565b5093508386811015612463576040516314715aa160e11b815260040161245a91815260200190565b60405180910390fd5b505050509250929050565b60605f835160011480156124ba5750612485612cb4565b6006015484516001600160a01b039091169085905f906124a7576124a761534f565b60200260200101516001600160a01b0316145b80156124f157505f6001600160a01b0316845f815181106124dd576124dd61534f565b60200260200101516001600160a01b031614155b1561255157825160011461251857604051630ef9926760e21b815260040160405180910390fd5b825f8151811061252a5761252a61534f565b60200260200101519050612027835f815181106125495761254961534f565b506060919050565b61203884846140ac565b606061256561339c565b6107cc826140b8565b612576612e21565b5f61257f612cb4565b6009019190915550565b612591612e21565b5f61259a612cb4565b9050600c81016125aa8382615647565b507fd65900dd44764cfc9d7d6f6a36f82c15f38955a604922fa324ed9516e26e186f82604051610ba991906146fe565b7fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f705545f5160206159ba5f395f51905f52547fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f703545f9283925f51602061599a5f395f51905f5292612659926001600160a01b0390811692811691166140c3565b92509250509091565b5f805f51602061599a5f395f51905f52739247f6d0cb46057d26193634d5a9ab8bdc9c3781635bd923f56126946115bd565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602481018490526044016040805180830381865af41580156126dc573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061265991906153c1565b5f5f611cd0614007565b5f51602061599a5f395f51905f52739247f6d0cb46057d26193634d5a9ab8bdc9c3781630dcd3d6861273a6115bd565b83885f8151811061274d5761274d61534f565b6020026020010151885f815181106127675761276761534f565b6020026020010151885f815181106127815761278161534f565b60200260200101516040518663ffffffff1660e01b81526004016127a995949392919061552f565b5f6040518083038186803b1580156127bf575f5ffd5b505af41580156127d1573d5f5f3e3d5ffd5b505050505050505050565b5f6127e5612cb4565b60040154905090565b60606127f8612cb4565b600b01805480602002602001604051908101604052809291908181526020015f905b828210156128c2578382905f5260205f20018054612837906155c4565b80601f0160208091040260200160405190810160405280929190818152602001828054612863906155c4565b80156128ae5780601f10612885576101008083540402835291602001916128ae565b820191905f5260205f20905b81548152906001019060200180831161289157829003601f168201915b50505050508152602001906001019061281a565b50505050905090565b5f6128d4612cb4565b60030154905090565b60606128e761339c565b73a79909da6a7b1f9ec66fd08074bc7d145de64ccd6325567aef612909612cb4565b6040516001600160e01b031960e084901b168152600481019190915260248101879052604481018690526001600160a01b03851660648201526084015f60405180830381865af415801561295f573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611c3e919081019061542d565b60408051600c8082526101a0820190925260609182915f51602061599a5f395f51905f529160208201610180803683370190505092508060090154835f815181106129d3576129d361534f565b60200260200101818152505080600a0154836001815181106129f7576129f761534f565b60200260200101818152505080600b015483600281518110612a1b57612a1b61534f565b60200260200101818152505080600c015483600381518110612a3f57612a3f61534f565b60200260200101818152505080600d015483600481518110612a6357612a6361534f565b60200260200101818152505080600e015483600581518110612a8757612a8761534f565b60200260200101818152505080600f015483600681518110612aab57612aab61534f565b602002602001018181525050806010015483600781518110612acf57612acf61534f565b602002602001018181525050806011015483600881518110612af357612af361534f565b602002602001018181525050806012015483600981518110612b1757612b1761534f565b602002602001018181525050806013015483600a81518110612b3b57612b3b61534f565b602002602001018181525050806015015483600b81518110612b5f57612b5f61534f565b60209081029190910101526040805160028082526060820190925290816020016020820280368337505050600482015481519193506001600160a01b03169083905f90612bae57612bae61534f565b6001600160a01b0392831660209182029290920101526014820154835191169083906001908110612be157612be161534f565b60200260200101906001600160a01b031690816001600160a01b031681525050509091565b5f612c0f612cb4565b546001600160a01b0316919050565b604080516001808252818301909252606091816020015b6060815260200190600190039081612c355790505090506040518060400160405280600b81526020016a436f6d706f756e64696e6760a81b815250815f81518110612c8257612c8261534f565b602002602001018190525090565b5f6001600160e01b03198216637a2a253160e01b14806107cc57506107cc826141e9565b7fb14b643f49bed6a2c6693bbd50f68dc950245db265c66acadbfa51ccc8c3ba0090565b60605f612ce761271084615472565b90505f6103e8612cf983612710615377565b612d0390866153a1565b612d0d9190615472565b60405163be59b50760e01b81526004810184905290915073cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979063be59b507906024015f60405180830381865af4158015612d5d573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612d849190810190615083565b60405163be59b50760e01b81526004810183905273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979063be59b507906024015f60405180830381865af4158015612dd1573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612df89190810190615083565b604051602001612e09929190615701565b60405160208183030381529060405292505050919050565b612e296115bd565b6040516336b87bd760e11b81523360048201526001600160a01b039190911690636d70f7ae90602401602060405180830381865afa158015612e6d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e9191906155a9565b612eae57604051631f0853c160e21b815260040160405180910390fd5b565b60605f846001600160a01b03166379502c556040518163ffffffff1660e01b8152600401602060405180830381865afa158015612eef573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f139190615068565b6001600160a01b031663189e17e46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612f4e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f729190615051565b9050836001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015612faf573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612fd69190810190615083565b836001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa158015613011573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526130389190810190615083565b60405163be59b50760e01b81526004810184905273cb88ad4bc2a5abcbe2ef2bb523fdaabea1bee6979063be59b507906024015f60405180830381865af4158015613085573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526130ac9190810190615083565b6040516020016130be9392919061572a565b6040516020818303038152906040529150509392505050565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a006107cc565b61310761421d565b60608101515f51602061599a5f395f51905f5280546001600160a01b03199081166001600160a01b0393841617825560808401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f7018054831691851691909117905560a08401515f5160206159ba5f395f51905f528054831691851691909117905560c08401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f7038054831691851691909117905560e08401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f704805483169185169190911790556101008401517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70580549092169316929092179091556101208201517fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70881905560408051918252517f2bdd781a443b30701c9ab6bf87f6cb0d8424bf4f343f2eb4bb49e815193d80d2916020908290030190a16040805160018082528183019092525f91602080830190803683370190505090508260600151815f815181106132b9576132b961534f565b6001600160a01b0390921660209283029190910182015283015183516040850151611c24929190845f5f19614242565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261333a84826142e6565b61223d57604080516001600160a01b03851660248201525f6044808301919091528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261339290859061432f565b61223d848261432f565b6133a4612cb4565b546001600160a01b03163314612eae576040516362df054560e01b815260040160405180910390fd5b306001600160a01b03166374bac4296040518163ffffffff1660e01b8152600401602060405180830381865afa158015613409573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061342d91906155a9565b612eae576040516309ea311f60e11b815260040160405180910390fd5b60608060608061345861205f565b604080515f80825260208083019182526001838501818152608085019095529498509195509350909190606085019080368337505060408051608080820183525f80835260208084018290528385018290526060938401829052845192830185525f51602061599a5f395f51905f5280546001600160a01b0390811685527fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f701548116928501929092525f5160206159ba5f395f51905f52548216958401959095527fbcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f70354169282019290925293965090929150613552612cb4565b90505f8160010154905082604001516001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303815f875af115801561359d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135c19190615051565b5082606001516001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303815f875af1158015613603573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136279190615051565b506040805163f91afc8760e01b815284516001600160a01b0390811660048301526020860151811660248301529185015182166044820152606085015190911660648201525f90739247f6d0cb46057d26193634d5a9ab8bdc9c37819063f91afc8790608401602060405180830381865af41580156136a8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136cc9190615051565b845160405163e3d670d760e01b81526001600160a01b03909116600482015273a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063e3d670d790602401602060405180830381865af4158015613725573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137499190615051565b613753919061538e565b9050818111156137865761376782826153a1565b885f815181106137795761377961534f565b6020026020010181815250505b600183018190555f61379883836157b5565b90505f6137a3612662565b5090505f8560020154426137b791906153a1565b90505f6137c26115bd565b6001600160a01b03166349b5fdb46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137fd573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138219190615068565b88516040516341976e0960e01b81526001600160a01b0391821660048201529192505f91908316906341976e09906024016040805180830381865afa15801561386c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061389091906153c1565b5090505f895f01516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156138d3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138f791906157db565b61390290600a6158de565b61390c83886158ec565b613916919061591b565b6040516377d6938160e11b81526004810187905260248101829052604481018690529091505f9073a79909da6a7b1f9ec66fd08074bc7d145de64ccd9063efad270290606401602060405180830381865af4158015613977573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061399b9190615051565b90505f5f6139c88e6005015f9054906101000a90046001600160a01b03168e604001518f606001516140c3565b915091505f6139d5614007565b5060408051868152602081018d90529081018b9052606081018a90526080810182905260a0810185905260c081018490529091507f55b344f7779d44f14b50a9ae3eb0959de12c0956ec73aeddb89c62c0bfce3aad9060e00160405180910390a1505050505050505050505f5f613a4a61212c565b50505092505091507fb83dc6ff11ec1f33d17651f75f3998b69e170ade8f9072b116beaa5e6d037e1e8282604051613a8c929190918252602082015260400190565b60405180910390a15050505050505090919293565b6060611c3e8383613ca9565b606080613ab861205f565b604080516001808252818301909252919350602080830190803683370190505090505f5f51602061599a5f395f51905f526002810154604051633f02cd9160e11b81526001600160a01b039091166004820152909150739247f6d0cb46057d26193634d5a9ab8bdc9c378190637e059b2290602401602060405180830381865af4158015613b48573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b6c9190615051565b825f81518110613b7e57613b7e61534f565b602002602001018181525050509091565b5f613b986115bd565b9050336001600160a01b0316816001600160a01b0316635aa6e6756040518163ffffffff1660e01b8152600401602060405180830381865afa158015613be0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c049190615068565b6001600160a01b03161480613c895750336001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613c5a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c7e9190615068565b6001600160a01b0316145b613ca6576040516354299b6f60e01b815260040160405180910390fd5b50565b60605f51602061599a5f395f51905f525f613cc2612cb4565b9050739247f6d0cb46057d26193634d5a9ab8bdc9c37816357477647613ce66115bd565b6040516001600160e01b031960e084901b1681526001600160a01b039182166004820152602481018690526044810185905260648101899052908716608482015260a4015f60405180830381865af4158015613d44573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613d6b919081019061542d565b95945050505050565b6060806107cc565b60605f61203884846140ac565b5f613d92612cb4565b600601546001600160a01b031614613dd1576040518060400160405280600f81526020016e1b9bdd081a5b5c1b195b595b9d1959608a1b815250613df8565b6040518060400160405280600d81526020016c6e6f20756e6465726c79696e6760981b8152505b60405162461bcd60e51b815260040161245a91906146fe565b5f5f51602061599a5f395f51905f5281613e29612cb4565b9050739247f6d0cb46057d26193634d5a9ab8bdc9c378163f1d7a9938383613e4f61205f565b896040518563ffffffff1660e01b8152600401613e6f9493929190615947565b602060405180830381865af4158015613e8a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613d6b9190615051565b5f8080613ebd84860186615965565b9250925092505f613ed85f51602061599a5f395f51905f5290565b9050739247f6d0cb46057d26193634d5a9ab8bdc9c3781630dcd3d68613efc6115bd565b83878787613f0a578c613f0c565b8d5b6040518663ffffffff1660e01b8152600401613f2c95949392919061552f565b5f6040518083038186803b158015613f42575f5ffd5b505af4158015613f54573d5f5f3e3d5ffd5b505050505050505050505050565b5f739247f6d0cb46057d26193634d5a9ab8bdc9c378163b86c2a78613f856115bd565b845f51602061599a5f395f51905f526040516001600160e01b031960e086901b1681526001600160a01b03909316600484015260248301919091526044820152606401602060405180830381865af4158015613fe3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107cc9190615051565b5f5f5f614012612662565b925090505f61401f612c06565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561405a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061407e9190615051565b905080156140a6578061409983670de0b6b3a7640000615377565b6140a39190615472565b93505b50509091565b60605f6120388361439b565b60605f613d92612cb4565b6040516327b52bdb60e11b81526001600160a01b0383811660048301525f918291670de0b6b3a764000091620186a091881690634f6a57b690602401602060405180830381865afa15801561411a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061413e9190615051565b6141489190615377565b6141529190615472565b604051620707bd60e51b81526001600160a01b038581166004830152919350670de0b6b3a764000091620186a0919088169062e0f7a090602401602060405180830381865afa1580156141a7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906141cb9190615051565b6141d59190615377565b6141df9190615472565b9050935093915050565b5f6001600160e01b03198216630f1ec81f60e41b14806107cc57506301ffc9a760e01b6001600160e01b03198316146107cc565b614225614419565b612eae57604051631afcd79f60e31b815260040160405180910390fd5b61424a61421d565b61425386614432565b5f61425c612cb4565b600881018390556006810180546001600160a01b0319166001600160a01b03861617905584519091508690869086908690869060078701905f90889082906142ad90600584019060208a01906145e3565b5081546001600160a01b03808a166101009390930a92830292021916179055506142d78682615647565b50505050505050505050505050565b5f5f5f5f60205f8651602088015f8a5af192503d91505f519050828015614325575081156143175780600114614325565b5f866001600160a01b03163b115b9695505050505050565b5f5f60205f8451602086015f885af18061434e576040513d5f823e3d81fd5b50505f513d91508115614365578060011415614372565b6001600160a01b0384163b155b1561223d57604051635274afe760e01b81526001600160a01b038516600482015260240161245a565b6040805160018082528183019092526060915f919060208083019080368337019050509150825f815181106143d2576143d261534f565b6020026020010151825f815181106143ec576143ec61534f565b602002602001018181525050815f8151811061440a5761440a61534f565b60200260200101519050915091565b5f6144226130d7565b54600160401b900460ff16919050565b61443a61421d565b6001600160a01b038116158015906144c357505f6001600160a01b0316816001600160a01b0316634783c35b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015614493573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906144b79190615068565b6001600160a01b031614155b6144e0576040516371c42ac360e01b815260040160405180910390fd5b61451361450e60017faa116a42804728f23983458454b6eb9c6ddf3011db9f9addaf3cd7508d85b0d66153a1565b829055565b6145454361454260017f812a673dfca07956350df10f8a654925f561d7a0da09bdbe79e653939a14d9f16153a1565b55565b604080516001600160a01b0383168152426020820152438183015290517f1a2dd071001ebf6e03174e3df5b305795a4ad5d41d8fdb9ba41dbbe2367134269181900360600190a150565b828054828255905f5260205f209081019282156145d3579160200282015b828111156145d357825182906145c39082615647565b50916020019190600101906145ad565b506145df929150614642565b5090565b828054828255905f5260205f20908101928215614636579160200282015b8281111561463657825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190614601565b506145df92915061465e565b808211156145df575f6146558282614672565b50600101614642565b5b808211156145df575f815560010161465f565b50805461467e906155c4565b5f825580601f1061468d575050565b601f0160209004905f5260205f2090810190613ca6919061465e565b5f602082840312156146b9575f5ffd5b81356001600160e01b03198116811461222a575f5ffd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f61222a60208301846146d0565b604081525f61472260408301856146d0565b905082151560208301529392505050565b5f60208284031215614743575f5ffd5b5035919050565b6001600160a01b0381168114613ca6575f5ffd5b5f6020828403121561476e575f5ffd5b813561222a8161474a565b5f82825180855260208501945060208160051b830101602085015f5b838110156147c757601f198584030188526147b18383516146d0565b6020988901989093509190910190600101614795565b50909695505050505050565b5f8151808452602084019350602083015f5b8281101561480c5781516001600160a01b03168652602095860195909101906001016147e5565b5093949350505050565b5f8151808452602084019350602083015f5b8281101561480c578151865260209586019590910190600101614828565b608081525f6148586080830187614779565b828103602084015261486a81876147d3565b9050828103604084015261487e8186614816565b8381036060850152845180825260208087019350909101905f5b818110156148b957835160020b835260209384019390920191600101614898565b509098975050505050505050565b634e487b7160e01b5f52604160045260245ffd5b604051606081016001600160401b03811182821017156148fd576148fd6148c7565b60405290565b604051601f8201601f191681016001600160401b038111828210171561492b5761492b6148c7565b604052919050565b5f6001600160401b0382111561494b5761494b6148c7565b5060051b60200190565b5f82601f830112614964575f5ffd5b813561497761497282614933565b614903565b8082825260208201915060208360051b860101925085831115614998575f5ffd5b602085015b838110156149be5780356149b08161474a565b83526020928301920161499d565b5095945050505050565b5f82601f8301126149d7575f5ffd5b81356149e561497282614933565b8082825260208201915060208360051b860101925085831115614a06575f5ffd5b602085015b838110156149be578035835260209283019201614a0b565b8060020b8114613ca6575f5ffd5b5f5f5f60608486031215614a43575f5ffd5b83356001600160401b03811115614a58575f5ffd5b614a6486828701614955565b93505060208401356001600160401b03811115614a7f575f5ffd5b614a8b868287016149c8565b92505060408401356001600160401b03811115614aa6575f5ffd5b8401601f81018613614ab6575f5ffd5b8035614ac461497282614933565b8082825260208201915060208360051b850101925088831115614ae5575f5ffd5b6020840193505b82841015614b10578335614aff81614a23565b825260209384019390910190614aec565b809450505050509250925092565b604081525f614b3060408301856147d3565b8281036020840152613d6b8185614816565b5f5f60408385031215614b53575f5ffd5b82356001600160401b03811115614b68575f5ffd5b614b74858286016149c8565b92505060208301356001600160401b03811115614b8f575f5ffd5b614b9b85828601614955565b9150509250929050565b5f6001600160401b03821115614bbd57614bbd6148c7565b50601f01601f191660200190565b5f82601f830112614bda575f5ffd5b8135602083015f614bed61497284614ba5565b9050828152858383011115614c00575f5ffd5b828260208301375f92810160200192909252509392505050565b5f60208284031215614c2a575f5ffd5b81356001600160401b03811115614c3f575f5ffd5b8201601f81018413614c4f575f5ffd5b8035614c5d61497282614933565b8082825260208201915060208360051b850101925086831115614c7e575f5ffd5b602084015b83811015614cbe5780356001600160401b03811115614ca0575f5ffd5b614caf89602083890101614bcb565b84525060209283019201614c83565b509695505050505050565b5f5f5f60608486031215614cdb575f5ffd5b83356001600160401b03811115614cf0575f5ffd5b614cfc86828701614955565b935050602084013591506040840135614d148161474a565b809150509250925092565b602081525f61222a6020830184614816565b5f5f5f60608486031215614d43575f5ffd5b8335614d4e8161474a565b92506020840135915060408401356001600160401b03811115614d6f575f5ffd5b614d7b86828701614bcb565b9150509250925092565b5f5f60408385031215614d96575f5ffd5b82356001600160401b03811115614dab575f5ffd5b614db785828601614955565b92505060208301356001600160401b03811115614dd2575f5ffd5b614b9b858286016149c8565b604081525f614df06040830185614816565b90508260208301529392505050565b602081525f61222a60208301846147d3565b5f5f60408385031215614e22575f5ffd5b823591506020830135614e348161474a565b809150509250929050565b5f60208284031215614e4f575f5ffd5b81356001600160401b03811115614e64575f5ffd5b611c3e848285016149c8565b5f5f5f5f60608587031215614e83575f5ffd5b843593506020850135925060408501356001600160401b03811115614ea6575f5ffd5b8501601f81018713614eb6575f5ffd5b80356001600160401b03811115614ecb575f5ffd5b876020828401011115614edc575f5ffd5b949793965060200194505050565b5f5f60408385031215614efb575f5ffd5b50508035926020909101359150565b5f60208284031215614f1a575f5ffd5b81356001600160401b03811115614f2f575f5ffd5b611c3e84828501614bcb565b5f5f5f5f60808587031215614f4e575f5ffd5b84356001600160401b03811115614f63575f5ffd5b614f6f87828801614955565b94505060208501356001600160401b03811115614f8a575f5ffd5b614f96878288016149c8565b93505060408501356001600160401b03811115614fb1575f5ffd5b614fbd878288016149c8565b92505060608501356001600160401b03811115614fd8575f5ffd5b614fe487828801614bcb565b91505092959194509250565b602081525f61222a6020830184614779565b5f5f5f60608486031215615014575f5ffd5b83359250602084013591506040840135614d148161474a565b604081525f61503f6040830185614816565b8281036020840152613d6b81856147d3565b5f60208284031215615061575f5ffd5b5051919050565b5f60208284031215615078575f5ffd5b815161222a8161474a565b5f60208284031215615093575f5ffd5b81516001600160401b038111156150a8575f5ffd5b8201601f810184136150b8575f5ffd5b80516150c661497282614ba5565b8181528560208385010111156150da575f5ffd5b8160208401602083015e5f91810160200191909152949350505050565b5f5f5f60608486031215615109575f5ffd5b5050815160208301516040909301519094929350919050565b5f81518060208401855e5f93019283525090919050565b5f6151448286615122565b600160fd1b81526151586001820186615122565b9050600160fd1b81526143256001820185615122565b5f82601f83011261517d575f5ffd5b815161518b61497282614933565b8082825260208201915060208360051b8601019250858311156151ac575f5ffd5b602085015b838110156149be5780516151c48161474a565b8352602092830192016151b1565b5f82601f8301126151e1575f5ffd5b81516151ef61497282614933565b8082825260208201915060208360051b860101925085831115615210575f5ffd5b602085015b838110156149be578051835260209283019201615215565b5f6020828403121561523d575f5ffd5b81516001600160401b03811115615252575f5ffd5b820160608185031215615263575f5ffd5b61526b6148db565b81516001600160401b03811115615280575f5ffd5b61528c8682850161516e565b82525060208201516001600160401b038111156152a7575f5ffd5b6152b3868285016151d2565b60208301525060408201516001600160401b038111156152d1575f5ffd5b80830192505084601f8301126152e5575f5ffd5b81516152f361497282614933565b8082825260208201915060208360051b860101925087831115615314575f5ffd5b6020850194505b8285101561533f57845161532e81614a23565b82526020948501949091019061531b565b6040840152509095945050505050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176107cc576107cc615363565b808201808211156107cc576107cc615363565b818103818111156107cc576107cc615363565b8015158114613ca6575f5ffd5b5f5f604083850312156153d2575f5ffd5b82516020840151909250614e34816153b4565b6001600160a01b038581168252841660208201526080604082018190525f90615410908301856147d3565b82810360608401526154228185614816565b979650505050505050565b5f6020828403121561543d575f5ffd5b81516001600160401b03811115615452575f5ffd5b611c3e848285016151d2565b634e487b7160e01b5f52601260045260245ffd5b5f826154805761548061545e565b500490565b8681526001600160a01b038616602082015260c0604082018190525f906154ae908301876147d3565b82810360608401526154c08187614816565b6080840195909552505060a00152949350505050565b5f5f604083850312156154e7575f5ffd5b82516001600160401b038111156154fc575f5ffd5b6155088582860161516e565b92505060208301516001600160401b03811115615523575f5ffd5b614b9b858286016151d2565b6001600160a01b03958616815260208101949094529190931660408301526060820192909252608081019190915260a00190565b5f5f5f5f5f5f60c08789031215615578575f5ffd5b50508451602086015160408701516060880151608089015160a090990151939a929950909790965094509092509050565b5f602082840312156155b9575f5ffd5b815161222a816153b4565b600181811c908216806155d857607f821691505b6020821081036155f657634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115611c2457805f5260205f20601f840160051c810160208510156156215750805b601f840160051c820191505b81811015615640575f815560010161562d565b5050505050565b81516001600160401b03811115615660576156606148c7565b6156748161566e84546155c4565b846155fc565b6020601f8211600181146156a6575f831561568f5750848201515b5f19600385901b1c1916600184901b178455615640565b5f84815260208120601f198516915b828110156156d557878501518255602094850194600190920191016156b5565b50848210156156f257868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b600f60fb1b81525f6157166001830185615122565b601760f91b8152613d6b6001820185615122565b66029bab838363c960cd1b81525f6157456007830186615122565b6b01030b732103137b93937bb960a51b8152615764600c820186615122565b90507201037b71029b4b637902b191036b0b935b2ba1606d1b815261578c6013820185615122565b752077697468206c65766572616765206c6f6f70696e6760501b81526016019695505050505050565b8181035f8312801583831316838312821617156157d4576157d4615363565b5092915050565b5f602082840312156157eb575f5ffd5b815160ff8116811461222a575f5ffd5b6001815b60018411156158365780850481111561581a5761581a615363565b600184161561582857908102905b60019390931c9280026157ff565b935093915050565b5f8261584c575060016107cc565b8161585857505f6107cc565b816001811461586e576002811461587857615894565b60019150506107cc565b60ff84111561588957615889615363565b50506001821b6107cc565b5060208310610133831016604e8410600b84101617156158b7575081810a6107cc565b6158c35f1984846157fb565b805f19048211156158d6576158d6615363565b029392505050565b5f61222a60ff84168361583e565b8082025f8212600160ff1b8414161561590757615907615363565b81810583148215176107cc576107cc615363565b5f826159295761592961545e565b600160ff1b82145f198414161561594257615942615363565b500590565b848152836020820152608060408201525f61541060808301856147d3565b5f5f5f60608486031215615977575f5ffd5b83356159828161474a565b9250602084013591506040840135614d14816153b456febcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f700bcea52cc71723df4e8ce4341004b27df2cc7bc9197584ea7d92bbe219528f702a264697066735822122096c872ca507f62e4d57a7ed0c6505978f2f4dfc555d3a84f589186b84390cdab64736f6c634300081c0033

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

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.