ETH Price: $3,029.06 (-5.78%)

Token

ERC20 ***

Overview

Max Total Supply

0 ERC20 ***

Holders

0

Total Transfers

-

Market

Price

$0.00 @ 0.000000 ETH

Onchain Market Cap

-

Circulating Supply Market Cap

-

Other Info

Token Contract (WITH 18 Decimals)

Loading...
Loading
Loading...
Loading
Loading...
Loading

Click here to update the token information / general information
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.

Contract Source Code Verified (Exact Match)

Contract Name:
LSTMorphoLooper

Compiler Version
v0.8.23+commit.f704f362

Optimization Enabled:
Yes with 200 runs

Other Settings:
shanghai EvmVersion
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

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

import {BaseMorphoLooper} from "./BaseMorphoLooper.sol";
import {Id} from "./interfaces/morpho/IMorpho.sol";
import {UniswapV3Swapper} from "@periphery/swappers/UniswapV3Swapper.sol";

/**
 * @notice LSTMorphoLooper is a looper that is built to use any token as collateral to
 *         leveragae loop against its underlying asset.
 *         It uses Uniswap V3 to swap the collateral to the underlying asset and back.
 */
contract LSTMorphoLooper is BaseMorphoLooper, UniswapV3Swapper {
    using SafeERC20 for ERC20;

    constructor(
        address _asset,
        string memory _name,
        address _collateralToken,
        address _morpho,
        Id _marketId
    ) BaseMorphoLooper(_asset, _name, _collateralToken, _morpho, _marketId) {
        _setUniFees(address(asset), address(collateralToken), 100);
    }

    function setUniFees(
        address _token0,
        address _token1,
        uint24 _fee
    ) external onlyManagement {
        _setUniFees(_token0, _token1, _fee);
    }

    /*//////////////////////////////////////////////////////////////
                            CONVERSIONS
    //////////////////////////////////////////////////////////////*/

    function _convertAssetToCollateral(
        uint256 amount
    ) internal override returns (uint256) {
        if (amount == 0) return 0;
        // Gateway mints iUSD and stakes directly to sIUSD for this contract.
        return _swapFrom(address(asset), address(collateralToken), amount, 0);
    }

    function _convertCollateralToAsset(
        uint256 amount
    ) internal override returns (uint256) {
        if (amount == 0) return 0;
        // Add slippage to the amount in to make sure we get enough for the flash loan repayment.
        return _swapFrom(address(collateralToken), address(asset), amount, 0);
    }

    /*//////////////////////////////////////////////////////////////
                        NO-OP REWARDS (NONE)
    //////////////////////////////////////////////////////////////*/

    function _claimAndSellRewards() internal pure override {}
}

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

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

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

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

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

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

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

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

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

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

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

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

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

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

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

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

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

    /**
     * @dev 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

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

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

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

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

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

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

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

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

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {BaseLooper} from "./BaseLooper.sol";
import {IMorpho, Id, MarketParams, Position} from "./interfaces/morpho/IMorpho.sol";
import {IMorphoFlashLoanCallback} from "./interfaces/morpho/IMorphoFlashLoanCallback.sol";
import {IOracle} from "./interfaces/morpho/IOracle.sol";
import {MarketParamsLib} from "./libraries/morpho/MarketParamsLib.sol";
import {MorphoBalancesLib} from "./libraries/morpho/periphery/MorphoBalancesLib.sol";
import {MorphoLib} from "./libraries/morpho/periphery/MorphoLib.sol";
import {SharesMathLib} from "./libraries/morpho/SharesMathLib.sol";
import {IMerklDistributor} from "./interfaces/IMerkleDistributor.sol";
import {AuctionSwapper} from "@periphery/swappers/AuctionSwapper.sol";

/**
 * @title BaseMorphoLooper
 * @notice Morpho Blue specific implementation of BaseLooper.
 *         Implements the flashloan callback and protocol-specific operations.
 *         All generic flashloan logic and calculations live in BaseLooper.
 */
abstract contract BaseMorphoLooper is
    BaseLooper,
    IMorphoFlashLoanCallback,
    AuctionSwapper
{
    using SafeERC20 for ERC20;
    using MarketParamsLib for MarketParams;
    using MorphoBalancesLib for IMorpho;
    using MorphoLib for IMorpho;

    /// @notice The Merkl Distributor contract for claiming rewards
    IMerklDistributor public constant MERKL_DISTRIBUTOR =
        IMerklDistributor(0x3Ef3D8bA38EBe18DB133cEc108f4D14CE00Dd9Ae);

    IMorpho public immutable morpho;
    Id public immutable marketId;
    MarketParams internal marketParams;

    bool internal isFlashloanActive;

    constructor(
        address _asset,
        string memory _name,
        address _collateralToken,
        address _morpho,
        Id _marketId
    ) BaseLooper(_asset, _name, _collateralToken) {
        morpho = IMorpho(_morpho);
        marketId = _marketId;

        marketParams = morpho.idToMarketParams(_marketId);
        require(marketParams.loanToken == _asset, "!loanToken");
        require(
            marketParams.collateralToken == _collateralToken,
            "!collateral"
        );

        ERC20(_asset).forceApprove(_morpho, type(uint256).max);
        ERC20(_collateralToken).forceApprove(_morpho, type(uint256).max);
    }

    function _accrueInterest() internal virtual override {
        //morpho.accrueInterest(marketParams);
    }

    /*//////////////////////////////////////////////////////////////
                        FLASHLOAN IMPLEMENTATION
    //////////////////////////////////////////////////////////////*/

    /// @notice Execute flashloan through Morpho
    function _executeFlashloan(
        address token,
        uint256 amount,
        bytes memory data
    ) internal override {
        isFlashloanActive = true;
        morpho.flashLoan(token, amount, data);
        isFlashloanActive = false;
    }

    /// @notice Morpho flashloan callback - CRITICAL SECURITY FUNCTION
    /// @dev Only callable by Morpho contract during flashLoan execution
    function onMorphoFlashLoan(
        uint256 assets,
        bytes calldata data
    ) external override {
        require(msg.sender == address(morpho), "!morpho");
        require(isFlashloanActive, "flashloan active");
        // Delegate to parent's generic handler
        _onFlashloanReceived(assets, data);

        // Morpho already has max approval from constructor, no need to re-approve
    }

    /// @notice Max available flashloan from Morpho
    function maxFlashloan() public view override returns (uint256) {
        return asset.balanceOf(address(morpho));
    }

    /*//////////////////////////////////////////////////////////////
                        ORACLE IMPLEMENTATION
    //////////////////////////////////////////////////////////////*/

    /// @notice Get oracle price (loan token value per 1 collateral token, 1e36 scale)
    /// @dev Returns raw oracle price to preserve precision. Callers must divide by ORACLE_PRICE_SCALE.
    function _getCollateralPrice()
        internal
        view
        virtual
        override
        returns (uint256)
    {
        return IOracle(marketParams.oracle).price();
    }

    /*//////////////////////////////////////////////////////////////
                    MORPHO PROTOCOL OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function _supplyCollateral(uint256 amount) internal override {
        if (amount == 0) return;
        morpho.supplyCollateral(marketParams, amount, address(this), "");
    }

    function _withdrawCollateral(uint256 amount) internal override {
        if (amount == 0) return;
        morpho.withdrawCollateral(
            marketParams,
            amount,
            address(this),
            address(this)
        );
    }

    function _borrow(uint256 amount) internal virtual override {
        if (amount == 0) return;
        morpho.borrow(marketParams, amount, 0, address(this), address(this));
    }

    function _repay(uint256 amount) internal virtual override {
        if (amount == 0) return;
        (
            ,
            ,
            uint256 totalBorrowAssets,
            uint256 totalBorrowShares
        ) = MorphoBalancesLib.expectedMarketBalances(morpho, marketParams);

        uint256 shares = Math.min(
            SharesMathLib.toSharesDown(
                amount,
                totalBorrowAssets,
                totalBorrowShares
            ),
            morpho.borrowShares(marketId, address(this))
        );

        morpho.repay(marketParams, 0, shares, address(this), "");
    }

    /*//////////////////////////////////////////////////////////////
                            VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function _isSupplyPaused() internal view virtual override returns (bool) {
        return false;
    }

    function _isBorrowPaused() internal view virtual override returns (bool) {
        return false;
    }

    function _isLiquidatable() internal view virtual override returns (bool) {
        Position memory p = morpho.position(marketId, address(this));
        if (p.borrowShares == 0) return false;

        uint256 collateralValue = (uint256(p.collateral) *
            IOracle(marketParams.oracle).price()) / ORACLE_PRICE_SCALE;
        uint256 maxBorrow = (collateralValue * marketParams.lltv) / WAD;

        return balanceOfDebt() > maxBorrow;
    }

    function _maxCollateralDeposit()
        internal
        view
        virtual
        override
        returns (uint256)
    {
        return type(uint256).max;
    }

    function _maxBorrowAmount()
        internal
        view
        virtual
        override
        returns (uint256)
    {
        (uint256 totalSupplyAssets, , uint256 totalBorrowAssets, ) = morpho
            .expectedMarketBalances(marketParams);
        return
            totalSupplyAssets > totalBorrowAssets
                ? totalSupplyAssets - totalBorrowAssets
                : 0;
    }

    function getLiquidateCollateralFactor()
        public
        view
        virtual
        override
        returns (uint256)
    {
        return marketParams.lltv;
    }

    function balanceOfCollateral()
        public
        view
        virtual
        override
        returns (uint256)
    {
        Position memory p = morpho.position(marketId, address(this));
        return p.collateral;
    }

    function balanceOfDebt() public view virtual override returns (uint256) {
        return morpho.expectedBorrowAssets(marketParams, address(this));
    }

    ////////////////////////////////////////////////////////////////
    //                     REWARDS
    ////////////////////////////////////////////////////////////////

    /**
     * @notice Claims rewards from Merkl distributor
     * @param users Recipients of tokens
     * @param tokens ERC20 tokens being claimed
     * @param amounts Amounts of tokens that will be sent to the corresponding users
     * @param proofs Array of Merkle proofs verifying the claims
     */
    function claim(
        address[] calldata users,
        address[] calldata tokens,
        uint256[] calldata amounts,
        bytes32[][] calldata proofs
    ) external {
        MERKL_DISTRIBUTOR.claim(users, tokens, amounts, proofs);
    }

    function setAuction(address _auction) external onlyManagement {
        _setAuction(_auction);
    }

    function setUseAuction(bool _useAuction) external onlyManagement {
        _setUseAuction(_useAuction);
    }

    function kickAuction(
        address _token
    ) external override onlyKeepers returns (uint256) {
        return _kickAuction(_token);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

type Id is bytes32;

struct MarketParams {
    address loanToken;
    address collateralToken;
    address oracle;
    address irm;
    uint256 lltv;
}

/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
    uint256 supplyShares;
    uint128 borrowShares;
    uint128 collateral;
}

/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
    uint128 totalSupplyAssets;
    uint128 totalSupplyShares;
    uint128 totalBorrowAssets;
    uint128 totalBorrowShares;
    uint128 lastUpdate;
    uint128 fee;
}

struct Authorization {
    address authorizer;
    address authorized;
    bool isAuthorized;
    uint256 nonce;
    uint256 deadline;
}

struct Signature {
    uint8 v;
    bytes32 r;
    bytes32 s;
}

/// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoBase {
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    function owner() external view returns (address);

    function feeRecipient() external view returns (address);

    function isIrmEnabled(address irm) external view returns (bool);

    function isLltvEnabled(uint256 lltv) external view returns (bool);

    function isAuthorized(
        address authorizer,
        address authorized
    ) external view returns (bool);

    function nonce(address authorizer) external view returns (uint256);

    function setOwner(address newOwner) external;

    function enableIrm(address irm) external;

    function enableLltv(uint256 lltv) external;

    function setFee(MarketParams memory marketParams, uint256 newFee) external;

    function setFeeRecipient(address newFeeRecipient) external;

    function createMarket(MarketParams memory marketParams) external;

    function supply(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);

    function withdraw(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);

    function borrow(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);

    function repay(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        bytes memory data
    ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);

    function supplyCollateral(
        MarketParams memory marketParams,
        uint256 assets,
        address onBehalf,
        bytes memory data
    ) external;

    function withdrawCollateral(
        MarketParams memory marketParams,
        uint256 assets,
        address onBehalf,
        address receiver
    ) external;

    function liquidate(
        MarketParams memory marketParams,
        address borrower,
        uint256 seizedAssets,
        uint256 repaidShares,
        bytes memory data
    ) external returns (uint256, uint256);

    function flashLoan(
        address token,
        uint256 assets,
        bytes calldata data
    ) external;

    function setAuthorization(
        address authorized,
        bool newIsAuthorized
    ) external;

    function setAuthorizationWithSig(
        Authorization calldata authorization,
        Signature calldata signature
    ) external;

    function accrueInterest(MarketParams memory marketParams) external;

    function extSloads(
        bytes32[] memory slots
    ) external view returns (bytes32[] memory);
}

interface IMorphoStaticTyping is IMorphoBase {
    function position(
        Id id,
        address user
    )
        external
        view
        returns (
            uint256 supplyShares,
            uint128 borrowShares,
            uint128 collateral
        );

    function market(
        Id id
    )
        external
        view
        returns (
            uint128 totalSupplyAssets,
            uint128 totalSupplyShares,
            uint128 totalBorrowAssets,
            uint128 totalBorrowShares,
            uint128 lastUpdate,
            uint128 fee
        );

    function idToMarketParams(
        Id id
    )
        external
        view
        returns (
            address loanToken,
            address collateralToken,
            address oracle,
            address irm,
            uint256 lltv
        );
}

interface IMorpho is IMorphoBase {
    function position(
        Id id,
        address user
    ) external view returns (Position memory p);

    function market(Id id) external view returns (Market memory m);

    function idToMarketParams(
        Id id
    ) external view returns (MarketParams memory);
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

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

import {ISwapRouter} from "../interfaces/Uniswap/V3/ISwapRouter.sol";
import {BaseSwapper} from "./BaseSwapper.sol";

/**
 *   @title UniswapV3Swapper
 *   @author Yearn.finance
 *   @dev This is a simple contract that can be inherited by any tokenized
 *   strategy that would like to use Uniswap V3 for swaps. It hold all needed
 *   logic to perform both exact input and exact output swaps.
 *
 *   The global address variables default to the ETH mainnet addresses but
 *   remain settable by the inheriting contract to allow for customization
 *   based on needs or chain its used on.
 *
 *   The only variables that are required to be set are the specific fees
 *   for each token pair. The inheriting contract can use the {_setUniFees}
 *   function to easily set this for any token pairs needed.
 */
contract UniswapV3Swapper is BaseSwapper {
    using SafeERC20 for ERC20;
    // Defaults to WETH on mainnet.
    address public base = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    // Defaults to Uniswap V3 router on mainnet.
    address public router = 0xE592427A0AEce92De3Edee1F18E0157C05861564;

    // Fees for the Uni V3 pools. Each fee should get set each way in
    // the mapping so no matter the direction the correct fee will get
    // returned for any two tokens.
    mapping(address => mapping(address => uint24)) public uniFees;

    /**
     * @dev All fess will default to 0 on creation. A strategist will need
     * To set the mapping for the tokens expected to swap. This function
     * is to help set the mapping. It can be called internally during
     * initialization, through permissioned functions etc.
     */
    function _setUniFees(
        address _token0,
        address _token1,
        uint24 _fee
    ) internal virtual {
        uniFees[_token0][_token1] = _fee;
        uniFees[_token1][_token0] = _fee;
    }

    /**
     * @dev Used to swap a specific amount of `_from` to `_to`.
     * This will check and handle all allowances as well as not swapping
     * unless `_amountIn` is greater than the set `_minAmountOut`
     *
     * If one of the tokens matches with the `base` token it will do only
     * one jump, otherwise will do two jumps.
     *
     * The corresponding uniFees for each token pair will need to be set
     * other wise this function will revert.
     *
     * @param _from The token we are swapping from.
     * @param _to The token we are swapping to.
     * @param _amountIn The amount of `_from` we will swap.
     * @param _minAmountOut The min of `_to` to get out.
     * @return _amountOut The actual amount of `_to` that was swapped to
     */
    function _swapFrom(
        address _from,
        address _to,
        uint256 _amountIn,
        uint256 _minAmountOut
    ) internal virtual returns (uint256 _amountOut) {
        if (_amountIn != 0 && _amountIn >= minAmountToSell) {
            _checkAllowance(router, _from, _amountIn);
            if (_from == base || _to == base) {
                ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
                    .ExactInputSingleParams(
                        _from, // tokenIn
                        _to, // tokenOut
                        uniFees[_from][_to], // from-to fee
                        address(this), // recipient
                        block.timestamp, // deadline
                        _amountIn, // amountIn
                        _minAmountOut, // amountOut
                        0 // sqrtPriceLimitX96
                    );

                _amountOut = ISwapRouter(router).exactInputSingle(params);
            } else {
                bytes memory path = abi.encodePacked(
                    _from, // tokenIn
                    uniFees[_from][base], // from-base fee
                    base, // base token
                    uniFees[base][_to], // base-to fee
                    _to // tokenOut
                );

                _amountOut = ISwapRouter(router).exactInput(
                    ISwapRouter.ExactInputParams(
                        path,
                        address(this),
                        block.timestamp,
                        _amountIn,
                        _minAmountOut
                    )
                );
            }
        }
    }

    /**
     * @dev Used to swap a specific amount of `_to` from `_from` unless
     * it takes more than `_maxAmountFrom`.
     *
     * This will check and handle all allowances as well as not swapping
     * unless `_maxAmountFrom` is greater than the set `minAmountToSell`
     *
     * If one of the tokens matches with the `base` token it will do only
     * one jump, otherwise will do two jumps.
     *
     * The corresponding uniFees for each token pair will need to be set
     * other wise this function will revert.
     *
     * @param _from The token we are swapping from.
     * @param _to The token we are swapping to.
     * @param _amountTo The amount of `_to` we need out.
     * @param _maxAmountFrom The max of `_from` we will swap.
     * @return _amountIn The actual amount of `_from` swapped.
     */
    function _swapTo(
        address _from,
        address _to,
        uint256 _amountTo,
        uint256 _maxAmountFrom
    ) internal virtual returns (uint256 _amountIn) {
        if (_maxAmountFrom != 0 && _maxAmountFrom >= minAmountToSell) {
            _checkAllowance(router, _from, _maxAmountFrom);
            if (_from == base || _to == base) {
                ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter
                    .ExactOutputSingleParams(
                        _from, // tokenIn
                        _to, // tokenOut
                        uniFees[_from][_to], // from-to fee
                        address(this), // recipient
                        block.timestamp, // deadline
                        _amountTo, // amountOut
                        _maxAmountFrom, // maxAmountIn
                        0 // sqrtPriceLimitX96
                    );

                _amountIn = ISwapRouter(router).exactOutputSingle(params);
            } else {
                bytes memory path = abi.encodePacked(
                    _to,
                    uniFees[base][_to], // base-to fee
                    base,
                    uniFees[_from][base], // from-base fee
                    _from
                );

                _amountIn = ISwapRouter(router).exactOutput(
                    ISwapRouter.ExactOutputParams(
                        path,
                        address(this),
                        block.timestamp,
                        _amountTo, // How much we want out
                        _maxAmountFrom
                    )
                );
            }
        }
    }

    /**
     * @dev Internal safe function to make sure the contract you want to
     * interact with has enough allowance to pull the desired tokens.
     *
     * @param _contract The address of the contract that will move the token.
     * @param _token The ERC-20 token that will be getting spent.
     * @param _amount The amount of `_token` to be spent.
     */
    function _checkAllowance(
        address _contract,
        address _token,
        uint256 _amount
    ) internal virtual {
        if (ERC20(_token).allowance(address(this), _contract) < _amount) {
            ERC20(_token).forceApprove(_contract, 0);
            ERC20(_token).forceApprove(_contract, _amount);
        }
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
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 v4.9.4) (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

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

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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

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

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

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

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

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

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

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

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

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

File 13 of 43 : BaseLooper.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {BaseHealthCheck, ERC20} from "@periphery/Bases/HealthCheck/BaseHealthCheck.sol";

/**
 * @title BaseLooper
 * @notice Shared leverage-looping logic using flashloans exclusively.
 *         Uses a fixed leverage ratio system with flashloan-based operations.
 *         Since asset == borrowToken, pricing uses a single oracle for collateral/asset conversion.
 *         Inheritors implement protocol specific hooks for flashloans, supplying collateral,
 *         borrowing, repaying, and oracle access.
 */
abstract contract BaseLooper is BaseHealthCheck {
    using SafeERC20 for ERC20;

    /// @notice Accrue interest before state changing functions
    modifier accrue() {
        _accrueInterest();
        _;
    }

    uint256 internal constant WAD = 1e18;
    uint256 internal constant ORACLE_PRICE_SCALE = 1e36;

    /// @notice Flashloan operation types
    enum FlashLoanOperation {
        LEVERAGE, // Deposit flow: increase leverage
        DELEVERAGE // Withdraw flow: decrease leverage
    }

    /// @notice Data passed through flashloan callback
    struct FlashLoanData {
        FlashLoanOperation operation;
        uint256 targetAmount; // Amount to deploy or free (in asset terms)
    }

    /// The token posted as collateral in the loop.
    address public immutable collateralToken;

    /// @notice Target leverage ratio in WAD (e.g., 3e18 = 3x leverage)
    /// @dev leverage = collateralValue / (collateralValue - debtValue) = 1 / (1 - LTV)
    uint256 public targetLeverageRatio;

    /// @notice Buffer tolerance in WAD (e.g., 0.5e18 = +/- 0.5x triggers tend)
    /// @dev Bounds are [targetLeverageRatio - buffer, targetLeverageRatio + buffer]
    uint256 public leverageBuffer;

    /// @notice Maximum leverage ratio in WAD (e.g., 10e18 = 10x leverage)
    /// Will trigger a tend if the current leverage ratio exceeds this value.
    uint256 public maxLeverageRatio;

    /// @notice Slippage tolerance (in basis points) for swaps.
    uint64 public slippage;

    /// The max the base fee (in gwei) will be for a tend.
    uint256 public maxGasPriceToTend;

    /// Lower limit on flashloan size.
    uint256 public minAmountToBorrow;

    uint256 public depositLimit;

    mapping(address => bool) public allowed;

    constructor(
        address _asset,
        string memory _name,
        address _collateralToken
    ) BaseHealthCheck(_asset, _name) {
        collateralToken = _collateralToken;

        depositLimit = type(uint256).max;
        // Allow self so we can use availableDepositLimit() to get the max deposit amount.
        allowed[address(this)] = true;

        // Leverage ratio defaults: 3x target, 0.5x buffer
        targetLeverageRatio = 3e18;
        leverageBuffer = 0.25e18;
        maxLeverageRatio = 4e18;

        maxGasPriceToTend = 200 * 1e9;
        slippage = 50;

        _setLossLimitRatio(10);
        _setProfitLimitRatio(1_000);
    }

    /*//////////////////////////////////////////////////////////////
                            SETTERS
    //////////////////////////////////////////////////////////////*/

    function setDepositLimit(uint256 _depositLimit) external onlyManagement {
        depositLimit = _depositLimit;
    }

    function setAllowed(
        address _address,
        bool _allowed
    ) external onlyManagement {
        allowed[_address] = _allowed;
    }

    // TODO: HOW do we set it to unwind, or just hold collataeral? Is 0 target possible?
    function setLeverageParams(
        uint256 _targetLeverageRatio,
        uint256 _leverageBuffer,
        uint256 _maxLeverageRatio
    ) external onlyManagement {
        if (_targetLeverageRatio == 0) {
            require(_leverageBuffer == 0, "buffer must be 0 if target is 0");
        } else {
            require(_targetLeverageRatio >= WAD, "leverage < 1x");
            require(_leverageBuffer >= 0.01e18, "buffer too small");
            require(_targetLeverageRatio > _leverageBuffer, "target < buffer");
        }

        require(
            _maxLeverageRatio >= _targetLeverageRatio + _leverageBuffer,
            "max leverage < target + buffer"
        );

        // Ensure max leverage doesn't exceed LLT
        uint256 maxLTV = WAD - (WAD * WAD) / _maxLeverageRatio;
        require(maxLTV < getLiquidateCollateralFactor(), "exceeds LLTV");

        targetLeverageRatio = _targetLeverageRatio;
        leverageBuffer = _leverageBuffer;
        maxLeverageRatio = _maxLeverageRatio;
    }

    function setMaxGasPriceToTend(
        uint256 _maxGasPriceToTend
    ) external onlyManagement {
        maxGasPriceToTend = _maxGasPriceToTend;
    }

    function setSlippage(uint256 _slippage) external onlyManagement {
        require(_slippage < MAX_BPS, "slippage");
        slippage = uint64(_slippage);
    }

    function setMinAmountToBorrow(
        uint256 _minAmountToBorrow
    ) external onlyManagement {
        minAmountToBorrow = _minAmountToBorrow;
    }

    /*//////////////////////////////////////////////////////////////
                NEEDED TO BE OVERRIDDEN BY STRATEGIST
    //////////////////////////////////////////////////////////////*/

    function _deployFunds(uint256 _amount) internal virtual override accrue {}

    function _freeFunds(uint256 _amount) internal virtual override accrue {
        _delever(_amount);
    }

    function _harvestAndReport()
        internal
        virtual
        override
        accrue
        returns (uint256 _totalAssets)
    {
        _claimAndSellRewards();

        _lever(
            Math.min(balanceOfAsset(), availableDepositLimit(address(this)))
        );

        _totalAssets = estimatedTotalAssets();
    }

    function estimatedTotalAssets() public view virtual returns (uint256) {
        return
            balanceOfAsset() +
            _collateralToAsset(balanceOfCollateral()) -
            balanceOfDebt();
    }

    /*//////////////////////////////////////////////////////////////
                    OPTIONAL TO OVERRIDE BY STRATEGIST
    //////////////////////////////////////////////////////////////*/

    function availableDepositLimit(
        address _owner
    ) public view virtual override returns (uint256) {
        if (!allowed[_owner]) return 0;

        if (_isSupplyPaused() || _isBorrowPaused()) return 0;

        uint256 totalAssets = TokenizedStrategy.totalAssets();
        uint256 limit = depositLimit > totalAssets
            ? depositLimit - totalAssets
            : 0;

        uint256 targetLTV = _getTargetLTV();
        if (targetLTV == 0) return 0;

        uint256 maxDepositFromCollateral = _maxCollateralDeposit();
        if (maxDepositFromCollateral == 0) return 0;

        // Max collateral capacity converted to deposit amount
        // Total collateral = deposit * L, so deposit = collateral / L = collateral * (1 - targetLTV)
        maxDepositFromCollateral = maxDepositFromCollateral == type(uint256).max
            ? maxDepositFromCollateral
            : (_collateralToAsset(maxDepositFromCollateral) *
                (WAD - targetLTV)) / WAD;

        // Max deposit based on borrow capacity
        // Debt = deposit * (L - 1), so deposit = debt / (L - 1) = debt * (1 - targetLTV) / targetLTV
        uint256 maxBorrow = _maxBorrowAmount();
        if (maxBorrow == 0) return 0;

        uint256 maxDepositFromBorrow = (maxBorrow * (WAD - targetLTV)) /
            targetLTV;

        return
            Math.min(
                limit,
                Math.min(maxDepositFromCollateral, maxDepositFromBorrow)
            );
    }

    function availableWithdrawLimit(
        address /*_owner*/
    ) public view virtual override returns (uint256) {
        return type(uint256).max;
    }

    function _tend(uint256 _totalIdle) internal virtual override accrue {
        _lever(_totalIdle);
    }

    function _tendTrigger() internal view virtual override returns (bool) {
        if (_isLiquidatable()) return true;
        if (TokenizedStrategy.totalAssets() == 0) return false;
        if (_isSupplyPaused() || _isBorrowPaused()) return false;

        uint256 currentLeverage = getCurrentLeverageRatio();

        if (currentLeverage > maxLeverageRatio) {
            return true;
        }

        uint256 _targetLeverageRatio = targetLeverageRatio;
        if (_targetLeverageRatio == 0) {
            return currentLeverage > 0 && _isBaseFeeAcceptable();
        }

        if (balanceOfAsset() > minAmountToBorrow) {
            return _isBaseFeeAcceptable();
        }

        // Check if outside buffer zone
        uint256 upperBound = _targetLeverageRatio + leverageBuffer;
        uint256 lowerBound = _targetLeverageRatio - leverageBuffer;

        if (currentLeverage < lowerBound || currentLeverage > upperBound) {
            return _isBaseFeeAcceptable();
        }

        return false;
    }

    /*//////////////////////////////////////////////////////////////
                        FLASHLOAN OPERATIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Adjust position to target leverage ratio
    /// @dev Handles three cases: lever up, delever, or just deploy _amount
    function _lever(uint256 _amount) internal virtual {
        (uint256 currentCollateralValue, uint256 currentDebt, ) = position();
        uint256 currentEquity = currentCollateralValue - currentDebt + _amount;
        (, uint256 targetDebt) = getTargetPosition(currentEquity);

        if (targetDebt > currentDebt) {
            // CASE 1: Need MORE debt → leverage up via flashloan
            uint256 flashloanAmount = targetDebt - currentDebt;

            if (flashloanAmount <= minAmountToBorrow) {
                // Too small for flashloan, just repay debt with available assets
                _repay(Math.min(_amount, balanceOfDebt()));
                return;
            }

            bytes memory data = abi.encode(
                FlashLoanData({
                    operation: FlashLoanOperation.LEVERAGE,
                    targetAmount: _amount
                })
            );
            _executeFlashloan(address(asset), flashloanAmount, data);
        } else if (currentDebt > targetDebt) {
            // CASE 2: Need LESS debt → deleverage
            uint256 debtToRepay = currentDebt - targetDebt;

            if (_amount >= debtToRepay) {
                // _amount covers the debt repayment, just repay and supply the rest
                _repay(debtToRepay);
                uint256 remainder = _amount - debtToRepay;
                if (remainder > 0) {
                    _supplyCollateral(_convertAssetAndCheckSlippage(remainder));
                }
                return;
            }

            // First repay what is loose.
            _repay(_amount);

            // Flashloan to repay debt, withdraw collateral to cover
            uint256 collateralToWithdraw = (_assetToCollateral(
                debtToRepay - _amount
            ) * (MAX_BPS + slippage)) / MAX_BPS;

            bytes memory data = abi.encode(
                FlashLoanData({
                    operation: FlashLoanOperation.DELEVERAGE,
                    targetAmount: collateralToWithdraw
                })
            );
            _executeFlashloan(address(asset), debtToRepay - _amount, data);
        } else {
            // CASE 3: At target debt → just deploy _amount if any
            _repay(Math.min(_amount, balanceOfDebt()));
        }
    }

    /// @notice Deleverage position using flashloan
    function _delever(uint256 _amountNeeded) internal virtual {
        (uint256 valueOfCollateral, uint256 currentDebt, ) = position();

        if (currentDebt == 0) {
            // No debt, just withdraw collateral
            uint256 toWithdraw = Math.min(
                _assetToCollateral(_amountNeeded),
                balanceOfCollateral()
            );
            _withdrawCollateral(toWithdraw);
            _convertCollateralAndCheckSlippage(toWithdraw);
            return;
        }

        uint256 equity = valueOfCollateral - currentDebt;

        uint256 targetEquity = equity > _amountNeeded
            ? equity - _amountNeeded
            : 0;
        (, uint256 targetDebt) = getTargetPosition(targetEquity);

        uint256 debtToRepay = currentDebt > targetDebt // Add slippage to account for swap back.
            ? ((currentDebt - targetDebt) * (MAX_BPS + slippage)) / MAX_BPS
            : 0;

        uint256 collateralToWithdraw = _assetToCollateral(
            debtToRepay + _amountNeeded
        );

        if (debtToRepay == 0 && collateralToWithdraw != 0) {
            // No debt to repay, just withdraw collateral
            _withdrawCollateral(collateralToWithdraw);
            _convertCollateralAndCheckSlippage(collateralToWithdraw);
            return;
        }

        bytes memory data = abi.encode(
            FlashLoanData({
                operation: FlashLoanOperation.DELEVERAGE,
                targetAmount: collateralToWithdraw
            })
        );

        _executeFlashloan(address(asset), debtToRepay, data);
    }

    /// @notice Called by protocol-specific flashloan callback
    function _onFlashloanReceived(
        uint256 assets,
        bytes memory data
    ) internal virtual {
        FlashLoanData memory params = abi.decode(data, (FlashLoanData));

        if (params.operation == FlashLoanOperation.LEVERAGE) {
            _executeLeverageCallback(assets, params);
        } else if (params.operation == FlashLoanOperation.DELEVERAGE) {
            _executeDeleverageCallback(assets, params);
        } else {
            revert("invalid operation");
        }
    }

    function _executeLeverageCallback(
        uint256 flashloanAmount,
        FlashLoanData memory params
    ) internal virtual {
        // Total asset to convert = deposit + flashloan
        uint256 totalToConvert = params.targetAmount + flashloanAmount;

        // Convert all asset to collateral
        uint256 collateralReceived = _convertAssetAndCheckSlippage(
            totalToConvert
        );

        // Supply collateral
        _supplyCollateral(collateralReceived);

        // Borrow to repay flashloan
        _borrow(flashloanAmount);
    }

    function _executeDeleverageCallback(
        uint256 flashloanAmount,
        FlashLoanData memory params
    ) internal virtual {
        // Use flashloaned amount to repay debt
        _repay(Math.min(flashloanAmount, balanceOfDebt()));

        uint256 collateralToWithdraw = Math.min(
            params.targetAmount,
            balanceOfCollateral()
        );
        // Withdraw
        _withdrawCollateral(collateralToWithdraw);

        // Convert collateral back to asset
        _convertCollateralAndCheckSlippage(collateralToWithdraw);
    }

    /*//////////////////////////////////////////////////////////////
                        MANAGEMENT FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Emergency full position close via flashloan
    function manualFullUnwind() external onlyEmergencyAuthorized {
        _delever(TokenizedStrategy.totalAssets());
    }

    /// @notice Manual: supply collateral
    function manualSupplyCollateral(
        uint256 amount
    ) external onlyEmergencyAuthorized {
        _supplyCollateral(Math.min(amount, balanceOfCollateralToken()));
    }

    /// @notice Manual: withdraw collateral
    function manualWithdrawCollateral(
        uint256 amount
    ) external onlyEmergencyAuthorized {
        _withdrawCollateral(Math.min(amount, balanceOfCollateral()));
    }

    /// @notice Manual: borrow from protocol
    function manualBorrow(uint256 amount) external onlyEmergencyAuthorized {
        _borrow(amount);
    }

    /// @notice Manual: repay debt
    function manualRepay(uint256 amount) external onlyEmergencyAuthorized {
        _repay(Math.min(amount, balanceOfAsset()));
    }

    function convertCollateralToAsset(
        uint256 amount
    ) external onlyEmergencyAuthorized {
        _convertCollateralAndCheckSlippage(
            Math.min(amount, balanceOfCollateralToken())
        );
    }

    function convertAssetToCollateral(
        uint256 amount
    ) external onlyEmergencyAuthorized {
        _convertAssetAndCheckSlippage(Math.min(amount, balanceOfAsset()));
    }

    function _convertCollateralAndCheckSlippage(
        uint256 amount
    ) internal returns (uint256) {
        uint256 converted = _convertCollateralToAsset(amount);
        require(converted >= _getAmountOut(amount, false), "slippage: asset");
        return converted;
    }

    function _convertAssetAndCheckSlippage(
        uint256 amount
    ) internal returns (uint256) {
        uint256 converted = _convertAssetToCollateral(amount);
        require(
            converted >= _getAmountOut(amount, true),
            "slippage: collateral"
        );
        return converted;
    }

    /*//////////////////////////////////////////////////////////////
                    ABSTRACT - PROTOCOL SPECIFIC
    //////////////////////////////////////////////////////////////*/

    /// @notice Accrue interest before state changing functions
    function _accrueInterest() internal virtual {
        // No-op by default
    }

    /// @notice Execute a flashloan through the protocol
    function _executeFlashloan(
        address token,
        uint256 amount,
        bytes memory data
    ) internal virtual;

    /// @notice Max available flashloan from protocol
    function maxFlashloan() public view virtual returns (uint256);

    /// @notice Get oracle price (loan token value per 1 collateral token, ORACLE_PRICE_SCALE)
    /// @dev Must return raw oracle price in 1e36 scale for precision in conversions
    function _getCollateralPrice() internal view virtual returns (uint256);

    /// @notice Supply collateral (with asset->collateral conversion)
    function _supplyCollateral(uint256 amount) internal virtual;

    /// @notice Withdraw collateral (with collateral->asset conversion)
    function _withdrawCollateral(uint256 amount) internal virtual;

    function _borrow(uint256 amount) internal virtual;

    function _repay(uint256 amount) internal virtual;

    function _isSupplyPaused() internal view virtual returns (bool);

    function _isBorrowPaused() internal view virtual returns (bool);

    function _isLiquidatable() internal view virtual returns (bool);

    function _maxCollateralDeposit() internal view virtual returns (uint256);

    function _maxBorrowAmount() internal view virtual returns (uint256);

    function getLiquidateCollateralFactor()
        public
        view
        virtual
        returns (uint256);

    function balanceOfCollateral() public view virtual returns (uint256);

    function balanceOfDebt() public view virtual returns (uint256);

    /// @notice Convert asset to collateral tokens
    function _convertAssetToCollateral(
        uint256 amount
    ) internal virtual returns (uint256);

    /// @notice Convert collateral tokens to asset
    function _convertCollateralToAsset(
        uint256 amount
    ) internal virtual returns (uint256);

    /*//////////////////////////////////////////////////////////////
                            VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function balanceOfAsset() public view virtual returns (uint256) {
        return asset.balanceOf(address(this));
    }

    function balanceOfCollateralToken() public view virtual returns (uint256) {
        return ERC20(collateralToken).balanceOf(address(this));
    }

    /// @notice Get collateral value in asset terms
    /// @dev price is in ORACLE_PRICE_SCALE (1e36), so we divide by 1e36
    function _collateralToAsset(
        uint256 collateralAmount
    ) internal view virtual returns (uint256) {
        if (collateralAmount == 0) return 0;
        return (collateralAmount * _getCollateralPrice()) / ORACLE_PRICE_SCALE;
    }

    /// @notice Get collateral amount for asset value
    /// @dev price is in ORACLE_PRICE_SCALE (1e36), so we multiply by 1e36
    function _assetToCollateral(
        uint256 assetAmount
    ) internal view virtual returns (uint256) {
        if (assetAmount == 0) return 0;
        uint256 price = _getCollateralPrice();
        return (assetAmount * ORACLE_PRICE_SCALE) / price;
    }

    /// @notice Get current leverage ratio
    function getCurrentLeverageRatio() public view virtual returns (uint256) {
        (uint256 collateralValue, uint256 debt, ) = position();
        if (collateralValue == 0) return 0;
        if (debt >= collateralValue) return type(uint256).max;
        return (collateralValue * WAD) / (collateralValue - debt);
    }

    /// @notice Get current LTV
    function getCurrentLTV() external view virtual returns (uint256) {
        (, , uint256 currentLTV) = position();
        return currentLTV;
    }

    function position()
        public
        view
        virtual
        returns (uint256 collateralValue, uint256 debt, uint256 currentLTV)
    {
        uint256 collateral = balanceOfCollateral();
        collateralValue = _collateralToAsset(collateral);
        debt = balanceOfDebt();
        currentLTV = collateralValue > 0 ? (debt * WAD) / collateralValue : 0;
    }

    function getTargetPosition(
        uint256 _equity
    ) public view virtual returns (uint256 collateral, uint256 debt) {
        uint256 targetCollateral = (_equity * targetLeverageRatio) / WAD;
        uint256 targetDebt = targetCollateral > _equity
            ? targetCollateral - _equity
            : 0;
        return (targetCollateral, targetDebt);
    }

    /// @notice Get target LTV derived from leverage ratio
    function _getTargetLTV() internal view virtual returns (uint256) {
        if (targetLeverageRatio <= WAD) return 0;
        return WAD - (WAD * WAD) / targetLeverageRatio;
    }

    /// @notice Get amount out with slippage
    function _getAmountOut(
        uint256 amount,
        bool assetToCollateral
    ) internal view virtual returns (uint256) {
        if (amount == 0) return 0;
        uint256 converted = assetToCollateral
            ? _assetToCollateral(amount)
            : _collateralToAsset(amount);
        return (converted * (MAX_BPS - slippage)) / MAX_BPS;
    }

    function _isBaseFeeAcceptable() internal view virtual returns (bool) {
        return block.basefee <= maxGasPriceToTend;
    }

    /*//////////////////////////////////////////////////////////////
                        HARVEST / TOKEN CONVERSIONS
    //////////////////////////////////////////////////////////////*/

    function _claimAndSellRewards() internal virtual;

    /*//////////////////////////////////////////////////////////////
                            EMERGENCY
    //////////////////////////////////////////////////////////////*/

    function _emergencyWithdraw(uint256 _amount) internal virtual override {
        // Try full unwind first
        uint256 debt = balanceOfDebt();
        if (debt > 0) {
            _delever(Math.min(_amount, TokenizedStrategy.totalAssets()));
        } else if (_amount > 0) {
            _amount = Math.min(_amount, balanceOfCollateral());
            _withdrawCollateral(_amount);
            _convertCollateralAndCheckSlippage(_amount);
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title IMorphoFlashLoanCallback
/// @notice Interface that contracts must implement to use Morpho's flashLoan callback.
interface IMorphoFlashLoanCallback {
    /// @notice Callback called when a flash loan occurs.
    /// @dev The callback is called only if data is not empty.
    /// @param assets The amount of assets that was flash loaned.
    /// @param data Arbitrary data passed to the flashLoan function.
    function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}

File 15 of 43 : IOracle.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

interface IOracle {
    /// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.
    function price() external view returns (uint256);
}

File 16 of 43 : MarketParamsLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

import {Id, MarketParams} from "../../interfaces/morpho/IMorpho.sol";

library MarketParamsLib {
    uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;

    function id(
        MarketParams memory marketParams
    ) internal pure returns (Id marketParamsId) {
        assembly ("memory-safe") {
            marketParamsId := keccak256(
                marketParams,
                MARKET_PARAMS_BYTES_LENGTH
            )
        }
    }
}

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

import {Id, MarketParams, Market, IMorpho} from "../../../interfaces/morpho/IMorpho.sol";
import {IIrm} from "../../../interfaces/morpho/IIrm.sol";

import {MathLib} from "../MathLib.sol";
import {UtilsLib} from "../UtilsLib.sol";
import {MorphoLib} from "./MorphoLib.sol";
import {SharesMathLib} from "../SharesMathLib.sol";
import {MarketParamsLib} from "../MarketParamsLib.sol";

library MorphoBalancesLib {
    using MathLib for uint256;
    using MathLib for uint128;
    using UtilsLib for uint256;
    using MorphoLib for IMorpho;
    using SharesMathLib for uint256;
    using MarketParamsLib for MarketParams;

    function expectedMarketBalances(
        IMorpho morpho,
        MarketParams memory marketParams
    ) internal view returns (uint256, uint256, uint256, uint256) {
        Id id = marketParams.id();
        Market memory market = morpho.market(id);

        uint256 elapsed = block.timestamp - market.lastUpdate;

        if (
            elapsed != 0 &&
            market.totalBorrowAssets != 0 &&
            marketParams.irm != address(0)
        ) {
            uint256 borrowRate = IIrm(marketParams.irm).borrowRateView(
                marketParams,
                market
            );
            uint256 interest = market.totalBorrowAssets.wMulDown(
                borrowRate.wTaylorCompounded(elapsed)
            );
            market.totalBorrowAssets += interest.toUint128();
            market.totalSupplyAssets += interest.toUint128();

            if (market.fee != 0) {
                uint256 feeAmount = interest.wMulDown(market.fee);
                uint256 feeShares = feeAmount.toSharesDown(
                    market.totalSupplyAssets - feeAmount,
                    market.totalSupplyShares
                );
                market.totalSupplyShares += feeShares.toUint128();
            }
        }

        return (
            market.totalSupplyAssets,
            market.totalSupplyShares,
            market.totalBorrowAssets,
            market.totalBorrowShares
        );
    }

    function expectedTotalSupplyAssets(
        IMorpho morpho,
        MarketParams memory marketParams
    ) internal view returns (uint256 totalSupplyAssets) {
        (totalSupplyAssets, , , ) = expectedMarketBalances(
            morpho,
            marketParams
        );
    }

    function expectedTotalBorrowAssets(
        IMorpho morpho,
        MarketParams memory marketParams
    ) internal view returns (uint256 totalBorrowAssets) {
        (, , totalBorrowAssets, ) = expectedMarketBalances(
            morpho,
            marketParams
        );
    }

    function expectedTotalSupplyShares(
        IMorpho morpho,
        MarketParams memory marketParams
    ) internal view returns (uint256 totalSupplyShares) {
        (, totalSupplyShares, , ) = expectedMarketBalances(
            morpho,
            marketParams
        );
    }

    function expectedSupplyAssets(
        IMorpho morpho,
        MarketParams memory marketParams,
        address user
    ) internal view returns (uint256) {
        Id id = marketParams.id();
        uint256 supplyShares = morpho.supplyShares(id, user);
        (
            uint256 totalSupplyAssets,
            uint256 totalSupplyShares,
            ,

        ) = expectedMarketBalances(morpho, marketParams);

        return supplyShares.toAssetsDown(totalSupplyAssets, totalSupplyShares);
    }

    function expectedBorrowAssets(
        IMorpho morpho,
        MarketParams memory marketParams,
        address user
    ) internal view returns (uint256) {
        Id id = marketParams.id();
        uint256 borrowShares = morpho.borrowShares(id, user);
        (
            ,
            ,
            uint256 totalBorrowAssets,
            uint256 totalBorrowShares
        ) = expectedMarketBalances(morpho, marketParams);

        return borrowShares.toAssetsUp(totalBorrowAssets, totalBorrowShares);
    }
}

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

import {IMorpho, Id} from "../../../interfaces/morpho/IMorpho.sol";
import {MorphoStorageLib} from "./MorphoStorageLib.sol";

library MorphoLib {
    function supplyShares(
        IMorpho morpho,
        Id id,
        address user
    ) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.positionSupplySharesSlot(id, user)
        );
        return uint256(morpho.extSloads(slot)[0]);
    }

    function borrowShares(
        IMorpho morpho,
        Id id,
        address user
    ) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user)
        );
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function collateral(
        IMorpho morpho,
        Id id,
        address user
    ) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user)
        );
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function totalSupplyAssets(
        IMorpho morpho,
        Id id
    ) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id)
        );
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function totalSupplyShares(
        IMorpho morpho,
        Id id
    ) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id)
        );
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function totalBorrowAssets(
        IMorpho morpho,
        Id id
    ) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id)
        );
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function totalBorrowShares(
        IMorpho morpho,
        Id id
    ) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id)
        );
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function lastUpdate(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.marketLastUpdateAndFeeSlot(id)
        );
        return uint128(uint256(morpho.extSloads(slot)[0]));
    }

    function fee(IMorpho morpho, Id id) internal view returns (uint256) {
        bytes32[] memory slot = _array(
            MorphoStorageLib.marketLastUpdateAndFeeSlot(id)
        );
        return uint256(morpho.extSloads(slot)[0] >> 128);
    }

    function _array(bytes32 x) private pure returns (bytes32[] memory) {
        bytes32[] memory res = new bytes32[](1);
        res[0] = x;
        return res;
    }
}

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

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

library SharesMathLib {
    using MathLib for uint256;

    uint256 internal constant VIRTUAL_SHARES = 1e6;
    uint256 internal constant VIRTUAL_ASSETS = 1;

    function toSharesDown(
        uint256 assets,
        uint256 totalAssets,
        uint256 totalShares
    ) internal pure returns (uint256) {
        return
            assets.mulDivDown(
                totalShares + VIRTUAL_SHARES,
                totalAssets + VIRTUAL_ASSETS
            );
    }

    function toAssetsDown(
        uint256 shares,
        uint256 totalAssets,
        uint256 totalShares
    ) internal pure returns (uint256) {
        return
            shares.mulDivDown(
                totalAssets + VIRTUAL_ASSETS,
                totalShares + VIRTUAL_SHARES
            );
    }

    function toSharesUp(
        uint256 assets,
        uint256 totalAssets,
        uint256 totalShares
    ) internal pure returns (uint256) {
        return
            assets.mulDivUp(
                totalShares + VIRTUAL_SHARES,
                totalAssets + VIRTUAL_ASSETS
            );
    }

    function toAssetsUp(
        uint256 shares,
        uint256 totalAssets,
        uint256 totalShares
    ) internal pure returns (uint256) {
        return
            shares.mulDivUp(
                totalAssets + VIRTUAL_ASSETS,
                totalShares + VIRTUAL_SHARES
            );
    }
}

File 20 of 43 : IMerkleDistributor.sol
pragma solidity ^0.8.18;

interface IMerklDistributor {
    /// @notice Claims rewards for a given set of users
    /// @dev Anyone may call this function for anyone else, funds go to destination regardless, it's just a question of
    /// who provides the proof and pays the gas: `msg.sender` is used only for addresses that require a trusted operator
    /// @param users Recipient of tokens
    /// @param tokens ERC20 claimed
    /// @param amounts Amount of tokens that will be sent to the corresponding users
    /// @param proofs Array of hashes bridging from a leaf `(hash of user | token | amount)` to the Merkle root
    function claim(
        address[] calldata users,
        address[] calldata tokens,
        uint256[] calldata amounts,
        bytes32[][] calldata proofs
    ) external;
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

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

import {AuctionFactory, Auction} from "../Auctions/AuctionFactory.sol";
import {BaseSwapper} from "./BaseSwapper.sol";

/**
 *   @title AuctionSwapper
 *   @author yearn.fi
 *   @dev Helper contract for a strategy to use dutch auctions for token sales.
 *
 *   This contract is meant to be inherited by a V3 strategy in order
 *   to easily integrate dutch auctions into a contract for token swaps.
 *
 *   AUCTION SETUP:
 *   - The strategist needs to implement a way to call `_setAuction()`
 *     to set the auction contract address for token sales
 *   - `useAuction` defaults to false but is automatically set to true
 *     when a non-zero auction address is set via `_setAuction()`
 *   - Auctions can be manually enabled/disabled using `_setUseAuction()`
 *
 *   PERMISSIONLESS OPERATIONS:
 *   - `kickAuction()` is public and permissionless - anyone can trigger
 *     auctions when conditions are met (sufficient balance, auctions enabled)
 *   - This allows for automated auction triggering by bots or external systems
 *
 *   AUCTION TRIGGER INTEGRATION:
 *   - Implements `auctionTrigger()` for integration with CommonAuctionTrigger
 *   - Returns encoded calldata for `kickAuction()` when conditions are met
 *   - Provides smart logic to prevent duplicate auctions and handle edge cases
 *
 *   HOOKS:
 *   - The contract can act as a `hook` contract for the auction with the
 *     ability to override functions to implement custom hooks
 *   - If hooks are not desired, call `setHookFlags()` on the auction contract
 *     to avoid unnecessary gas for unused functions
 */
contract AuctionSwapper is BaseSwapper {
    using SafeERC20 for ERC20;

    event AuctionSet(address indexed auction);
    event UseAuctionSet(bool indexed useAuction);

    /// @notice Address of the specific Auction contract this strategy uses for token sales.
    address public auction;

    /// @notice Whether to use auctions for token swaps.
    /// @dev Defaults to false but automatically set to true when setting a non-zero auction address.
    ///      Can be manually controlled via _setUseAuction() for fine-grained control.
    bool public useAuction;

    /*//////////////////////////////////////////////////////////////
                    AUCTION STARTING AND STOPPING
    //////////////////////////////////////////////////////////////*/

    /// @notice Set the auction contract to use.
    /// @dev Automatically enables auctions (useAuction = true) when setting a non-zero address.
    /// @param _auction The auction contract address. Must have this contract as receiver.
    function _setAuction(address _auction) internal virtual {
        if (_auction != address(0)) {
            require(
                Auction(_auction).receiver() == address(this),
                "wrong receiver"
            );
            // Automatically enable auctions when setting a non-zero auction address
            if (!useAuction) {
                useAuction = true;
                emit UseAuctionSet(true);
            }
        }
        auction = _auction;
        emit AuctionSet(_auction);
    }

    /// @notice Manually enable or disable auction usage.
    /// @dev Can be used to override the auto-enable behavior or temporarily disable auctions.
    /// @param _useAuction Whether to use auctions for token swaps.
    function _setUseAuction(bool _useAuction) internal virtual {
        useAuction = _useAuction;
        emit UseAuctionSet(_useAuction);
    }

    /**
     * @notice Return how much of a token could currently be kicked into auction.
     * @dev Includes both contract balance and tokens already in the auction contract.
     * @param _token The token that could be sold in auction.
     * @return The total amount of `_token` available for auction (0 if auctions disabled).
     */
    function kickable(address _token) public view virtual returns (uint256) {
        if (!useAuction) return 0;

        address _auction = auction;
        if (_auction == address(0)) return 0;

        if (
            Auction(_auction).isActive(_token) &&
            Auction(_auction).available(_token) > 0
        ) {
            return 0;
        }

        return
            ERC20(_token).balanceOf(address(this)) +
            ERC20(_token).balanceOf(_auction);
    }

    /**
     * @notice Kick an auction for a given token (PERMISSIONLESS).
     * @dev Anyone can call this function to trigger auctions when conditions are met.
     *      Useful for automated systems, bots, or manual triggering.
     * @param _from The token to be sold in the auction.
     * @return The amount of tokens that were kicked into the auction.
     */
    function kickAuction(address _from) external virtual returns (uint256) {
        return _kickAuction(_from);
    }

    /**
     * @dev Internal function to kick an auction for a given token.
     * @param _from The token that was being sold.
     */
    function _kickAuction(address _from) internal virtual returns (uint256) {
        require(useAuction, "useAuction is false");
        address _auction = auction;

        if (Auction(_auction).isActive(_from)) {
            if (Auction(_auction).available(_from) > 0) {
                return 0;
            }

            Auction(_auction).settle(_from);
        }

        uint256 _balance = ERC20(_from).balanceOf(address(this));
        if (_balance > 0) {
            ERC20(_from).safeTransfer(_auction, _balance);
        }

        return Auction(_auction).kick(_from);
    }

    /*//////////////////////////////////////////////////////////////
                        AUCTION TRIGGER INTERFACE
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Default auction trigger implementation for CommonAuctionTrigger integration.
     * @dev Returns whether an auction should be kicked and the encoded calldata to do so.
     *      This enables automated auction triggering through external trigger systems.
     * @param _from The token that could be sold in an auction.
     * @return shouldKick True if an auction should be kicked for this token.
     * @return data Encoded calldata for `kickAuction(_from)` if shouldKick is true,
     *              otherwise a descriptive error message explaining why not.
     */
    function auctionTrigger(
        address _from
    ) external view virtual returns (bool shouldKick, bytes memory data) {
        address _auction = auction;
        if (_auction == address(0)) {
            return (false, bytes("No auction set"));
        }

        if (!useAuction) {
            return (false, bytes("Auctions disabled"));
        }

        uint256 kickableAmount = kickable(_from);

        if (kickableAmount != 0 && kickableAmount >= minAmountToSell) {
            return (true, abi.encodeCall(this.kickAuction, (_from)));
        }

        return (false, bytes("not enough kickable"));
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;

import "./IUniswapV3SwapCallback.sol";

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(
        ExactInputSingleParams calldata params
    ) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(
        ExactInputParams calldata params
    ) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(
        ExactOutputSingleParams calldata params
    ) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(
        ExactOutputParams calldata params
    ) external payable returns (uint256 amountIn);

    // Taken from https://soliditydeveloper.com/uniswap3
    // Manually added to the interface
    function refundETH() external payable;
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

/**
 * @title BaseSwapper
 * @author yearn.fi
 * @dev Base contract for all swapper contracts except TradeFactorySwapper.
 *      Contains the common minAmountToSell variable that most swappers need.
 */
contract BaseSwapper {
    /// @notice Minimum amount of tokens to sell in a swap.
    uint256 public minAmountToSell;

    /**
     * @dev Set the minimum amount to sell in a swap.
     * @param _minAmountToSell Minimum amount of tokens needed to execute a swap.
     */
    function _setMinAmountToSell(uint256 _minAmountToSell) internal virtual {
        minAmountToSell = _minAmountToSell;
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

import {BaseStrategy, ERC20} from "@tokenized-strategy/BaseStrategy.sol";

/**
 *   @title Base Health Check
 *   @author Yearn.finance
 *   @notice This contract can be inherited by any Yearn
 *   V3 strategy wishing to implement a health check during
 *   the `report` function in order to prevent any unexpected
 *   behavior from being permanently recorded as well as the
 *   `checkHealth` modifier.
 *
 *   A strategist simply needs to inherit this contract. Set
 *   the limit ratios to the desired amounts and then
 *   override `_harvestAndReport()` just as they otherwise
 *  would. If the profit or loss that would be recorded is
 *   outside the acceptable bounds the tx will revert.
 *
 *   The healthcheck does not prevent a strategy from reporting
 *   losses, but rather can make sure manual intervention is
 *   needed before reporting an unexpected loss or profit.
 */
abstract contract BaseHealthCheck is BaseStrategy {
    // Can be used to determine if a healthcheck should be called.
    // Defaults to true;
    bool public doHealthCheck = true;

    uint256 internal constant MAX_BPS = 10_000;

    // Default profit limit to 100%.
    uint16 private _profitLimitRatio = uint16(MAX_BPS);

    // Defaults loss limit to 0.
    uint16 private _lossLimitRatio;

    constructor(
        address _asset,
        string memory _name
    ) BaseStrategy(_asset, _name) {}

    /**
     * @notice Returns the current profit limit ratio.
     * @dev Use a getter function to keep the variable private.
     * @return . The current profit limit ratio.
     */
    function profitLimitRatio() public view returns (uint256) {
        return _profitLimitRatio;
    }

    /**
     * @notice Returns the current loss limit ratio.
     * @dev Use a getter function to keep the variable private.
     * @return . The current loss limit ratio.
     */
    function lossLimitRatio() public view returns (uint256) {
        return _lossLimitRatio;
    }

    /**
     * @notice Set the `profitLimitRatio`.
     * @dev Denominated in basis points. I.E. 1_000 == 10%.
     * @param _newProfitLimitRatio The mew profit limit ratio.
     */
    function setProfitLimitRatio(
        uint256 _newProfitLimitRatio
    ) external onlyManagement {
        _setProfitLimitRatio(_newProfitLimitRatio);
    }

    /**
     * @dev Internally set the profit limit ratio. Denominated
     * in basis points. I.E. 1_000 == 10%.
     * @param _newProfitLimitRatio The mew profit limit ratio.
     */
    function _setProfitLimitRatio(uint256 _newProfitLimitRatio) internal {
        require(_newProfitLimitRatio > 0, "!zero profit");
        require(_newProfitLimitRatio <= type(uint16).max, "!too high");
        _profitLimitRatio = uint16(_newProfitLimitRatio);
    }

    /**
     * @notice Set the `lossLimitRatio`.
     * @dev Denominated in basis points. I.E. 1_000 == 10%.
     * @param _newLossLimitRatio The new loss limit ratio.
     */
    function setLossLimitRatio(
        uint256 _newLossLimitRatio
    ) external onlyManagement {
        _setLossLimitRatio(_newLossLimitRatio);
    }

    /**
     * @dev Internally set the loss limit ratio. Denominated
     * in basis points. I.E. 1_000 == 10%.
     * @param _newLossLimitRatio The new loss limit ratio.
     */
    function _setLossLimitRatio(uint256 _newLossLimitRatio) internal {
        require(_newLossLimitRatio < MAX_BPS, "!loss limit");
        _lossLimitRatio = uint16(_newLossLimitRatio);
    }

    /**
     * @notice Turns the healthcheck on and off.
     * @dev If turned off the next report will auto turn it back on.
     * @param _doHealthCheck Bool if healthCheck should be done.
     */
    function setDoHealthCheck(bool _doHealthCheck) public onlyManagement {
        doHealthCheck = _doHealthCheck;
    }

    /**
     * @notice OVerrides the default {harvestAndReport} to include a healthcheck.
     * @return _totalAssets New totalAssets post report.
     */
    function harvestAndReport()
        external
        override
        onlySelf
        returns (uint256 _totalAssets)
    {
        // Let the strategy report.
        _totalAssets = _harvestAndReport();

        // Run the healthcheck on the amount returned.
        _executeHealthCheck(_totalAssets);
    }

    /**
     * @dev To be called during a report to make sure the profit
     * or loss being recorded is within the acceptable bound.
     *
     * @param _newTotalAssets The amount that will be reported.
     */
    function _executeHealthCheck(uint256 _newTotalAssets) internal virtual {
        if (!doHealthCheck) {
            doHealthCheck = true;
            return;
        }

        // Get the current total assets from the implementation.
        uint256 currentTotalAssets = TokenizedStrategy.totalAssets();

        if (_newTotalAssets > currentTotalAssets) {
            require(
                ((_newTotalAssets - currentTotalAssets) <=
                    (currentTotalAssets * uint256(_profitLimitRatio)) /
                        MAX_BPS),
                "healthCheck"
            );
        } else if (currentTotalAssets > _newTotalAssets) {
            require(
                (currentTotalAssets - _newTotalAssets <=
                    ((currentTotalAssets * uint256(_lossLimitRatio)) /
                        MAX_BPS)),
                "healthCheck"
            );
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {MarketParams, Market} from "./IMorpho.sol";

interface IIrm {
    function borrowRate(
        MarketParams memory marketParams,
        Market memory market
    ) external returns (uint256);

    function borrowRateView(
        MarketParams memory marketParams,
        Market memory market
    ) external view returns (uint256);
}

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

uint256 constant WAD = 1e18;

library MathLib {
    function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD);
    }

    function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y);
    }

    function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y);
    }

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 d
    ) internal pure returns (uint256) {
        return (x * y) / d;
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 d
    ) internal pure returns (uint256) {
        return (x * y + (d - 1)) / d;
    }

    function wTaylorCompounded(
        uint256 x,
        uint256 n
    ) internal pure returns (uint256) {
        uint256 firstTerm = x * n;
        uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
        uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);

        return firstTerm + secondTerm + thirdTerm;
    }
}

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

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

library UtilsLib {
    function exactlyOneZero(
        uint256 x,
        uint256 y
    ) internal pure returns (bool z) {
        assembly {
            z := xor(iszero(x), iszero(y))
        }
    }

    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    function toUint128(uint256 x) internal pure returns (uint128) {
        require(x <= type(uint128).max, ErrorsLib.MAX_UINT128_EXCEEDED);
        return uint128(x);
    }

    function zeroFloorSub(
        uint256 x,
        uint256 y
    ) internal pure returns (uint256 z) {
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }
}

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

import {Id} from "../../../interfaces/morpho/IMorpho.sol";

library MorphoStorageLib {
    uint256 internal constant OWNER_SLOT = 0;
    uint256 internal constant FEE_RECIPIENT_SLOT = 1;
    uint256 internal constant POSITION_SLOT = 2;
    uint256 internal constant MARKET_SLOT = 3;
    uint256 internal constant IS_IRM_ENABLED_SLOT = 4;
    uint256 internal constant IS_LLTV_ENABLED_SLOT = 5;
    uint256 internal constant IS_AUTHORIZED_SLOT = 6;
    uint256 internal constant NONCE_SLOT = 7;
    uint256 internal constant ID_TO_MARKET_PARAMS_SLOT = 8;

    uint256 internal constant LOAN_TOKEN_OFFSET = 0;
    uint256 internal constant COLLATERAL_TOKEN_OFFSET = 1;
    uint256 internal constant ORACLE_OFFSET = 2;
    uint256 internal constant IRM_OFFSET = 3;
    uint256 internal constant LLTV_OFFSET = 4;

    uint256 internal constant SUPPLY_SHARES_OFFSET = 0;
    uint256 internal constant BORROW_SHARES_AND_COLLATERAL_OFFSET = 1;

    uint256 internal constant TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET = 0;
    uint256 internal constant TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET = 1;
    uint256 internal constant LAST_UPDATE_AND_FEE_OFFSET = 2;

    function positionSupplySharesSlot(
        Id id,
        address user
    ) internal pure returns (bytes32) {
        return
            bytes32(
                uint256(
                    keccak256(
                        abi.encode(
                            user,
                            keccak256(abi.encode(id, POSITION_SLOT))
                        )
                    )
                ) + SUPPLY_SHARES_OFFSET
            );
    }

    function positionBorrowSharesAndCollateralSlot(
        Id id,
        address user
    ) internal pure returns (bytes32) {
        return
            bytes32(
                uint256(
                    keccak256(
                        abi.encode(
                            user,
                            keccak256(abi.encode(id, POSITION_SLOT))
                        )
                    )
                ) + BORROW_SHARES_AND_COLLATERAL_OFFSET
            );
    }

    function marketTotalSupplyAssetsAndSharesSlot(
        Id id
    ) internal pure returns (bytes32) {
        return
            bytes32(
                uint256(keccak256(abi.encode(id, MARKET_SLOT))) +
                    TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET
            );
    }

    function marketTotalBorrowAssetsAndSharesSlot(
        Id id
    ) internal pure returns (bytes32) {
        return
            bytes32(
                uint256(keccak256(abi.encode(id, MARKET_SLOT))) +
                    TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET
            );
    }

    function marketLastUpdateAndFeeSlot(Id id) internal pure returns (bytes32) {
        return
            bytes32(
                uint256(keccak256(abi.encode(id, MARKET_SLOT))) +
                    LAST_UPDATE_AND_FEE_OFFSET
            );
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

import {Auction} from "./Auction.sol";
import {ClonableCreate2} from "../utils/ClonableCreate2.sol";

/// @title AuctionFactory
/// @notice Deploy a new Auction.
contract AuctionFactory is ClonableCreate2 {
    event DeployedNewAuction(address indexed auction, address indexed want);

    /// @notice The amount to start the auction with.
    uint256 public constant DEFAULT_STARTING_PRICE = 1_000_000;

    /// @notice Full array of all auctions deployed through this factory.
    address[] public auctions;

    constructor() {
        // Deploy the original
        original = address(new Auction());
    }

    function version() external pure returns (string memory) {
        return "1.0.3";
    }

    /**
     * @notice Creates a new auction contract.
     * @param _want Address of the token users will bid with.
     * @return _newAuction Address of the newly created auction contract.
     */
    function createNewAuction(address _want) external returns (address) {
        return
            _createNewAuction(
                _want,
                msg.sender,
                msg.sender,
                DEFAULT_STARTING_PRICE,
                bytes32(0)
            );
    }

    /**
     * @notice Creates a new auction contract.
     * @param _want Address of the token users will bid with.
     * @param _receiver Address that will receive the funds in the auction.
     * @return _newAuction Address of the newly created auction contract.
     */
    function createNewAuction(
        address _want,
        address _receiver
    ) external returns (address) {
        return
            _createNewAuction(
                _want,
                _receiver,
                msg.sender,
                DEFAULT_STARTING_PRICE,
                bytes32(0)
            );
    }

    /**
     * @notice Creates a new auction contract.
     * @param _want Address of the token users will bid with.
     * @param _receiver Address that will receive the funds in the auction.
     * @param _governance Address allowed to enable and disable auctions.
     * @return _newAuction Address of the newly created auction contract.
     */
    function createNewAuction(
        address _want,
        address _receiver,
        address _governance
    ) external returns (address) {
        return
            _createNewAuction(
                _want,
                _receiver,
                _governance,
                DEFAULT_STARTING_PRICE,
                bytes32(0)
            );
    }

    /**
     * @notice Creates a new auction contract.
     * @param _want Address of the token users will bid with.
     * @param _receiver Address that will receive the funds in the auction.
     * @param _governance Address allowed to enable and disable auctions.
     * @param _startingPrice Starting price for the auction (no decimals).
     *  NOTE: The starting price should be without decimals (1k == 1_000).
     * @return _newAuction Address of the newly created auction contract.
     */
    function createNewAuction(
        address _want,
        address _receiver,
        address _governance,
        uint256 _startingPrice
    ) external returns (address) {
        return
            _createNewAuction(
                _want,
                _receiver,
                _governance,
                _startingPrice,
                bytes32(0)
            );
    }

    /**
     * @notice Creates a new auction contract.
     * @param _want Address of the token users will bid with.
     * @param _receiver Address that will receive the funds in the auction.
     * @param _governance Address allowed to enable and disable auctions.
     * @param _startingPrice Starting price for the auction (no decimals).
     * @param _salt The salt to use for deterministic deployment.
     * @return _newAuction Address of the newly created auction contract.
     */
    function createNewAuction(
        address _want,
        address _receiver,
        address _governance,
        uint256 _startingPrice,
        bytes32 _salt
    ) external returns (address) {
        return
            _createNewAuction(
                _want,
                _receiver,
                _governance,
                _startingPrice,
                _salt
            );
    }

    /**
     * @dev Deploys and initializes a new Auction
     */
    function _createNewAuction(
        address _want,
        address _receiver,
        address _governance,
        uint256 _startingPrice,
        bytes32 _salt
    ) internal returns (address _newAuction) {
        if (_salt == bytes32(0)) {
            // If none set, generate unique salt. msg.sender gets encoded in getSalt()
            _salt = keccak256(abi.encodePacked(_want, _receiver, _governance));
        }

        _newAuction = _cloneCreate2(_salt);

        Auction(_newAuction).initialize(
            _want,
            _receiver,
            _governance,
            _startingPrice
        );

        auctions.push(_newAuction);

        emit DeployedNewAuction(_newAuction, _want);
    }

    /**
     * @notice Get the full list of auctions deployed through this factory.
     */
    function getAllAuctions() external view returns (address[] memory) {
        return auctions;
    }

    /**
     * @notice Get the total number of auctions deployed through this factory.
     */
    function numberOfAuctions() external view returns (uint256) {
        return auctions.length;
    }
}

File 30 of 43 : IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

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

// TokenizedStrategy interface used for internal view delegateCalls.
import {ITokenizedStrategy} from "./interfaces/ITokenizedStrategy.sol";

/**
 * @title YearnV3 Base Strategy
 * @author yearn.finance
 * @notice
 *  BaseStrategy implements all of the required functionality to
 *  seamlessly integrate with the `TokenizedStrategy` implementation contract
 *  allowing anyone to easily build a fully permissionless ERC-4626 compliant
 *  Vault by inheriting this contract and overriding three simple functions.

 *  It utilizes an immutable proxy pattern that allows the BaseStrategy
 *  to remain simple and small. All standard logic is held within the
 *  `TokenizedStrategy` and is reused over any n strategies all using the
 *  `fallback` function to delegatecall the implementation so that strategists
 *  can only be concerned with writing their strategy specific code.
 *
 *  This contract should be inherited and the three main abstract methods
 *  `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt
 *  the Strategy to the particular needs it has to generate yield. There are
 *  other optional methods that can be implemented to further customize
 *  the strategy if desired.
 *
 *  All default storage for the strategy is controlled and updated by the
 *  `TokenizedStrategy`. The implementation holds a storage struct that
 *  contains all needed global variables in a manual storage slot. This
 *  means strategists can feel free to implement their own custom storage
 *  variables as they need with no concern of collisions. All global variables
 *  can be viewed within the Strategy by a simple call using the
 *  `TokenizedStrategy` variable. IE: TokenizedStrategy.globalVariable();.
 */
abstract contract BaseStrategy {
    /*//////////////////////////////////////////////////////////////
                            MODIFIERS
    //////////////////////////////////////////////////////////////*/
    /**
     * @dev Used on TokenizedStrategy callback functions to make sure it is post
     * a delegateCall from this address to the TokenizedStrategy.
     */
    modifier onlySelf() {
        _onlySelf();
        _;
    }

    /**
     * @dev Use to assure that the call is coming from the strategies management.
     */
    modifier onlyManagement() {
        TokenizedStrategy.requireManagement(msg.sender);
        _;
    }

    /**
     * @dev Use to assure that the call is coming from either the strategies
     * management or the keeper.
     */
    modifier onlyKeepers() {
        TokenizedStrategy.requireKeeperOrManagement(msg.sender);
        _;
    }

    /**
     * @dev Use to assure that the call is coming from either the strategies
     * management or the emergency admin.
     */
    modifier onlyEmergencyAuthorized() {
        TokenizedStrategy.requireEmergencyAuthorized(msg.sender);
        _;
    }

    /**
     * @dev Require that the msg.sender is this address.
     */
    function _onlySelf() internal view {
        require(msg.sender == address(this), "!self");
    }

    /*//////////////////////////////////////////////////////////////
                            CONSTANTS
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev This is the address of the TokenizedStrategy implementation
     * contract that will be used by all strategies to handle the
     * accounting, logic, storage etc.
     *
     * Any external calls to the that don't hit one of the functions
     * defined in this base or the strategy will end up being forwarded
     * through the fallback function, which will delegateCall this address.
     *
     * This address should be the same for every strategy, never be adjusted
     * and always be checked before any integration with the Strategy.
     */
    address public constant tokenizedStrategyAddress =
        0xD377919FA87120584B21279a491F82D5265A139c;

    /*//////////////////////////////////////////////////////////////
                            IMMUTABLES
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev Underlying asset the Strategy is earning yield on.
     * Stored here for cheap retrievals within the strategy.
     */
    ERC20 internal immutable asset;

    /**
     * @dev This variable is set to address(this) during initialization of each strategy.
     *
     * This can be used to retrieve storage data within the strategy
     * contract as if it were a linked library.
     *
     *       i.e. uint256 totalAssets = TokenizedStrategy.totalAssets()
     *
     * Using address(this) will mean any calls using this variable will lead
     * to a call to itself. Which will hit the fallback function and
     * delegateCall that to the actual TokenizedStrategy.
     */
    ITokenizedStrategy internal immutable TokenizedStrategy;

    /**
     * @notice Used to initialize the strategy on deployment.
     *
     * This will set the `TokenizedStrategy` variable for easy
     * internal view calls to the implementation. As well as
     * initializing the default storage variables based on the
     * parameters and using the deployer for the permissioned roles.
     *
     * @param _asset Address of the underlying asset.
     * @param _name Name the strategy will use.
     */
    constructor(address _asset, string memory _name) {
        asset = ERC20(_asset);

        // Set instance of the implementation for internal use.
        TokenizedStrategy = ITokenizedStrategy(address(this));

        // Initialize the strategy's storage variables.
        _delegateCall(
            abi.encodeCall(
                ITokenizedStrategy.initialize,
                (_asset, _name, msg.sender, msg.sender, msg.sender)
            )
        );

        // Store the tokenizedStrategyAddress at the standard implementation
        // address storage slot so etherscan picks up the interface. This gets
        // stored on initialization and never updated.
        assembly {
            sstore(
                // keccak256('eip1967.proxy.implementation' - 1)
                0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
                tokenizedStrategyAddress
            )
        }
    }

    /*//////////////////////////////////////////////////////////////
                NEEDED TO BE OVERRIDDEN BY STRATEGIST
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev Can deploy up to '_amount' of 'asset' in the yield source.
     *
     * This function is called at the end of a {deposit} or {mint}
     * call. Meaning that unless a whitelist is implemented it will
     * be entirely permissionless and thus can be sandwiched or otherwise
     * manipulated.
     *
     * @param _amount The amount of 'asset' that the strategy can attempt
     * to deposit in the yield source.
     */
    function _deployFunds(uint256 _amount) internal virtual;

    /**
     * @dev Should attempt to free the '_amount' of 'asset'.
     *
     * NOTE: The amount of 'asset' that is already loose has already
     * been accounted for.
     *
     * This function is called during {withdraw} and {redeem} calls.
     * Meaning that unless a whitelist is implemented it will be
     * entirely permissionless and thus can be sandwiched or otherwise
     * manipulated.
     *
     * Should not rely on asset.balanceOf(address(this)) calls other than
     * for diff accounting purposes.
     *
     * Any difference between `_amount` and what is actually freed will be
     * counted as a loss and passed on to the withdrawer. This means
     * care should be taken in times of illiquidity. It may be better to revert
     * if withdraws are simply illiquid so not to realize incorrect losses.
     *
     * @param _amount, The amount of 'asset' to be freed.
     */
    function _freeFunds(uint256 _amount) internal virtual;

    /**
     * @dev Internal function to harvest all rewards, redeploy any idle
     * funds and return an accurate accounting of all funds currently
     * held by the Strategy.
     *
     * This should do any needed harvesting, rewards selling, accrual,
     * redepositing etc. to get the most accurate view of current assets.
     *
     * NOTE: All applicable assets including loose assets should be
     * accounted for in this function.
     *
     * Care should be taken when relying on oracles or swap values rather
     * than actual amounts as all Strategy profit/loss accounting will
     * be done based on this returned value.
     *
     * This can still be called post a shutdown, a strategist can check
     * `TokenizedStrategy.isShutdown()` to decide if funds should be
     * redeployed or simply realize any profits/losses.
     *
     * @return _totalAssets A trusted and accurate account for the total
     * amount of 'asset' the strategy currently holds including idle funds.
     */
    function _harvestAndReport()
        internal
        virtual
        returns (uint256 _totalAssets);

    /*//////////////////////////////////////////////////////////////
                    OPTIONAL TO OVERRIDE BY STRATEGIST
    //////////////////////////////////////////////////////////////*/

    /**
     * @dev Optional function for strategist to override that can
     *  be called in between reports.
     *
     * If '_tend' is used tendTrigger() will also need to be overridden.
     *
     * This call can only be called by a permissioned role so may be
     * through protected relays.
     *
     * This can be used to harvest and compound rewards, deposit idle funds,
     * perform needed position maintenance or anything else that doesn't need
     * a full report for.
     *
     *   EX: A strategy that can not deposit funds without getting
     *       sandwiched can use the tend when a certain threshold
     *       of idle to totalAssets has been reached.
     *
     * This will have no effect on PPS of the strategy till report() is called.
     *
     * @param _totalIdle The current amount of idle funds that are available to deploy.
     */
    function _tend(uint256 _totalIdle) internal virtual {}

    /**
     * @dev Optional trigger to override if tend() will be used by the strategy.
     * This must be implemented if the strategy hopes to invoke _tend().
     *
     * @return . Should return true if tend() should be called by keeper or false if not.
     */
    function _tendTrigger() internal view virtual returns (bool) {
        return false;
    }

    /**
     * @notice Returns if tend() should be called by a keeper.
     *
     * @return . Should return true if tend() should be called by keeper or false if not.
     * @return . Calldata for the tend call.
     */
    function tendTrigger() external view virtual returns (bool, bytes memory) {
        return (
            // Return the status of the tend trigger.
            _tendTrigger(),
            // And the needed calldata either way.
            abi.encodeWithSelector(ITokenizedStrategy.tend.selector)
        );
    }

    /**
     * @notice Gets the max amount of `asset` that an address can deposit.
     * @dev Defaults to an unlimited amount for any address. But can
     * be overridden by strategists.
     *
     * This function will be called before any deposit or mints to enforce
     * any limits desired by the strategist. This can be used for either a
     * traditional deposit limit or for implementing a whitelist etc.
     *
     *   EX:
     *      if(isAllowed[_owner]) return super.availableDepositLimit(_owner);
     *
     * This does not need to take into account any conversion rates
     * from shares to assets. But should know that any non max uint256
     * amounts may be converted to shares. So it is recommended to keep
     * custom amounts low enough as not to cause overflow when multiplied
     * by `totalSupply`.
     *
     * @param . The address that is depositing into the strategy.
     * @return . The available amount the `_owner` can deposit in terms of `asset`
     */
    function availableDepositLimit(
        address /*_owner*/
    ) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /**
     * @notice Gets the max amount of `asset` that can be withdrawn.
     * @dev Defaults to an unlimited amount for any address. But can
     * be overridden by strategists.
     *
     * This function will be called before any withdraw or redeem to enforce
     * any limits desired by the strategist. This can be used for illiquid
     * or sandwichable strategies. It should never be lower than `totalIdle`.
     *
     *   EX:
     *       return TokenIzedStrategy.totalIdle();
     *
     * This does not need to take into account the `_owner`'s share balance
     * or conversion rates from shares to assets.
     *
     * @param . The address that is withdrawing from the strategy.
     * @return . The available amount that can be withdrawn in terms of `asset`
     */
    function availableWithdrawLimit(
        address /*_owner*/
    ) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /**
     * @dev Optional function for a strategist to override that will
     * allow management to manually withdraw deployed funds from the
     * yield source if a strategy is shutdown.
     *
     * This should attempt to free `_amount`, noting that `_amount` may
     * be more than is currently deployed.
     *
     * NOTE: This will not realize any profits or losses. A separate
     * {report} will be needed in order to record any profit/loss. If
     * a report may need to be called after a shutdown it is important
     * to check if the strategy is shutdown during {_harvestAndReport}
     * so that it does not simply re-deploy all funds that had been freed.
     *
     * EX:
     *   if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) {
     *       depositFunds...
     *    }
     *
     * @param _amount The amount of asset to attempt to free.
     */
    function _emergencyWithdraw(uint256 _amount) internal virtual {}

    /*//////////////////////////////////////////////////////////////
                        TokenizedStrategy HOOKS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Can deploy up to '_amount' of 'asset' in yield source.
     * @dev Callback for the TokenizedStrategy to call during a {deposit}
     * or {mint} to tell the strategy it can deploy funds.
     *
     * Since this can only be called after a {deposit} or {mint}
     * delegateCall to the TokenizedStrategy msg.sender == address(this).
     *
     * Unless a whitelist is implemented this will be entirely permissionless
     * and thus can be sandwiched or otherwise manipulated.
     *
     * @param _amount The amount of 'asset' that the strategy can
     * attempt to deposit in the yield source.
     */
    function deployFunds(uint256 _amount) external virtual onlySelf {
        _deployFunds(_amount);
    }

    /**
     * @notice Should attempt to free the '_amount' of 'asset'.
     * @dev Callback for the TokenizedStrategy to call during a withdraw
     * or redeem to free the needed funds to service the withdraw.
     *
     * This can only be called after a 'withdraw' or 'redeem' delegateCall
     * to the TokenizedStrategy so msg.sender == address(this).
     *
     * @param _amount The amount of 'asset' that the strategy should attempt to free up.
     */
    function freeFunds(uint256 _amount) external virtual onlySelf {
        _freeFunds(_amount);
    }

    /**
     * @notice Returns the accurate amount of all funds currently
     * held by the Strategy.
     * @dev Callback for the TokenizedStrategy to call during a report to
     * get an accurate accounting of assets the strategy controls.
     *
     * This can only be called after a report() delegateCall to the
     * TokenizedStrategy so msg.sender == address(this).
     *
     * @return . A trusted and accurate account for the total amount
     * of 'asset' the strategy currently holds including idle funds.
     */
    function harvestAndReport() external virtual onlySelf returns (uint256) {
        return _harvestAndReport();
    }

    /**
     * @notice Will call the internal '_tend' when a keeper tends the strategy.
     * @dev Callback for the TokenizedStrategy to initiate a _tend call in the strategy.
     *
     * This can only be called after a tend() delegateCall to the TokenizedStrategy
     * so msg.sender == address(this).
     *
     * We name the function `tendThis` so that `tend` calls are forwarded to
     * the TokenizedStrategy.

     * @param _totalIdle The amount of current idle funds that can be
     * deployed during the tend
     */
    function tendThis(uint256 _totalIdle) external virtual onlySelf {
        _tend(_totalIdle);
    }

    /**
     * @notice Will call the internal '_emergencyWithdraw' function.
     * @dev Callback for the TokenizedStrategy during an emergency withdraw.
     *
     * This can only be called after a emergencyWithdraw() delegateCall to
     * the TokenizedStrategy so msg.sender == address(this).
     *
     * We name the function `shutdownWithdraw` so that `emergencyWithdraw`
     * calls are forwarded to the TokenizedStrategy.
     *
     * @param _amount The amount of asset to attempt to free.
     */
    function shutdownWithdraw(uint256 _amount) external virtual onlySelf {
        _emergencyWithdraw(_amount);
    }

    /**
     * @dev Function used to delegate call the TokenizedStrategy with
     * certain `_calldata` and return any return values.
     *
     * This is used to setup the initial storage of the strategy, and
     * can be used by strategist to forward any other call to the
     * TokenizedStrategy implementation.
     *
     * @param _calldata The abi encoded calldata to use in delegatecall.
     * @return . The return value if the call was successful in bytes.
     */
    function _delegateCall(
        bytes memory _calldata
    ) internal returns (bytes memory) {
        // Delegate call the tokenized strategy with provided calldata.
        (bool success, bytes memory result) = tokenizedStrategyAddress
            .delegatecall(_calldata);

        // If the call reverted. Return the error.
        if (!success) {
            assembly {
                let ptr := mload(0x40)
                let size := returndatasize()
                returndatacopy(ptr, 0, size)
                revert(ptr, size)
            }
        }

        // Return the result.
        return result;
    }

    /**
     * @dev Execute a function on the TokenizedStrategy and return any value.
     *
     * This fallback function will be executed when any of the standard functions
     * defined in the TokenizedStrategy are called since they wont be defined in
     * this contract.
     *
     * It will delegatecall the TokenizedStrategy implementation with the exact
     * calldata and return any relevant values.
     *
     */
    fallback() external {
        // load our target address
        address _tokenizedStrategyAddress = tokenizedStrategyAddress;
        // Execute external function using delegatecall and return any value.
        assembly {
            // Copy function selector and any arguments.
            calldatacopy(0, 0, calldatasize())
            // Execute function delegatecall.
            let result := delegatecall(
                gas(),
                _tokenizedStrategyAddress,
                0,
                calldatasize(),
                0,
                0
            )
            // Get any return value
            returndatacopy(0, 0, returndatasize())
            // Return any return value or error back to the caller
            switch result
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }
}

File 32 of 43 : ErrorsLib.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

library ErrorsLib {
    string internal constant NOT_OWNER = "not owner";
    string internal constant MAX_LLTV_EXCEEDED = "max LLTV exceeded";
    string internal constant MAX_FEE_EXCEEDED = "max fee exceeded";
    string internal constant ALREADY_SET = "already set";
    string internal constant IRM_NOT_ENABLED = "IRM not enabled";
    string internal constant LLTV_NOT_ENABLED = "LLTV not enabled";
    string internal constant MARKET_ALREADY_CREATED = "market already created";
    string internal constant NO_CODE = "no code";
    string internal constant MARKET_NOT_CREATED = "market not created";
    string internal constant INCONSISTENT_INPUT = "inconsistent input";
    string internal constant ZERO_ASSETS = "zero assets";
    string internal constant ZERO_ADDRESS = "zero address";
    string internal constant UNAUTHORIZED = "unauthorized";
    string internal constant INSUFFICIENT_COLLATERAL =
        "insufficient collateral";
    string internal constant INSUFFICIENT_LIQUIDITY = "insufficient liquidity";
    string internal constant HEALTHY_POSITION = "position is healthy";
    string internal constant INVALID_SIGNATURE = "invalid signature";
    string internal constant SIGNATURE_EXPIRED = "signature expired";
    string internal constant INVALID_NONCE = "invalid nonce";
    string internal constant TRANSFER_REVERTED = "transfer reverted";
    string internal constant TRANSFER_RETURNED_FALSE =
        "transfer returned false";
    string internal constant TRANSFER_FROM_REVERTED = "transferFrom reverted";
    string internal constant TRANSFER_FROM_RETURNED_FALSE =
        "transferFrom returned false";
    string internal constant MAX_UINT128_EXCEEDED = "max uint128 exceeded";
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

import {Maths} from "../libraries/Maths.sol";
import {ITaker} from "../interfaces/ITaker.sol";
import {GPv2Order} from "../libraries/GPv2Order.sol";
import {Governance2Step} from "../utils/Governance2Step.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";

interface ICowSettlement {
    function domainSeparator() external view returns (bytes32);
}

/**
 *   @title Auction
 *   @author yearn.fi
 *   @notice General use dutch auction contract for token sales.
 */
contract Auction is Governance2Step, ReentrancyGuard {
    using GPv2Order for GPv2Order.Data;
    using SafeERC20 for ERC20;

    /// @notice Emitted when a new auction is enabled
    event AuctionEnabled(address indexed from, address indexed to);

    /// @notice Emitted when an auction is disabled.
    event AuctionDisabled(address indexed from, address indexed to);

    /// @notice Emitted when auction has been kicked.
    event AuctionKicked(address indexed from, uint256 available);

    /// @notice Emitted when the starting price is updated.
    event UpdatedStartingPrice(uint256 startingPrice);

    /// @notice Emitted when the step decay rate is updated.
    event UpdatedStepDecayRate(uint256 indexed stepDecayRate);

    /// @notice Emitted when the step duration is updated.
    event UpdatedStepDuration(uint256 indexed stepDuration);

    /// @notice Emitted when the auction is settled.
    event AuctionSettled(address indexed from);

    /// @notice Emitted when the auction is swept.
    event AuctionSwept(address indexed token, address indexed to);

    /// @dev Store address and scaler in one slot.
    struct TokenInfo {
        address tokenAddress;
        uint96 scaler;
    }

    /// @notice Store all the auction specific information.
    struct AuctionInfo {
        uint64 kicked;
        uint64 scaler;
        uint128 initialAvailable;
    }

    uint256 internal constant WAD = 1e18;

    address internal constant COW_SETTLEMENT =
        0x9008D19f58AAbD9eD0D60971565AA8510560ab41;

    address internal constant VAULT_RELAYER =
        0xC92E8bdf79f0507f65a392b0ab4667716BFE0110;

    /// @notice The time that each auction lasts.
    uint256 internal constant AUCTION_LENGTH = 1 days;

    /// @notice Struct to hold the info for `want`.
    TokenInfo internal wantInfo;

    /// @notice The address that will receive the funds in the auction.
    address public receiver;

    /// @notice The amount to start the auction at.
    /// @dev This is an unscaled "lot size" essentially to start the pricing in "want".
    ///   The kicked amount of _from is divided by this to get the per auction initial price.
    uint256 public startingPrice;

    /// @notice The time period for each price step in seconds.
    uint256 public stepDuration;

    /// @notice The decay rate per step in basis points (e.g., 50 for 0.5% decrease per step).
    uint256 public stepDecayRate;

    /// @notice Mapping from `from` token to its struct.
    mapping(address => AuctionInfo) public auctions;

    /// @notice Array of all the enabled auction for this contract.
    address[] public enabledAuctions;

    constructor() Governance2Step(msg.sender) {}

    /**
     * @notice Initializes the Auction contract with initial parameters.
     * @param _want Address this auction is selling to.
     * @param _receiver Address that will receive the funds from the auction.
     * @param _governance Address of the contract governance.
     * @param _startingPrice Starting price for each auction.
     */
    function initialize(
        address _want,
        address _receiver,
        address _governance,
        uint256 _startingPrice
    ) public virtual {
        require(stepDecayRate == 0, "initialized");
        require(_want != address(0), "ZERO ADDRESS");
        require(_startingPrice != 0, "starting price");
        require(_receiver != address(0), "receiver");
        // Cannot have more than 18 decimals.
        uint256 decimals = ERC20(_want).decimals();
        require(decimals <= 18, "unsupported decimals");

        // Set variables
        wantInfo = TokenInfo({
            tokenAddress: _want,
            scaler: uint96(WAD / 10 ** decimals)
        });

        receiver = _receiver;
        governance = _governance;
        emit GovernanceTransferred(address(0), _governance);
        startingPrice = _startingPrice;
        emit UpdatedStartingPrice(_startingPrice);

        // Default to 50bps every 60 seconds
        stepDuration = 60;
        emit UpdatedStepDuration(stepDuration);
        stepDecayRate = 50; // 50 basis points = 0.5% decay per step
        emit UpdatedStepDecayRate(stepDecayRate);
    }

    /*//////////////////////////////////////////////////////////////
                         VIEW METHODS
    //////////////////////////////////////////////////////////////*/

    function version() external pure returns (string memory) {
        return "1.0.3";
    }

    /**
     * @notice Get the address of this auctions want token.
     * @return . The want token.
     */
    function want() public view virtual returns (address) {
        return wantInfo.tokenAddress;
    }

    function auctionLength() public view virtual returns (uint256) {
        return AUCTION_LENGTH;
    }

    /**
     * @notice Get the available amount for the auction.
     * @param _from The address of the token to be auctioned.
     * @return . The available amount for the auction.
     */
    function available(address _from) public view virtual returns (uint256) {
        if (!isActive(_from)) return 0;

        return
            Maths.min(
                auctions[_from].initialAvailable,
                ERC20(_from).balanceOf(address(this))
            );
    }

    /**
     * @notice Get the kicked timestamp for the auction.
     * @param _from The address of the token to be auctioned.
     * @return . The kicked timestamp for the auction.
     */
    function kicked(address _from) external view virtual returns (uint256) {
        return auctions[_from].kicked;
    }

    /**
     * @notice Check if the auction is active.
     * @param _from The address of the token to be auctioned.
     * @return . Whether the auction is active.
     */
    function isActive(address _from) public view virtual returns (bool) {
        return auctions[_from].kicked + AUCTION_LENGTH >= block.timestamp;
    }

    /**
     * @notice Get all the enabled auctions.
     */
    function getAllEnabledAuctions()
        external
        view
        virtual
        returns (address[] memory)
    {
        return enabledAuctions;
    }

    /**
     * @notice Get the pending amount available for the next auction.
     * @dev Defaults to the auctions balance of the from token if no hook.
     * @param _from The address of the token to be auctioned.
     * @return uint256 The amount that can be kicked into the auction.
     */
    function kickable(address _from) external view virtual returns (uint256) {
        // If not enough time has passed then `kickable` is 0.
        if (isActive(_from)) return 0;

        // Use the full balance of this contract.
        return ERC20(_from).balanceOf(address(this));
    }

    /**
     * @notice Gets the amount of `want` needed to buy the available amount of `from`.
     * @param _from The address of the token to be auctioned.
     * @return . The amount of `want` needed to fulfill the take amount.
     */
    function getAmountNeeded(
        address _from
    ) external view virtual returns (uint256) {
        return
            _getAmountNeeded(
                auctions[_from],
                available(_from),
                block.timestamp
            );
    }

    /**
     * @notice Gets the amount of `want` needed to buy a specific amount of `from`.
     * @param _from The address of the token to be auctioned.
     * @param _amountToTake The amount of `from` to take in the auction.
     * @return . The amount of `want` needed to fulfill the take amount.
     */
    function getAmountNeeded(
        address _from,
        uint256 _amountToTake
    ) external view virtual returns (uint256) {
        return
            _getAmountNeeded(auctions[_from], _amountToTake, block.timestamp);
    }

    /**
     * @notice Gets the amount of `want` needed to buy a specific amount of `from` at a specific timestamp.
     * @param _from The address of the token to be auctioned.
     * @param _amountToTake The amount `from` to take in the auction.
     * @param _timestamp The specific timestamp for calculating the amount needed.
     * @return . The amount of `want` needed to fulfill the take amount.
     */
    function getAmountNeeded(
        address _from,
        uint256 _amountToTake,
        uint256 _timestamp
    ) external view virtual returns (uint256) {
        return _getAmountNeeded(auctions[_from], _amountToTake, _timestamp);
    }

    /**
     * @dev Return the amount of `want` needed to buy `_amountToTake`.
     */
    function _getAmountNeeded(
        AuctionInfo memory _auction,
        uint256 _amountToTake,
        uint256 _timestamp
    ) internal view virtual returns (uint256) {
        return
            // Scale _amountToTake to 1e18
            (_amountToTake *
                _auction.scaler *
                // Price is always 1e18
                _price(
                    _auction.kicked,
                    _auction.initialAvailable * _auction.scaler,
                    _timestamp
                )) /
            1e18 /
            // Scale back down to want.
            wantInfo.scaler;
    }

    /**
     * @notice Gets the price of the auction at the current timestamp.
     * @param _from The address of the token to be auctioned.
     * @return . The price of the auction.
     */
    function price(address _from) external view virtual returns (uint256) {
        return price(_from, block.timestamp);
    }

    /**
     * @notice Gets the price of the auction at a specific timestamp.
     * @param _from The address of the token to be auctioned.
     * @param _timestamp The specific timestamp for calculating the price.
     * @return . The price of the auction.
     */
    function price(
        address _from,
        uint256 _timestamp
    ) public view virtual returns (uint256) {
        // Get unscaled price and scale it down.
        return
            _price(
                auctions[_from].kicked,
                auctions[_from].initialAvailable * auctions[_from].scaler,
                _timestamp
            ) / wantInfo.scaler;
    }

    /**
     * @dev Internal function to calculate the scaled price based on auction parameters.
     * @param _kicked The timestamp the auction was kicked.
     * @param _available The initial available amount scaled 1e18.
     * @param _timestamp The specific timestamp for calculating the price.
     * @return . The calculated price scaled to 1e18.
     */
    function _price(
        uint256 _kicked,
        uint256 _available,
        uint256 _timestamp
    ) internal view virtual returns (uint256) {
        if (_available == 0) return 0;

        uint256 secondsElapsed = _timestamp - _kicked;

        if (secondsElapsed > AUCTION_LENGTH) return 0;

        // Calculate the number of price steps that have passed
        uint256 steps = secondsElapsed / stepDuration;

        // Convert basis points to ray multiplier (e.g., 50 bps = 0.995 * 1e27)
        // rayMultiplier = 1e27 - (basisPoints * 1e23)
        uint256 rayMultiplier = 1e27 - (stepDecayRate * 1e23);

        // Calculate the decay multiplier using the configurable decay rate per step
        uint256 decayMultiplier = Maths.rpow(rayMultiplier, steps);

        // Calculate initial price per token
        uint256 initialPrice = Maths.wdiv(startingPrice * 1e18, _available);

        // Apply the decay to get the current price
        return Maths.rmul(initialPrice, decayMultiplier);
    }

    /*//////////////////////////////////////////////////////////////
                            SETTERS
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Enables a new auction.
     * @param _from The address of the token to be auctioned.
     */
    function enable(address _from) external virtual onlyGovernance {
        address _want = want();
        require(_from != address(0) && _from != _want, "ZERO ADDRESS");
        require(auctions[_from].scaler == 0, "already enabled");

        // Cannot have more than 18 decimals.
        uint256 decimals = ERC20(_from).decimals();
        require(decimals <= 18, "unsupported decimals");

        // Store all needed info.
        auctions[_from].scaler = uint64(WAD / 10 ** decimals);

        ERC20(_from).forceApprove(VAULT_RELAYER, type(uint256).max);

        // Add to the array.
        enabledAuctions.push(_from);

        emit AuctionEnabled(_from, _want);
    }

    /**
     * @notice Disables an existing auction.
     * @dev Only callable by governance.
     * @param _from The address of the token being sold.
     */
    function disable(address _from) external virtual {
        disable(_from, 0);
    }

    /**
     * @notice Disables an existing auction.
     * @dev Only callable by governance.
     * @param _from The address of the token being sold.
     * @param _index The index the auctionId is at in the array.
     */
    function disable(
        address _from,
        uint256 _index
    ) public virtual onlyGovernance {
        // Make sure the auction was enabled.
        require(auctions[_from].scaler != 0, "not enabled");

        // Remove the struct.
        delete auctions[_from];

        ERC20(_from).forceApprove(VAULT_RELAYER, 0);

        // Remove the auction ID from the array.
        address[] memory _enabledAuctions = enabledAuctions;
        if (_enabledAuctions[_index] != _from) {
            // If the _index given is not the id find it.
            for (uint256 i = 0; i < _enabledAuctions.length; ++i) {
                if (_enabledAuctions[i] == _from) {
                    _index = i;
                    break;
                }
            }
        }

        // Move the id to the last spot if not there.
        if (_index < _enabledAuctions.length - 1) {
            _enabledAuctions[_index] = _enabledAuctions[
                _enabledAuctions.length - 1
            ];
            // Update the array.
            enabledAuctions = _enabledAuctions;
        }

        // Pop the id off the array.
        enabledAuctions.pop();

        emit AuctionDisabled(_from, want());
    }

    function isAnActiveAuction() public view returns (bool) {
        address[] memory _enabledAuctions = enabledAuctions;
        for (uint256 i = 0; i < _enabledAuctions.length; ++i) {
            if (isActive(_enabledAuctions[i])) {
                return true;
            }
        }
        return false;
    }

    /**
     * @notice Sets the starting price for the auction.
     * @dev This is an unscaled "lot size" essentially to start the pricing in "want".
     *   The kicked amount of _from is divided by this to get the per auction initial price.
     * @param _startingPrice The new starting price for the auction.
     */
    function setStartingPrice(
        uint256 _startingPrice
    ) external virtual onlyGovernance {
        require(_startingPrice != 0, "starting price");

        // Don't change the price when an auction is active.
        require(!isAnActiveAuction(), "active auction");

        startingPrice = _startingPrice;

        emit UpdatedStartingPrice(_startingPrice);
    }

    /**
     * @notice Sets the step decay rate for the auction.
     * @dev The decay rate is in basis points (e.g., 50 for 0.5% decay per step).
     * @param _stepDecayRate The new decay rate per step in basis points (max 10000 = 100%).
     */
    function setStepDecayRate(
        uint256 _stepDecayRate
    ) external virtual onlyGovernance {
        require(
            _stepDecayRate > 0 && _stepDecayRate < 10_000,
            "invalid decay rate"
        );

        // Don't change the decay rate when an auction is active.
        require(!isAnActiveAuction(), "active auction");

        stepDecayRate = _stepDecayRate;

        emit UpdatedStepDecayRate(_stepDecayRate);
    }

    /**
     * @notice Sets the step duration for the auction.
     * @param _stepDuration The new step duration in seconds.
     */
    function setStepDuration(
        uint256 _stepDuration
    ) external virtual onlyGovernance {
        require(
            _stepDuration != 0 && _stepDuration < AUCTION_LENGTH,
            "invalid step duration"
        );

        require(!isAnActiveAuction(), "active auction");

        stepDuration = _stepDuration;

        emit UpdatedStepDuration(_stepDuration);
    }

    /*//////////////////////////////////////////////////////////////
                      PARTICIPATE IN AUCTION
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Kicks off an auction, updating its status and making funds available for bidding.
     * @param _from The address of the token to be auctioned.
     * @return _available The available amount for bidding on in the auction.
     */
    function kick(
        address _from
    ) external virtual nonReentrant returns (uint256 _available) {
        return _kick(_from);
    }

    function _kick(
        address _from
    ) internal virtual returns (uint256 _available) {
        require(auctions[_from].scaler != 0, "not enabled");
        require(
            block.timestamp > auctions[_from].kicked + AUCTION_LENGTH,
            "too soon"
        );

        // Just use current balance.
        _available = ERC20(_from).balanceOf(address(this));

        require(_available != 0, "nothing to kick");

        // Update the auctions status.
        auctions[_from].kicked = uint64(block.timestamp);
        auctions[_from].initialAvailable = uint128(_available);

        emit AuctionKicked(_from, _available);
    }

    /**
     * @notice Take the token being sold in a live auction.
     * @dev Defaults to taking the full amount and sending to the msg sender.
     * @param _from The address of the token to be auctioned.
     * @return . The amount of fromToken taken in the auction.
     */
    function take(address _from) external virtual returns (uint256) {
        return _take(_from, type(uint256).max, msg.sender, new bytes(0));
    }

    /**
     * @notice Take the token being sold in a live auction with a specified maximum amount.
     * @dev Will send the funds to the msg sender.
     * @param _from The address of the token to be auctioned.
     * @param _maxAmount The maximum amount of fromToken to take in the auction.
     * @return . The amount of fromToken taken in the auction.
     */
    function take(
        address _from,
        uint256 _maxAmount
    ) external virtual returns (uint256) {
        return _take(_from, _maxAmount, msg.sender, new bytes(0));
    }

    /**
     * @notice Take the token being sold in a live auction.
     * @param _from The address of the token to be auctioned.
     * @param _maxAmount The maximum amount of fromToken to take in the auction.
     * @param _takerReceiver The address that will receive the fromToken.
     * @return _amountTaken The amount of fromToken taken in the auction.
     */
    function take(
        address _from,
        uint256 _maxAmount,
        address _takerReceiver
    ) external virtual returns (uint256) {
        return _take(_from, _maxAmount, _takerReceiver, new bytes(0));
    }

    /**
     * @notice Take the token being sold in a live auction.
     * @param _from The address of the token to be auctioned.
     * @param _maxAmount The maximum amount of fromToken to take in the auction.
     * @param _takerReceiver The address that will receive the fromToken.
     * @param _data The data signify the callback should be used and sent with it.
     * @return _amountTaken The amount of fromToken taken in the auction.
     */
    function take(
        address _from,
        uint256 _maxAmount,
        address _takerReceiver,
        bytes calldata _data
    ) external virtual returns (uint256) {
        return _take(_from, _maxAmount, _takerReceiver, _data);
    }

    /// @dev Implements the take of the auction.
    function _take(
        address _from,
        uint256 _maxAmount,
        address _takerReceiver,
        bytes memory _data
    ) internal virtual nonReentrant returns (uint256 _amountTaken) {
        AuctionInfo memory auction = auctions[_from];
        // Make sure the auction is active.
        require(
            auction.kicked + AUCTION_LENGTH >= block.timestamp,
            "not kicked"
        );

        // Max amount that can be taken.
        uint256 _available = available(_from);
        _amountTaken = _available > _maxAmount ? _maxAmount : _available;

        // Get the amount needed
        uint256 needed = _getAmountNeeded(
            auction,
            _amountTaken,
            block.timestamp
        );

        require(needed != 0, "zero needed");

        // Send `from`.
        ERC20(_from).safeTransfer(_takerReceiver, _amountTaken);

        // If the caller has specified data.
        if (_data.length != 0) {
            // Do the callback.
            ITaker(_takerReceiver).auctionTakeCallback(
                _from,
                msg.sender,
                _amountTaken,
                needed,
                _data
            );
        }

        // Cache the want address.
        address _want = want();

        // Pull `want`.
        ERC20(_want).safeTransferFrom(msg.sender, receiver, needed);

        // If the full amount is taken, end the auction.
        if (_amountTaken == _available) {
            auctions[_from].kicked = uint64(0);

            emit AuctionSettled(_from);
        }
    }

    /// @dev Validates a COW order signature.
    function isValidSignature(
        bytes32 _hash,
        bytes calldata signature
    ) external view returns (bytes4) {
        // Make sure `_take` has not already been entered.
        require(!_reentrancyGuardEntered(), "ReentrancyGuard: reentrant call");

        // Decode the signature to get the order.
        GPv2Order.Data memory order = abi.decode(signature, (GPv2Order.Data));

        AuctionInfo memory auction = auctions[address(order.sellToken)];

        // Get the current amount needed for the auction.
        uint256 paymentAmount = _getAmountNeeded(
            auction,
            order.sellAmount,
            block.timestamp
        );

        // Verify the order details.
        // Retreive domain seperator each time for chains it is not deployed on yet
        require(
            _hash ==
                order.hash(ICowSettlement(COW_SETTLEMENT).domainSeparator()),
            "bad order"
        );
        require(paymentAmount != 0, "zero amount");
        require(available(address(order.sellToken)) != 0, "zero available");
        require(order.feeAmount == 0, "fee");
        require(order.partiallyFillable, "partial fill");
        require(order.validTo < auction.kicked + AUCTION_LENGTH, "expired");
        require(order.appData == bytes32(0), "app data");
        require(order.buyAmount >= paymentAmount, "bad price");
        require(address(order.buyToken) == want(), "bad token");
        require(order.receiver == receiver, "bad receiver");
        require(order.sellAmount <= auction.initialAvailable, "bad amount");

        // If all checks pass, return the magic value
        return this.isValidSignature.selector;
    }

    /**
     * @notice Forces the auction to be kicked.
     * @dev Only callable by governance in replace of sweep settle and kick.
     * @param _from The address of the token to be auctioned.
     */
    function forceKick(address _from) external onlyGovernance {
        auctions[_from].kicked = uint64(0);
        _kick(_from);
    }

    /**
     * @notice Allows the auction to be stopped if the full amount is taken.
     * @param _from The address of the token to be auctioned.
     */
    function settle(address _from) external virtual {
        require(isActive(_from), "!active");
        require(ERC20(_from).balanceOf(address(this)) == 0, "!empty");

        auctions[_from].kicked = uint64(0);

        emit AuctionSettled(_from);
    }

    function sweep(address _token) external virtual onlyGovernance {
        ERC20(_token).safeTransfer(
            msg.sender,
            ERC20(_token).balanceOf(address(this))
        );

        emit AuctionSwept(_token, msg.sender);
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

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

contract ClonableCreate2 is Clonable {
    /**
     * @notice Clone the contracts default `original` contract using CREATE2.
     * @param salt The salt to use for deterministic deployment.
     * @return Address of the new Minimal Proxy clone.
     */
    function _cloneCreate2(bytes32 salt) internal virtual returns (address) {
        return _cloneCreate2(original, salt);
    }

    /**
     * @notice Clone any `_original` contract using CREATE2.
     * @param _original The address of the contract to clone.
     * @param salt The salt to use for deterministic deployment.
     * @return _newContract Address of the new Minimal Proxy clone.
     */
    function _cloneCreate2(
        address _original,
        bytes32 salt
    ) internal virtual returns (address _newContract) {
        // Hash the salt with msg.sender to protect deployments for specific callers
        bytes32 finalSalt = getSalt(salt, msg.sender);
        address predicted = computeCreate2Address(_original, salt, msg.sender);

        bytes20 addressBytes = bytes20(_original);
        assembly {
            // EIP-1167 bytecode
            let clone_code := mload(0x40)
            mstore(
                clone_code,
                0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
            )
            mstore(add(clone_code, 0x14), addressBytes)
            mstore(
                add(clone_code, 0x28),
                0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
            )
            _newContract := create2(0, clone_code, 0x37, finalSalt)
        }

        require(
            _newContract != address(0) && _newContract == predicted,
            "ClonableCreate2: create2 failed"
        );
    }

    /**
     * @notice Compute the address where a clone would be deployed using CREATE2.
     * @param salt The salt to use for address computation.
     * @return The address where the clone would be deployed.
     */
    function computeCreate2Address(
        bytes32 salt
    ) external view virtual returns (address) {
        return computeCreate2Address(original, salt, msg.sender);
    }

    /**
     * @notice Compute the address where a clone would be deployed using CREATE2.
     * @param _original The address of the contract to clone.
     * @param salt The salt to use for address computation.
     * @return predicted address where the clone would be deployed.
     */
    function computeCreate2Address(
        address _original,
        bytes32 salt
    ) external view virtual returns (address predicted) {
        return computeCreate2Address(_original, salt, msg.sender);
    }

    /**
     * @notice Compute the address where a clone would be deployed using CREATE2.
     * @param _original The address of the contract to clone.
     * @param salt The salt to use for address computation.
     * @return predicted The address where the clone would be deployed.
     */
    function computeCreate2Address(
        address _original,
        bytes32 salt,
        address deployer
    ) public view virtual returns (address predicted) {
        // Hash the salt with msg.sender to match deployment behavior
        bytes32 finalSalt = getSalt(salt, deployer);

        bytes20 addressBytes = bytes20(_original);
        assembly {
            let ptr := mload(0x40)

            // Store the prefix
            mstore(
                ptr,
                0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
            )
            // Store the address
            mstore(add(ptr, 0x14), addressBytes)
            // Store the suffix
            mstore(
                add(ptr, 0x28),
                0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
            )

            // Compute init code hash
            let initCodeHash := keccak256(ptr, 0x37)

            // Compute the CREATE2 address
            // 0xff ++ address(this) ++ salt ++ initCodeHash
            mstore(ptr, 0xff)
            mstore8(ptr, 0xff)
            mstore(add(ptr, 0x01), shl(96, address()))
            mstore(add(ptr, 0x15), finalSalt)
            mstore(add(ptr, 0x35), initCodeHash)

            predicted := keccak256(ptr, 0x55)
        }
    }

    /**
     * @dev Internal function to compute the final salt by hashing with msg.sender.
     * This ensures that different callers get different deployment addresses
     * even when using the same salt value.
     * @param salt The user-provided salt.
     * @return The final salt to use for CREATE2.
     */
    function getSalt(
        bytes32 salt,
        address deployer
    ) public view virtual returns (bytes32) {
        return keccak256(abi.encodePacked(salt, deployer));
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";

// Interface that implements the 4626 standard and the implementation functions
interface ITokenizedStrategy is IERC4626, IERC20Permit {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event StrategyShutdown();

    event NewTokenizedStrategy(
        address indexed strategy,
        address indexed asset,
        string apiVersion
    );

    event Reported(
        uint256 profit,
        uint256 loss,
        uint256 protocolFees,
        uint256 performanceFees
    );

    event UpdatePerformanceFeeRecipient(
        address indexed newPerformanceFeeRecipient
    );

    event UpdateKeeper(address indexed newKeeper);

    event UpdatePerformanceFee(uint16 newPerformanceFee);

    event UpdateManagement(address indexed newManagement);

    event UpdateEmergencyAdmin(address indexed newEmergencyAdmin);

    event UpdateProfitMaxUnlockTime(uint256 newProfitMaxUnlockTime);

    event UpdatePendingManagement(address indexed newPendingManagement);

    /*//////////////////////////////////////////////////////////////
                           INITIALIZATION
    //////////////////////////////////////////////////////////////*/

    function initialize(
        address _asset,
        string memory _name,
        address _management,
        address _performanceFeeRecipient,
        address _keeper
    ) external;

    /*//////////////////////////////////////////////////////////////
                    NON-STANDARD 4626 OPTIONS
    //////////////////////////////////////////////////////////////*/

    function withdraw(
        uint256 assets,
        address receiver,
        address owner,
        uint256 maxLoss
    ) external returns (uint256);

    function redeem(
        uint256 shares,
        address receiver,
        address owner,
        uint256 maxLoss
    ) external returns (uint256);

    function maxWithdraw(
        address owner,
        uint256 /*maxLoss*/
    ) external view returns (uint256);

    function maxRedeem(
        address owner,
        uint256 /*maxLoss*/
    ) external view returns (uint256);

    /*//////////////////////////////////////////////////////////////
                        MODIFIER HELPERS
    //////////////////////////////////////////////////////////////*/

    function requireManagement(address _sender) external view;

    function requireKeeperOrManagement(address _sender) external view;

    function requireEmergencyAuthorized(address _sender) external view;

    /*//////////////////////////////////////////////////////////////
                        KEEPERS FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function tend() external;

    function report() external returns (uint256 _profit, uint256 _loss);

    /*//////////////////////////////////////////////////////////////
                        CONSTANTS
    //////////////////////////////////////////////////////////////*/

    function MAX_FEE() external view returns (uint16);

    function FACTORY() external view returns (address);

    /*//////////////////////////////////////////////////////////////
                            GETTERS
    //////////////////////////////////////////////////////////////*/

    function apiVersion() external view returns (string memory);

    function pricePerShare() external view returns (uint256);

    function management() external view returns (address);

    function pendingManagement() external view returns (address);

    function keeper() external view returns (address);

    function emergencyAdmin() external view returns (address);

    function performanceFee() external view returns (uint16);

    function performanceFeeRecipient() external view returns (address);

    function fullProfitUnlockDate() external view returns (uint256);

    function profitUnlockingRate() external view returns (uint256);

    function profitMaxUnlockTime() external view returns (uint256);

    function lastReport() external view returns (uint256);

    function isShutdown() external view returns (bool);

    function unlockedShares() external view returns (uint256);

    /*//////////////////////////////////////////////////////////////
                            SETTERS
    //////////////////////////////////////////////////////////////*/

    function setPendingManagement(address) external;

    function acceptManagement() external;

    function setKeeper(address _keeper) external;

    function setEmergencyAdmin(address _emergencyAdmin) external;

    function setPerformanceFee(uint16 _performanceFee) external;

    function setPerformanceFeeRecipient(
        address _performanceFeeRecipient
    ) external;

    function setProfitMaxUnlockTime(uint256 _profitMaxUnlockTime) external;

    function setName(string calldata _newName) external;

    function shutdownStrategy() external;

    function emergencyWithdraw(uint256 _amount) external;
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.18;

// Math library from https://github.com/ajna-finance/ajna-core/blob/master/src/libraries/internal/Maths.sol

/**
    @title  Maths library
    @notice Internal library containing common maths.
 */
library Maths {
    uint256 internal constant WAD = 1e18;
    uint256 internal constant RAY = 1e27;

    function wmul(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x * y + WAD / 2) / WAD;
    }

    function floorWmul(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x * y) / WAD;
    }

    function ceilWmul(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x * y + WAD - 1) / WAD;
    }

    function wdiv(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x * WAD + y / 2) / y;
    }

    function floorWdiv(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x * WAD) / y;
    }

    function ceilWdiv(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x * WAD + y - 1) / y;
    }

    function ceilDiv(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x + y - 1) / y;
    }

    function max(uint256 x, uint256 y) internal pure returns (uint256) {
        return x >= y ? x : y;
    }

    function min(uint256 x, uint256 y) internal pure returns (uint256) {
        return x <= y ? x : y;
    }

    function wad(uint256 x) internal pure returns (uint256) {
        return x * WAD;
    }

    function rmul(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x * y + RAY / 2) / RAY;
    }

    function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
        z = n % 2 != 0 ? x : RAY;

        for (n /= 2; n != 0; n /= 2) {
            x = rmul(x, x);

            if (n % 2 != 0) {
                z = rmul(z, x);
            }
        }
    }

    /*************************/
    /*** Integer Functions ***/
    /*************************/

    function maxInt(int256 x, int256 y) internal pure returns (int256) {
        return x >= y ? x : y;
    }

    function minInt(int256 x, int256 y) internal pure returns (int256) {
        return x <= y ? x : y;
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

interface ITaker {
    function auctionTakeCallback(
        address _from,
        address _sender,
        uint256 _amountTaken,
        uint256 _amountNeeded,
        bytes calldata _data
    ) external;
}

// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.0;

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

/// @title Gnosis Protocol v2 Order Library
/// @author Gnosis Developers
library GPv2Order {
    /// @dev The complete data for a Gnosis Protocol order. This struct contains
    /// all order parameters that are signed for submitting to GP.
    struct Data {
        ERC20 sellToken;
        ERC20 buyToken;
        address receiver;
        uint256 sellAmount;
        uint256 buyAmount;
        uint32 validTo;
        bytes32 appData;
        uint256 feeAmount;
        bytes32 kind;
        bool partiallyFillable;
        bytes32 sellTokenBalance;
        bytes32 buyTokenBalance;
    }

    /// @dev The order EIP-712 type hash for the [`GPv2Order.Data`] struct.
    ///
    /// This value is pre-computed from the following expression:
    /// ```
    /// keccak256(
    ///     "Order(" +
    ///         "address sellToken," +
    ///         "address buyToken," +
    ///         "address receiver," +
    ///         "uint256 sellAmount," +
    ///         "uint256 buyAmount," +
    ///         "uint32 validTo," +
    ///         "bytes32 appData," +
    ///         "uint256 feeAmount," +
    ///         "string kind," +
    ///         "bool partiallyFillable" +
    ///         "string sellTokenBalance" +
    ///         "string buyTokenBalance" +
    ///     ")"
    /// )
    /// ```
    bytes32 internal constant TYPE_HASH =
        hex"d5a25ba2e97094ad7d83dc28a6572da797d6b3e7fc6663bd93efb789fc17e489";

    /// @dev The marker value for a sell order for computing the order struct
    /// hash. This allows the EIP-712 compatible wallets to display a
    /// descriptive string for the order kind (instead of 0 or 1).
    ///
    /// This value is pre-computed from the following expression:
    /// ```
    /// keccak256("sell")
    /// ```
    bytes32 internal constant KIND_SELL =
        hex"f3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775";

    /// @dev The OrderKind marker value for a buy order for computing the order
    /// struct hash.
    ///
    /// This value is pre-computed from the following expression:
    /// ```
    /// keccak256("buy")
    /// ```
    bytes32 internal constant KIND_BUY =
        hex"6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc";

    /// @dev The TokenBalance marker value for using direct ERC20 balances for
    /// computing the order struct hash.
    ///
    /// This value is pre-computed from the following expression:
    /// ```
    /// keccak256("erc20")
    /// ```
    bytes32 internal constant BALANCE_ERC20 =
        hex"5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9";

    /// @dev The TokenBalance marker value for using Balancer Vault external
    /// balances (in order to re-use Vault ERC20 approvals) for computing the
    /// order struct hash.
    ///
    /// This value is pre-computed from the following expression:
    /// ```
    /// keccak256("external")
    /// ```
    bytes32 internal constant BALANCE_EXTERNAL =
        hex"abee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632";

    /// @dev The TokenBalance marker value for using Balancer Vault internal
    /// balances for computing the order struct hash.
    ///
    /// This value is pre-computed from the following expression:
    /// ```
    /// keccak256("internal")
    /// ```
    bytes32 internal constant BALANCE_INTERNAL =
        hex"4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce";

    /// @dev Marker address used to indicate that the receiver of the trade
    /// proceeds should the owner of the order.
    ///
    /// This is chosen to be `address(0)` for gas efficiency as it is expected
    /// to be the most common case.
    address internal constant RECEIVER_SAME_AS_OWNER = address(0);

    /// @dev The byte length of an order unique identifier.
    uint256 internal constant UID_LENGTH = 56;

    /// @dev Returns the actual receiver for an order. This function checks
    /// whether or not the [`receiver`] field uses the marker value to indicate
    /// it is the same as the order owner.
    ///
    /// @return receiver The actual receiver of trade proceeds.
    function actualReceiver(
        Data memory order,
        address owner
    ) internal pure returns (address receiver) {
        if (order.receiver == RECEIVER_SAME_AS_OWNER) {
            receiver = owner;
        } else {
            receiver = order.receiver;
        }
    }

    /// @dev Return the EIP-712 signing hash for the specified order.
    ///
    /// @param order The order to compute the EIP-712 signing hash for.
    /// @param domainSeparator The EIP-712 domain separator to use.
    /// @return orderDigest The 32 byte EIP-712 struct hash.
    function hash(
        Data memory order,
        bytes32 domainSeparator
    ) internal pure returns (bytes32 orderDigest) {
        bytes32 structHash;

        // NOTE: Compute the EIP-712 order struct hash in place. As suggested
        // in the EIP proposal, noting that the order struct has 10 fields, and
        // including the type hash `(12 + 1) * 32 = 416` bytes to hash.
        // <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-encodedata>
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let dataStart := sub(order, 32)
            let temp := mload(dataStart)
            mstore(dataStart, TYPE_HASH)
            structHash := keccak256(dataStart, 416)
            mstore(dataStart, temp)
        }

        // NOTE: Now that we have the struct hash, compute the EIP-712 signing
        // hash using scratch memory past the free memory pointer. The signing
        // hash is computed from `"\x19\x01" || domainSeparator || structHash`.
        // <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory>
        // <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification>
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let freeMemoryPointer := mload(0x40)
            mstore(freeMemoryPointer, "\x19\x01")
            mstore(add(freeMemoryPointer, 2), domainSeparator)
            mstore(add(freeMemoryPointer, 34), structHash)
            orderDigest := keccak256(freeMemoryPointer, 66)
        }
    }

    /// @dev Packs order UID parameters into the specified memory location. The
    /// result is equivalent to `abi.encodePacked(...)` with the difference that
    /// it allows re-using the memory for packing the order UID.
    ///
    /// This function reverts if the order UID buffer is not the correct size.
    ///
    /// @param orderUid The buffer pack the order UID parameters into.
    /// @param orderDigest The EIP-712 struct digest derived from the order
    /// parameters.
    /// @param owner The address of the user who owns this order.
    /// @param validTo The epoch time at which the order will stop being valid.
    function packOrderUidParams(
        bytes memory orderUid,
        bytes32 orderDigest,
        address owner,
        uint32 validTo
    ) internal pure {
        require(orderUid.length == UID_LENGTH, "GPv2: uid buffer overflow");

        // NOTE: Write the order UID to the allocated memory buffer. The order
        // parameters are written to memory in **reverse order** as memory
        // operations write 32-bytes at a time and we want to use a packed
        // encoding. This means, for example, that after writing the value of
        // `owner` to bytes `20:52`, writing the `orderDigest` to bytes `0:32`
        // will **overwrite** bytes `20:32`. This is desirable as addresses are
        // only 20 bytes and `20:32` should be `0`s:
        //
        //        |           1111111111222222222233333333334444444444555555
        //   byte | 01234567890123456789012345678901234567890123456789012345
        // -------+---------------------------------------------------------
        //  field | [.........orderDigest..........][......owner.......][vT]
        // -------+---------------------------------------------------------
        // mstore |                         [000000000000000000000000000.vT]
        //        |                     [00000000000.......owner.......]
        //        | [.........orderDigest..........]
        //
        // Additionally, since Solidity `bytes memory` are length prefixed,
        // 32 needs to be added to all the offsets.
        //
        // solhint-disable-next-line no-inline-assembly
        assembly {
            mstore(add(orderUid, 56), validTo)
            mstore(add(orderUid, 52), owner)
            mstore(add(orderUid, 32), orderDigest)
        }
    }

    /// @dev Extracts specific order information from the standardized unique
    /// order id of the protocol.
    ///
    /// @param orderUid The unique identifier used to represent an order in
    /// the protocol. This uid is the packed concatenation of the order digest,
    /// the validTo order parameter and the address of the user who created the
    /// order. It is used by the user to interface with the contract directly,
    /// and not by calls that are triggered by the solvers.
    /// @return orderDigest The EIP-712 signing digest derived from the order
    /// parameters.
    /// @return owner The address of the user who owns this order.
    /// @return validTo The epoch time at which the order will stop being valid.
    function extractOrderUidParams(
        bytes calldata orderUid
    )
        internal
        pure
        returns (bytes32 orderDigest, address owner, uint32 validTo)
    {
        require(orderUid.length == UID_LENGTH, "GPv2: invalid uid");

        // Use assembly to efficiently decode packed calldata.
        // solhint-disable-next-line no-inline-assembly
        assembly {
            orderDigest := calldataload(orderUid.offset)
            owner := shr(96, calldataload(add(orderUid.offset, 32)))
            validTo := shr(224, calldataload(add(orderUid.offset, 52)))
        }
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

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

contract Governance2Step is Governance {
    /// @notice Emitted when the pending governance address is set.
    event UpdatePendingGovernance(address indexed newPendingGovernance);

    /// @notice Address that is set to take over governance.
    address public pendingGovernance;

    constructor(address _governance) Governance(_governance) {}

    /**
     * @notice Sets a new address as the `pendingGovernance` of the contract.
     * @dev Throws if the caller is not current governance.
     * @param _newGovernance The new governance address.
     */
    function transferGovernance(
        address _newGovernance
    ) external virtual override onlyGovernance {
        require(_newGovernance != address(0), "ZERO ADDRESS");
        pendingGovernance = _newGovernance;

        emit UpdatePendingGovernance(_newGovernance);
    }

    /**
     * @notice Allows the `pendingGovernance` to accept the role.
     */
    function acceptGovernance() external virtual {
        require(msg.sender == pendingGovernance, "!pending governance");

        emit GovernanceTransferred(governance, msg.sender);

        governance = msg.sender;
        pendingGovernance = address(0);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

contract Clonable {
    /// @notice Set to the address to auto clone from.
    address public original;

    /**
     * @notice Clone the contracts default `original` contract.
     * @return Address of the new Minimal Proxy clone.
     */
    function _clone() internal virtual returns (address) {
        return _clone(original);
    }

    /**
     * @notice Clone any `_original` contract.
     * @return _newContract Address of the new Minimal Proxy clone.
     */
    function _clone(
        address _original
    ) internal virtual returns (address _newContract) {
        // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
        bytes20 addressBytes = bytes20(_original);
        assembly {
            // EIP-1167 bytecode
            let clone_code := mload(0x40)
            mstore(
                clone_code,
                0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
            )
            mstore(add(clone_code, 0x14), addressBytes)
            mstore(
                add(clone_code, 0x28),
                0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
            )
            _newContract := create(0, clone_code, 0x37)
        }
    }
}

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

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.8.18;

contract Governance {
    /// @notice Emitted when the governance address is updated.
    event GovernanceTransferred(
        address indexed previousGovernance,
        address indexed newGovernance
    );

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

    /// @notice Checks if the msg sender is the governance.
    function _checkGovernance() internal view virtual {
        require(governance == msg.sender, "!governance");
    }

    /// @notice Address that can set the default base fee and provider
    address public governance;

    constructor(address _governance) {
        governance = _governance;

        emit GovernanceTransferred(address(0), _governance);
    }

    /**
     * @notice Sets a new address as the governance of the contract.
     * @dev Throws if the caller is not current governance.
     * @param _newGovernance The new governance address.
     */
    function transferGovernance(
        address _newGovernance
    ) external virtual onlyGovernance {
        require(_newGovernance != address(0), "ZERO ADDRESS");
        address oldGovernance = governance;
        governance = _newGovernance;

        emit GovernanceTransferred(oldGovernance, _newGovernance);
    }
}

Settings
{
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "forge-std/=lib/forge-std/src/",
    "@tokenized-strategy/=lib/tokenized-strategy/src/",
    "@periphery/=lib/tokenized-strategy-periphery/src/",
    "@yearn-vaults/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/contracts/",
    "ds-test/=lib/tokenized-strategy/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/tokenized-strategy/lib/erc4626-tests/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/",
    "tokenized-strategy-periphery/=lib/tokenized-strategy-periphery/",
    "tokenized-strategy/=lib/tokenized-strategy/",
    "yearn-vaults-v3/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "shanghai",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"address","name":"_collateralToken","type":"address"},{"internalType":"address","name":"_morpho","type":"address"},{"internalType":"Id","name":"_marketId","type":"bytes32"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"auction","type":"address"}],"name":"AuctionSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bool","name":"useAuction","type":"bool"}],"name":"UseAuctionSet","type":"event"},{"stateMutability":"nonpayable","type":"fallback"},{"inputs":[],"name":"MERKL_DISTRIBUTOR","outputs":[{"internalType":"contract IMerklDistributor","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"allowed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"auction","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"}],"name":"auctionTrigger","outputs":[{"internalType":"bool","name":"shouldKick","type":"bool"},{"internalType":"bytes","name":"data","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"availableDepositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"availableWithdrawLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfAsset","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfCollateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfCollateralToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"balanceOfDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"base","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"users","type":"address[]"},{"internalType":"address[]","name":"tokens","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes32[][]","name":"proofs","type":"bytes32[][]"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collateralToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"convertAssetToCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"convertCollateralToAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"deployFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"depositLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"doHealthCheck","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"estimatedTotalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"freeFunds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getCurrentLTV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLiquidateCollateralFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_equity","type":"uint256"}],"name":"getTargetPosition","outputs":[{"internalType":"uint256","name":"collateral","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"harvestAndReport","outputs":[{"internalType":"uint256","name":"_totalAssets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"kickAuction","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"kickable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"leverageBuffer","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lossLimitRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"manualFullUnwind","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualRepay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualSupplyCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"manualWithdrawCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"marketId","outputs":[{"internalType":"Id","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxFlashloan","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxGasPriceToTend","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minAmountToBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minAmountToSell","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"morpho","outputs":[{"internalType":"contract IMorpho","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onMorphoFlashLoan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"position","outputs":[{"internalType":"uint256","name":"collateralValue","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"currentLTV","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"profitLimitRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"router","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"},{"internalType":"bool","name":"_allowed","type":"bool"}],"name":"setAllowed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_auction","type":"address"}],"name":"setAuction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_depositLimit","type":"uint256"}],"name":"setDepositLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_doHealthCheck","type":"bool"}],"name":"setDoHealthCheck","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_targetLeverageRatio","type":"uint256"},{"internalType":"uint256","name":"_leverageBuffer","type":"uint256"},{"internalType":"uint256","name":"_maxLeverageRatio","type":"uint256"}],"name":"setLeverageParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newLossLimitRatio","type":"uint256"}],"name":"setLossLimitRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxGasPriceToTend","type":"uint256"}],"name":"setMaxGasPriceToTend","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minAmountToBorrow","type":"uint256"}],"name":"setMinAmountToBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newProfitLimitRatio","type":"uint256"}],"name":"setProfitLimitRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_slippage","type":"uint256"}],"name":"setSlippage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"},{"internalType":"uint24","name":"_fee","type":"uint24"}],"name":"setUniFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_useAuction","type":"bool"}],"name":"setUseAuction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"shutdownWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"slippage","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"targetLeverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_totalIdle","type":"uint256"}],"name":"tendThis","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tendTrigger","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenizedStrategyAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"uniFees","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"useAuction","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

6101206040525f805462ffffff19166227100117905560108054610100600160a81b03191674c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2001790556011805473e592427a0aece92de3edee1f18e0157c058615646001600160a01b031990911617905534801562000071575f80fd5b5060405162005c0238038062005c028339810160408190526200009491620009f8565b6001600160a01b0385166080523060a0526040518590859085908590859085908590859083908390829082906200011190620000dd908490849033908190819060240162000b00565b60408051601f198184030181529190526020810180516001600160e01b03908116634b839d7360e11b179091526200039516565b505073d377919fa87120584b21279a491f82d5265a139c7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc555050506001600160a01b03811660c0525f19600755305f908152600860205260409020805460ff191660019081179091556729a2241af62c000090556703782dace9d90000600255673782dace9d900000600355642e90edd000600555600480546001600160401b0319166032179055620001c6600a62000424565b620001d36103e862000486565b5050506001600160a01b03821660e0819052610100829052604051632c3c915760e01b815260048101839052632c3c91579060240160a060405180830381865afa15801562000224573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200024a919062000b42565b8051600b80546001600160a01b03199081166001600160a01b039384169081179092556020840151600c805483169185169190911790556040840151600d805483169185169190911790556060840151600e8054909216908416179055608090920151600f55861614620002f25760405162461bcd60e51b815260206004820152600a60248201526910b637b0b72a37b5b2b760b11b60448201526064015b60405180910390fd5b600c546001600160a01b038481169116146200033f5760405162461bcd60e51b815260206004820152600b60248201526a0858dbdb1b185d195c985b60aa1b6044820152606401620002e9565b620003566001600160a01b038616835f1962000523565b6200036d6001600160a01b038416835f1962000523565b50505050506200038a60805160c0516064620005f860201b60201c565b505050505062000c27565b60605f8073d377919fa87120584b21279a491f82d5265a139c6001600160a01b031684604051620003c7919062000bd5565b5f60405180830381855af49150503d805f811462000401576040519150601f19603f3d011682016040523d82523d5f602084013e62000406565b606091505b5091509150816200041d576040513d805f833e8082fd5b9392505050565b6127108110620004655760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401620002e9565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b5f8111620004c65760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401620002e9565b61ffff811115620005065760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401620002e9565b5f805461ffff9092166101000262ffff0019909216919091179055565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b0390811663095ea7b360e01b179091526200057d90859083906200065216565b620005f2576040516001600160a01b03841660248201525f6044820152620005e690859063095ea7b360e01b9060640160408051808303601f190181529190526020810180516001600160e01b0319939093166001600160e01b0393841617905290620006fc16565b620005f28482620006fc565b50505050565b6001600160a01b039283165f818152601260208181526040808420969097168352948552858220805462ffffff90951662ffffff199586168117909155908552858220928252919093529290912080549091169091179055565b5f805f846001600160a01b0316846040516200066f919062000bd5565b5f604051808303815f865af19150503d805f8114620006aa576040519150601f19603f3d011682016040523d82523d5f602084013e620006af565b606091505b5091509150818015620006dd575080511580620006dd575080806020019051810190620006dd919062000bf2565b8015620006f357506001600160a01b0385163b15155b95945050505050565b6040805180820190915260208082527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564908201525f906200074a906001600160a01b038516908490620007d3565b905080515f14806200076d5750808060200190518101906200076d919062000bf2565b620007ce5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401620002e9565b505050565b6060620007e384845f85620007eb565b949350505050565b6060824710156200084e5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401620002e9565b5f80866001600160a01b031685876040516200086b919062000bd5565b5f6040518083038185875af1925050503d805f8114620008a7576040519150601f19603f3d011682016040523d82523d5f602084013e620008ac565b606091505b509092509050620008c087838387620008cb565b979650505050505050565b606083156200093e5782515f0362000936576001600160a01b0385163b620009365760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401620002e9565b5081620007e3565b620007e38383815115620009555781518083602001fd5b8060405162461bcd60e51b8152600401620002e9919062000c13565b80516001600160a01b038116811462000988575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b0381118282101715620009cc57620009cc6200098d565b604052919050565b5f5b83811015620009f0578181015183820152602001620009d6565b50505f910152565b5f805f805f60a0868803121562000a0d575f80fd5b62000a188662000971565b60208701519095506001600160401b038082111562000a35575f80fd5b818801915088601f83011262000a49575f80fd5b81518181111562000a5e5762000a5e6200098d565b62000a73601f8201601f1916602001620009a1565b915080825289602082850101111562000a8a575f80fd5b62000a9d816020840160208601620009d4565b50945062000ab090506040870162000971565b925062000ac06060870162000971565b9150608086015190509295509295909350565b5f815180845262000aec816020860160208601620009d4565b601f01601f19169290920160200192915050565b5f60018060a01b03808816835260a0602084015262000b2360a084018862000ad3565b9581166040840152938416606083015250911660809091015292915050565b5f60a0828403121562000b53575f80fd5b60405160a081016001600160401b038111828210171562000b785762000b786200098d565b60405262000b868362000971565b815262000b966020840162000971565b602082015262000ba96040840162000971565b604082015262000bbc6060840162000971565b6060820152608083015160808201528091505092915050565b5f825162000be8818460208701620009d4565b9190910192915050565b5f6020828403121562000c03575f80fd5b815180151581146200041d575f80fd5b602081525f6200041d602083018462000ad3565b60805160a05160c05160e05161010051614e4662000dbc5f395f818161065c01528181611357015281816129f401526137e701525f818161082c01528181610bde01528181610e3d0152818161138f01528181611bb50152818161235f0152818161252d0152818161298b015281816129d201528181612a3301528181612c3901528181612fb80152818161381f0152613a4701525f8181610762015281816115f80152818161310b01526139bf01525f818161093901528181610a0901528181610a8801528181610b1801528181610e9101528181610f4201528181611299015281816114e601528181611644015281816116a701528181611741015281816117bd01528181611844015281816118d001528181611956015281816119d201528181611aa901528181611b2501528181611c5a01528181611d2e01528181611db201528181611e4a015281816123e4015281816125af015261300c01525f818161156f01528181611bdf015281816128750152818161312c0152818161368201528181613792015261399e0152614e465ff3fe608060405234801561000f575f80fd5b50600436106103d9575f3560e01c8063797bf34311610208578063cfaec0da11610123578063ecf70858116100b6578063f887ea4011610085578063f887ea40146108c5578063fc7f71b6146108d8578063fd9f5f75146108eb578063fde813a8146108fe578063ff831b0514610911576103d9565b8063ecf708581461085e578063efbb5cb014610867578063f0fa55a91461086f578063f3ce280a14610882576103d9565b8063d6968601116100f2578063d696860114610814578063d8fbc83314610827578063e86211491461084e578063ea9c840714610856576103d9565b8063cfaec0da146107bb578063d19a3bb8146107ce578063d472a43b146107e9578063d63a8e11146107f2576103d9565b80639b90fb161161019b578063b6a165061161016a578063b6a1650614610784578063b8c6f5791461078d578063bdc8144b146107a0578063c31443bb146107b3576103d9565b80639b90fb16146107245780639d7fb70c14610737578063ac00ff261461074a578063b2016bd41461075d576103d9565b806384d78a38116101d757806384d78a38146106e25780638ca6dd4d146106f6578063950b3d73146106fe57806398cdabc914610711576103d9565b8063797bf343146106ad5780637baf6f77146106b55780637d969932146106bd5780637d9f6db5146106cf576103d9565b806349317f1d116102f85780636687500e1161028b5780636ed71ede1161025a5780636ed71ede1461065757806371ee95c01461067e57806372b10dd514610691578063757a291f1461069a576103d9565b80636687500e146106035780636718835f1461060b5780636be36a1d146106275780636c7a0c911461062f576103d9565b8063503160d9116102c7578063503160d9146105cc578063580e0d81146105df5780635d265d3f146105f25780635ef76292146105fa576103d9565b806349317f1d146105895780634a5d0943146105915780634aca9482146105a15780635001f3b5146105b4576103d9565b80632e3ecf2c116103705780633d6cb5751161033f5780633d6cb575146105255780633e032a3b146105385780634697f05d1461056357806346aa2f1214610576576103d9565b80632e3ecf2c146104d657806331f57072146104e95780633259356e146104fc578063392f7a701461051d576103d9565b806318144367116103ac578063181443671461047457806320aa49ae1461047d578063219461ed146104905780632b0015e6146104c3576103d9565b806304bd46291461040e5780630870e1801461043557806309218e91146104485780630ea44a561461046b575b73d377919fa87120584b21279a491f82d5265a139c365f80375f80365f845af43d5f803e808015610408573d5ff35b3d5ffd5b005b61042261041c3660046143e3565b505f1990565b6040519081526020015b60405180910390f35b61040c6104433660046143fe565b610924565b61045061099f565b6040805193845260208401929092529082015260600161042c565b61042260015481565b61042260095481565b61040c61048b366004614422565b6109f4565b6104ab733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae81565b6040516001600160a01b03909116815260200161042c565b61040c6104d13660046143fe565b610a73565b61040c6104e436600461443d565b610b03565b61040c6104f736600461448c565b610bd3565b61050f61050a3660046143e3565b610cbe565b60405161042c92919061454d565b610422610df3565b61040c6105333660046143fe565b610e6b565b60045461054b906001600160401b031681565b6040516001600160401b03909116815260200161042c565b61040c610571366004614567565b610e7c565b6104226105843660046143e3565b610f19565b610422611062565b5f54610100900461ffff16610422565b6104226105af3660046143e3565b611081565b6010546104ab9061010090046001600160a01b031681565b61040c6105da3660046143fe565b61127c565b61040c6105ed3660046143fe565b611284565b61050f61130b565b61042260035481565b610422611348565b5f546106179060ff1681565b604051901515815260200161042c565b600f54610422565b61064261063d3660046143fe565b61140b565b6040805192835260208301919091520161042c565b6104227f000000000000000000000000000000000000000000000000000000000000000081565b61040c61068c3660046145e5565b611455565b61042260065481565b61040c6106a83660046143fe565b6114d1565b610422611558565b6104226115e1565b5f546301000000900461ffff16610422565b600a546104ab906001600160a01b031681565b600a5461061790600160a01b900460ff1681565b61040c61162f565b61040c61070c3660046143fe565b61172c565b61040c61071f3660046143fe565b6117a8565b61040c6107323660046143fe565b61182f565b61040c6107453660046143fe565b6118aa565b61040c610758366004614422565b6118bb565b6104ab7f000000000000000000000000000000000000000000000000000000000000000081565b61042260055481565b61040c61079b3660046143e3565b611941565b61040c6107ae3660046143fe565b6119bd565b610422611a38565b61040c6107c93660046143fe565b611a94565b6104ab73d377919fa87120584b21279a491f82d5265a139c81565b61042260025481565b6106176108003660046143e3565b60086020525f908152604090205460ff1681565b61040c6108223660046143fe565b611b10565b6104ab7f000000000000000000000000000000000000000000000000000000000000000081565b610422611b8c565b610422611b9e565b61042260075481565b610422611c10565b61040c61087d3660046143fe565b611c45565b6108b161089036600461469f565b601260209081525f928352604080842090915290825290205462ffffff1681565b60405162ffffff909116815260200161042c565b6011546104ab906001600160a01b031681565b6104226108e63660046143e3565b611d17565b61040c6108f93660046143fe565b611d9d565b61040c61090c3660046143fe565b611e24565b61040c61091f3660046146cb565b611e35565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610981575f80fd5b505afa158015610993573d5f803e3d5ffd5b50505060069190915550565b5f805f806109ab611348565b90506109b6816120b5565b93506109c0610df3565b92505f84116109cf575f6109ec565b836109e2670de0b6b3a764000085614708565b6109ec919061471f565b915050909192565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610a51575f80fd5b505afa158015610a63573d5f803e3d5ffd5b50505050610a70816120f0565b50565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015610ad0575f80fd5b505afa158015610ae2573d5f803e3d5ffd5b50505050610aff610afa82610af56115e1565b612138565b612151565b5050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610b60575f80fd5b505afa158015610b72573d5f803e3d5ffd5b5050506001600160a01b038085165f8181526012602081815260408084209589168452948152848320805462ffffff1990811662ffffff8a16908117909255928252858420948452939052929020805490921617905550505050565b505050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610c3a5760405162461bcd60e51b8152602060048201526007602482015266216d6f7270686f60c81b60448201526064015b60405180910390fd5b60105460ff16610c7f5760405162461bcd60e51b815260206004820152601060248201526f666c6173686c6f616e2061637469766560801b6044820152606401610c31565b610bce8383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506121a992505050565b600a545f906060906001600160a01b031680610d06575f6040518060400160405280600e81526020016d139bc8185d58dd1a5bdb881cd95d60921b8152509250925050915091565b600a54600160a01b900460ff16610d4c575f60405180604001604052806011815260200170105d58dd1a5bdb9cc8191a5cd8589b1959607a1b8152509250925050915091565b5f610d5685611081565b90508015801590610d6957506009548110155b15610dbb575050604080516001600160a01b0394909416602480860191909152815180860390910181526044909401905250506020810180516001600160e01b0316637e3fb8db60e11b179052600191565b5f604051806040016040528060138152602001726e6f7420656e6f756768206b69636b61626c6560681b815250935093505050915091565b6040805160a081018252600b546001600160a01b039081168252600c5481166020830152600d54811692820192909252600e5482166060820152600f5460808201525f91610e66917f00000000000000000000000000000000000000000000000000000000000000009091169030612243565b905090565b610e73612289565b610a70816122c0565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610ed9575f80fd5b505afa158015610eeb573d5f803e3d5ffd5b505050506001600160a01b03919091165f908152600860205260409020805460ff1916911515919091179055565b6001600160a01b0381165f9081526008602052604081205460ff16610f3f57505f919050565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f9c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fc0919061473e565b90505f8160075411610fd2575f610fe0565b81600754610fe09190614755565b90505f610feb6122c9565b9050805f03610ffe57505f949350505050565b5f195f611009612311565b9050805f0361101e57505f9695505050505050565b5f8361103281670de0b6b3a7640000614755565b61103c9084614708565b611046919061471f565b905061105685610af58584612138565b98975050505050505050565b5f61106b612289565b6110736123a4565b905061107e816123c9565b90565b600a545f90600160a01b900460ff1661109b57505f919050565b600a546001600160a01b0316806110b457505f92915050565b604051639f8a13d760e01b81526001600160a01b038481166004830152821690639f8a13d790602401602060405180830381865afa1580156110f8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061111c9190614768565b801561119057506040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa15801561116a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118e919061473e565b115b1561119d57505f92915050565b6040516370a0823160e01b81526001600160a01b0382811660048301528416906370a0823190602401602060405180830381865afa1580156111e1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611205919061473e565b6040516370a0823160e01b81523060048201526001600160a01b038516906370a0823190602401602060405180830381865afa158015611247573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061126b919061473e565b6112759190614783565b9392505050565b610a70612289565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b1580156112e1575f80fd5b505afa1580156112f3573d5f803e3d5ffd5b50505050610a7061130682610af5611348565b61250c565b5f6060611316612599565b6040805160048152602481019091526020810180516001600160e01b031663440368a360e01b17905290939092509050565b6040516349e2903160e11b81527f000000000000000000000000000000000000000000000000000000000000000060048201523060248201525f9081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906393c5206290604401606060405180830381865afa1580156113d4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113f891906147f0565b604001516001600160801b031692915050565b5f805f670de0b6b3a7640000600154856114259190614708565b61142f919061471f565b90505f84821161143f575f611449565b6114498583614755565b91959194509092505050565b6040516301c7ba5760e61b8152733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae906371ee95c09061149a908b908b908b908b908b908b908b908b906004016148c9565b5f604051808303815f87803b1580156114b1575f80fd5b505af11580156114c3573d5f803e3d5ffd5b505050505050505050505050565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b15801561152e575f80fd5b505afa158015611540573d5f803e3d5ffd5b50505050610aff61155382610af5611558565b6126de565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a08231906024015b602060405180830381865afa1580156115bd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e66919061473e565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a08231906024016115a2565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b15801561168c575f80fd5b505afa15801561169e573d5f803e3d5ffd5b5050505061172a7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611701573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611725919061473e565b61273c565b565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611789575f80fd5b505afa15801561179b573d5f803e3d5ffd5b50505050610a708161289b565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611805575f80fd5b505afa158015611817573d5f803e3d5ffd5b50505050610a7061182a82610af5611558565b612934565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b15801561188c575f80fd5b505afa15801561189e573d5f803e3d5ffd5b50505060059190915550565b6118b2612289565b610a7081612ab6565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611918575f80fd5b505afa15801561192a573d5f803e3d5ffd5b50505f805460ff1916931515939093179092555050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b15801561199e575f80fd5b505afa1580156119b0573d5f803e3d5ffd5b50505050610a7081612abf565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611a1a575f80fd5b505afa158015611a2c573d5f803e3d5ffd5b50505060079190915550565b5f805f611a4361099f565b5091509150815f03611a57575f9250505090565b818110611a67575f199250505090565b611a718183614755565b611a83670de0b6b3a764000084614708565b611a8d919061471f565b9250505090565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611af1575f80fd5b505afa158015611b03573d5f803e3d5ffd5b50505050610a7081612c18565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611b6d575f80fd5b505afa158015611b7f573d5f803e3d5ffd5b50505050610a7081612cb6565b5f80611b9661099f565b949350505050565b6040516370a0823160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f917f0000000000000000000000000000000000000000000000000000000000000000909116906370a08231906024016115a2565b5f611c19610df3565b611c29611c24611348565b6120b5565b611c31611558565b611c3b9190614783565b610e669190614755565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611ca2575f80fd5b505afa158015611cb4573d5f803e3d5ffd5b505050506127108110611cf45760405162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b6044820152606401610c31565b6004805467ffffffffffffffff19166001600160401b0392909216919091179055565b60405163d43fdcf760e01b81523360048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063d43fdcf7906024015f6040518083038186803b158015611d76575f80fd5b505afa158015611d88573d5f803e3d5ffd5b50505050611d9582612d16565b90505b919050565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611dfa575f80fd5b505afa158015611e0c573d5f803e3d5ffd5b50505050610a70611e1f82610af56115e1565b612f97565b611e2c612289565b610a7081612ff2565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611e92575f80fd5b505afa158015611ea4573d5f803e3d5ffd5b50505050825f03611f02578115611efd5760405162461bcd60e51b815260206004820152601f60248201527f627566666572206d7573742062652030206966207461726765742069732030006044820152606401610c31565b611fd5565b670de0b6b3a7640000831015611f4a5760405162461bcd60e51b815260206004820152600d60248201526c0d8caeccae4c2ceca40784062f609b1b6044820152606401610c31565b662386f26fc10000821015611f945760405162461bcd60e51b815260206004820152601060248201526f189d5999995c881d1bdbc81cdb585b1b60821b6044820152606401610c31565b818311611fd55760405162461bcd60e51b815260206004820152600f60248201526e3a30b933b2ba101e10313ab33332b960891b6044820152606401610c31565b611fdf8284614783565b81101561202e5760405162461bcd60e51b815260206004820152601e60248201527f6d6178206c65766572616765203c20746172676574202b2062756666657200006044820152606401610c31565b5f81612042670de0b6b3a764000080614708565b61204c919061471f565b61205e90670de0b6b3a7640000614755565b9050612069600f5490565b81106120a65760405162461bcd60e51b815260206004820152600c60248201526b32bc31b2b2b2399026262a2b60a11b6044820152606401610c31565b50600192909255600255600355565b5f815f036120c457505f919050565b6ec097ce7bc90715b34b9f10000000006120dc6130b0565b6120e69084614708565b611d95919061471f565b600a805460ff60a01b1916600160a01b831515908102919091179091556040517feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a250565b5f8183106121465781612148565b825b90505b92915050565b5f8061215c836130f7565b9050612168835f613152565b81101561214b5760405162461bcd60e51b815260206004820152600f60248201526e1cdb1a5c1c1859d94e88185cdcd95d608a1b6044820152606401610c31565b5f818060200190518101906121be91906149a4565b90505f815160018111156121d4576121d46149fc565b036121e357610bce83826131af565b6001815160018111156121f8576121f86149fc565b0361220757610bce83826131e6565b60405162461bcd60e51b815260206004820152601160248201527034b73b30b634b21037b832b930ba34b7b760791b6044820152606401610c31565b5f806122508460a0902090565b90505f6122676001600160a01b038716838661321a565b90505f8061227588886132cc565b9094509250611056915084905083836135c2565b33301461172a5760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b6044820152606401610c31565b610a708161273c565b5f670de0b6b3a7640000600154116122e057505f90565b6001546122f5670de0b6b3a764000080614708565b6122ff919061471f565b610e6690670de0b6b3a7640000614755565b6040805160a081018252600b546001600160a01b039081168252600c5481166020830152600d54811692820192909252600e5482166060820152600f5460808201525f9182918291612387917f0000000000000000000000000000000000000000000000000000000000000000909116906132cc565b50925050915080821161239a575f611a8d565b611a8d8183614755565b5f6123c16123bc6123b3611558565b610af530610f19565b6135e6565b610e66611c10565b5f5460ff166123e157505f805460ff19166001179055565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa15801561243e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612462919061473e565b9050808211156124d5575f546127109061248590610100900461ffff1683614708565b61248f919061471f565b6124998284614755565b1115610aff5760405162461bcd60e51b815260206004820152600b60248201526a6865616c7468436865636b60a81b6044820152606401610c31565b81811115610aff575f54612710906124f8906301000000900461ffff1683614708565b612502919061471f565b6124998383614755565b805f036125165750565b604051638720316d60e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690638720316d9061256990600b90859030908190600401614a4e565b5f604051808303815f87803b158015612580575f80fd5b505af1158015612592573d5f803e3d5ffd5b5050505050565b5f6125a26137d8565b156125ad5750600190565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612609573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061262d919061473e565b5f0361263857505f90565b5f612641611a38565b905060035481111561265557600191505090565b6001545f819003612675575f82118015611a8d5750600554481115611a8d565b600654612680611558565b111561269157600554481115611a8d565b5f600254826126a09190614783565b90505f600254836126b19190614755565b9050808410806126c057508184115b156126d45760055448111594505050505090565b5f94505050505090565b5f806126e98361398a565b90506126f6836001613152565b81101561214b5760405162461bcd60e51b81526020600482015260146024820152731cdb1a5c1c1859d94e8818dbdb1b185d195c985b60621b6044820152606401610c31565b5f8061274661099f565b5091509150805f0361277b575f61276761275f856139e5565b610af5611348565b90506127728161250c565b61259281612151565b5f6127868284614755565b90505f848211612796575f6127a0565b6127a08583614755565b90505f6127ac8261140b565b9150505f8185116127bd575f6127f5565b600454612710906127d7906001600160401b031682614783565b6127e18488614755565b6127eb9190614708565b6127f5919061471f565b90505f61280a6128058984614783565b6139e5565b90508115801561281957508015155b1561283b576128278161250c565b61283081612151565b505050505050505050565b60408051808201825260018152602080820184905291515f9261285f929101614a82565b60405160208183030381529060405290506128307f00000000000000000000000000000000000000000000000000000000000000008483613a23565b5f81116128d95760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401610c31565b61ffff8111156129175760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401610c31565b5f805461ffff9092166101000262ffff0019909216919091179055565b805f0361293e5750565b6040805160a081018252600b546001600160a01b039081168252600c5481166020830152600d54811692820192909252600e549091166060820152600f5460808201525f9081906129b0907f0000000000000000000000000000000000000000000000000000000000000000906132cc565b9350935050505f612a196129c5858585613abc565b610af56001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f00000000000000000000000000000000000000000000000000000000000000003061321a565b6040516320b76e8160e01b81529091506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906320b76e8190612a6f90600b905f9086903090600401614ab9565b60408051808303815f875af1158015612a8a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612aae9190614aff565b505050505050565b610a70816135e6565b6001600160a01b03811615612bcf57306001600160a01b0316816001600160a01b031663f7260d3e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b14573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b389190614b21565b6001600160a01b031614612b7f5760405162461bcd60e51b815260206004820152600e60248201526d3bb937b733903932b1b2b4bb32b960911b6044820152606401610c31565b600a54600160a01b900460ff16612bcf57600a805460ff60a01b1916600160a01b1790556040516001907feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a25b600a80546001600160a01b0319166001600160a01b0383169081179091556040517f4da9b3b7ca08b559bc11eb42bb6961e0813372ed0b55f0e9b68b76cf0207fce8905f90a250565b805f03612c225750565b6040516350d8cd4b60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906350d8cd4b90612c7790600b9085905f9030908190600401614b3c565b60408051808303815f875af1158015612c92573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bce9190614aff565b6127108110612cf55760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401610c31565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b600a545f90600160a01b900460ff16612d675760405162461bcd60e51b815260206004820152601360248201527275736541756374696f6e2069732066616c736560681b6044820152606401610c31565b600a54604051639f8a13d760e01b81526001600160a01b038481166004830152909116908190639f8a13d790602401602060405180830381865afa158015612db1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612dd59190614768565b15612eaa576040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa158015612e21573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e45919061473e565b1115612e5357505f92915050565b604051636a256b2960e01b81526001600160a01b038481166004830152821690636a256b29906024015f604051808303815f87803b158015612e93575f80fd5b505af1158015612ea5573d5f803e3d5ffd5b505050505b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa158015612eee573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f12919061473e565b90508015612f2e57612f2e6001600160a01b0385168383613ae0565b6040516396c5517560e01b81526001600160a01b0385811660048301528316906396c55175906024016020604051808303815f875af1158015612f73573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b96919061473e565b805f03612fa15750565b60405163238d657960e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063238d65799061256990600b9085903090600401614b78565b5f612ffb610df3565b9050801561308a57610aff611725837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015613066573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610af5919061473e565b8115610aff5761309c82610af5611348565b91506130a78261250c565b610bce82612151565b600d546040805163501ad8ff60e11b815290515f926001600160a01b03169163a035b1fe9160048083019260209291908290030181865afa1580156115bd573d5f803e3d5ffd5b5f815f0361310657505f919050565b611d957f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000845f613b43565b5f825f0361316157505f61214b565b5f8261317557613170846120b5565b61317e565b61317e846139e5565b6004549091506127109061319b906001600160401b031682614755565b6131a59083614708565b611b96919061471f565b5f8282602001516131c09190614783565b90505f6131cc826126de565b90506131d781612f97565b6131e084612c18565b50505050565b6131f561182a83610af5610df3565b5f6132068260200151610af5611348565b90506132118161250c565b6131e081612151565b5f8061322e6132298585613df5565b613e68565b604051637784c68560e01b81529091506001600160a01b03861690637784c6859061325d908490600401614bb8565b5f60405180830381865afa158015613277573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261329e9190810190614bfb565b5f815181106132af576132af614c8f565b60200260200101515f1c6001600160801b03169150509392505050565b5f805f805f6132dc8660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa158015613324573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133489190614ca3565b90505f81608001516001600160801b0316426133649190614755565b90508015801590613381575060408201516001600160801b031615155b8015613399575060608801516001600160a01b031615155b1561358e576060888101805160408051638c00bf6b60e01b81528c516001600160a01b0390811660048301526020808f015182166024840152838f0151821660448401529451811660648301526080808f0151608484015288516001600160801b0390811660a485015295890151861660c484015292880151851660e483015294870151841661010482015290860151831661012482015260a08601519092166101448301525f921690638c00bf6b9061016401602060405180830381865afa158015613468573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061348c919061473e565b90505f6134b061349c8385613eb1565b60408601516001600160801b031690613f0f565b90506134bb81613f23565b846040018181516134cc9190614d3f565b6001600160801b03169052506134e181613f23565b845185906134f0908390614d3f565b6001600160801b0390811690915260a08601511615905061358b575f61352c8560a001516001600160801b031683613f0f90919063ffffffff16565b90505f61356082875f01516001600160801b031661354a9190614755565b60208801518491906001600160801b0316613abc565b905061356b81613f23565b8660200181815161357c9190614d3f565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f611b966135d1600185614783565b6135de620f424085614783565b869190613f7f565b5f806135f061099f565b5090925090505f836136028385614755565b61360c9190614783565b90505f6136188261140b565b915050828111156136af575f61362e8483614755565b9050600654811161364857612aae61182a87610af5610df3565b6040805180820182525f80825260208083018a90529251909261366c929101614a82565b60405160208183030381529060405290506136a87f00000000000000000000000000000000000000000000000000000000000000008383613a23565b5050612592565b808311156137c9575f6136c28285614755565b90508086106136fc576136d481612934565b5f6136df8288614755565b905080156136f3576136f3611e1f826126de565b50505050505050565b61370586612934565b6004545f9061271090613721906001600160401b031682614783565b61372e6128058a86614755565b6137389190614708565b613742919061471f565b90505f6040518060400160405280600180811115613762576137626149fc565b81526020018381525060405160200161377b9190614a82565b60408051601f1981840301815291905290506137c17f00000000000000000000000000000000000000000000000000000000000000006137bb8a86614755565b83613a23565b505050612592565b61259261182a86610af5610df3565b6040516349e2903160e11b81527f000000000000000000000000000000000000000000000000000000000000000060048201523060248201525f9081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906393c5206290604401606060405180830381865afa158015613864573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061388891906147f0565b905080602001516001600160801b03165f036138a5575f91505090565b5f6ec097ce7bc90715b34b9f1000000000600b6002015f9054906101000a90046001600160a01b03166001600160a01b031663a035b1fe6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613909573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061392d919061473e565b83604001516001600160801b03166139459190614708565b61394f919061471f565b90505f670de0b6b3a7640000600b600401548361396c9190614708565b613976919061471f565b905080613981610df3565b11935050505090565b5f815f0361399957505f919050565b611d957f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000845f613b43565b5f815f036139f457505f919050565b5f6139fd6130b0565b905080613a196ec097ce7bc90715b34b9f100000000085614708565b611275919061471f565b6010805460ff1916600117905560405163701195a160e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063e0232b4290613a8090869086908690600401614d66565b5f604051808303815f87803b158015613a97575f80fd5b505af1158015613aa9573d5f803e3d5ffd5b50506010805460ff191690555050505050565b5f611b96613acd620f424084614783565b613ad8600186614783565b869190613fa0565b6040516001600160a01b038316602482015260448101829052610bce90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613fac565b5f8215801590613b5557506009548310155b15611b9657601154613b71906001600160a01b0316868561407f565b6010546001600160a01b03868116610100909204161480613ba457506010546001600160a01b0385811661010090920416145b15613cba5760408051610100810182526001600160a01b0387811680835287821660208085018281525f938452601282528684209284529190528482205462ffffff9081168587019081523060608701908152426080880190815260a088018c815260c089018c815260e08a019788526011549a5163414bf38960e01b81528a518a16600482015296518916602488015293519094166044860152905186166064850152516084840152905160a48301525160c48201529051821660e48201529192169063414bf38990610104016020604051808303815f875af1158015613c8e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613cb2919061473e565b915050611b96565b6001600160a01b038581165f90815260126020818152604080842060105461010090048087168652908352818520549383528185208a8716865283529381902054815160608c811b6bffffffffffffffffffffffff199081169583019590955260e895861b6001600160e81b0319908116603484015296811b851660378301529190941b909416604b8401529288901b16604e8201528151604281830301815260115461010283018452606283018281523060828501524260a285015260c2840189905260e2909301879052925163c04b8d5960e01b81529093929092169163c04b8d5991613dab91600401614d8c565b6020604051808303815f875af1158015613dc7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613deb919061473e565b9695505050505050565b5f600182846002604051602001613e16929190918252602082015260400190565b60408051601f1981840301815282825280516020918201206001600160a01b0390941690830152810191909152606001604051602081830303815290604052805190602001205f1c6121489190614783565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f81518110613ea057613ea0614c8f565b602090810291909101015292915050565b5f80613ebd8385614708565b90505f613edd8280613ed8670de0b6b3a76400006002614708565b613fa0565b90505f613ef88284613ed8670de0b6b3a76400006003614708565b905080613f058385614783565b613deb9190614783565b5f6121488383670de0b6b3a7640000613fa0565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b03831115613f785760405162461bcd60e51b8152600401610c319190614de3565b5090919050565b5f81613f8c600182614755565b613f968587614708565b6131a59190614783565b5f816131a58486614708565b5f614000826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661411e9092919063ffffffff16565b905080515f14806140205750808060200190518101906140209190614768565b610bce5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610c31565b604051636eb1769f60e11b81523060048201526001600160a01b03848116602483015282919084169063dd62ed3e90604401602060405180830381865afa1580156140cc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140f0919061473e565b1015610bce5761410a6001600160a01b038316845f61412c565b610bce6001600160a01b038316848361412c565b6060611b9684845f856141ba565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261417d8482614291565b6131e0576040516001600160a01b03841660248201525f60448201526141b090859063095ea7b360e01b90606401613b0c565b6131e08482613fac565b60608247101561421b5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610c31565b5f80866001600160a01b031685876040516142369190614df5565b5f6040518083038185875af1925050503d805f8114614270576040519150601f19603f3d011682016040523d82523d5f602084013e614275565b606091505b509150915061428687838387614332565b979650505050505050565b5f805f846001600160a01b0316846040516142ac9190614df5565b5f604051808303815f865af19150503d805f81146142e5576040519150601f19603f3d011682016040523d82523d5f602084013e6142ea565b606091505b50915091508180156143145750805115806143145750808060200190518101906143149190614768565b801561432957506001600160a01b0385163b15155b95945050505050565b606083156143a05782515f03614399576001600160a01b0385163b6143995760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610c31565b5081611b96565b611b9683838151156143b55781518083602001fd5b8060405162461bcd60e51b8152600401610c319190614de3565b6001600160a01b0381168114610a70575f80fd5b5f602082840312156143f3575f80fd5b8135611275816143cf565b5f6020828403121561440e575f80fd5b5035919050565b8015158114610a70575f80fd5b5f60208284031215614432575f80fd5b813561127581614415565b5f805f6060848603121561444f575f80fd5b833561445a816143cf565b9250602084013561446a816143cf565b9150604084013562ffffff81168114614481575f80fd5b809150509250925092565b5f805f6040848603121561449e575f80fd5b8335925060208401356001600160401b03808211156144bb575f80fd5b818601915086601f8301126144ce575f80fd5b8135818111156144dc575f80fd5b8760208285010111156144ed575f80fd5b6020830194508093505050509250925092565b5f5b8381101561451a578181015183820152602001614502565b50505f910152565b5f8151808452614539816020860160208601614500565b601f01601f19169290920160200192915050565b8215158152604060208201525f611b966040830184614522565b5f8060408385031215614578575f80fd5b8235614583816143cf565b9150602083013561459381614415565b809150509250929050565b5f8083601f8401126145ae575f80fd5b5081356001600160401b038111156145c4575f80fd5b6020830191508360208260051b85010111156145de575f80fd5b9250929050565b5f805f805f805f806080898b0312156145fc575f80fd5b88356001600160401b0380821115614612575f80fd5b61461e8c838d0161459e565b909a50985060208b0135915080821115614636575f80fd5b6146428c838d0161459e565b909850965060408b013591508082111561465a575f80fd5b6146668c838d0161459e565b909650945060608b013591508082111561467e575f80fd5b5061468b8b828c0161459e565b999c989b5096995094979396929594505050565b5f80604083850312156146b0575f80fd5b82356146bb816143cf565b91506020830135614593816143cf565b5f805f606084860312156146dd575f80fd5b505081359360208301359350604090920135919050565b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141761214b5761214b6146f4565b5f8261473957634e487b7160e01b5f52601260045260245ffd5b500490565b5f6020828403121561474e575f80fd5b5051919050565b8181038181111561214b5761214b6146f4565b5f60208284031215614778575f80fd5b815161127581614415565b8082018082111561214b5761214b6146f4565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b03811182821017156147d2576147d2614796565b604052919050565b80516001600160801b0381168114611d98575f80fd5b5f60608284031215614800575f80fd5b604051606081018181106001600160401b038211171561482257614822614796565b60405282518152614835602084016147da565b6020820152614846604084016147da565b60408201529392505050565b8183525f60208085019450825f5b8581101561488e578135614873816143cf565b6001600160a01b031687529582019590820190600101614860565b509495945050505050565b8183525f6001600160fb1b038311156148b0575f80fd5b8260051b80836020870137939093016020019392505050565b608081525f6148dc608083018a8c614852565b6020838203818501526148f0828a8c614852565b9150838203604085015261490582888a614899565b84810360608601528581529150808201600586811b84018301885f5b8981101561498f57868303601f190185528135368c9003601e19018112614946575f80fd5b8b0186810190356001600160401b03811115614960575f80fd5b80861b3603821315614970575f80fd5b61497b858284614899565b968801969450505090850190600101614921565b50909f9e505050505050505050505050505050565b5f604082840312156149b4575f80fd5b604051604081018181106001600160401b03821117156149d6576149d6614796565b6040528251600281106149e7575f80fd5b81526020928301519281019290925250919050565b634e487b7160e01b5f52602160045260245ffd5b80546001600160a01b039081168352600182015481166020840152600282015481166040840152600382015416606083015260040154608090910152565b6101008101614a5d8287614a10565b60a08201949094526001600160a01b0392831660c0820152911660e090910152919050565b8151604082019060028110614aa557634e487b7160e01b5f52602160045260245ffd5b808352506020830151602083015292915050565b5f610120614ac78388614a10565b60a08301959095525060c08101929092526001600160a01b031660e082015261010081018290525f9181019190915261014001919050565b5f8060408385031215614b10575f80fd5b505080516020909101519092909150565b5f60208284031215614b31575f80fd5b8151611275816143cf565b6101208101614b4b8288614a10565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b5f610100614b868387614a10565b60a0830194909452506001600160a01b039190911660c082015260e081018290525f9181019190915261012001919050565b602080825282518282018190525f9190848201906040850190845b81811015614bef57835183529284019291840191600101614bd3565b50909695505050505050565b5f6020808385031215614c0c575f80fd5b82516001600160401b0380821115614c22575f80fd5b818501915085601f830112614c35575f80fd5b815181811115614c4757614c47614796565b8060051b9150614c588483016147aa565b8181529183018401918481019088841115614c71575f80fd5b938501935b8385101561105657845182529385019390850190614c76565b634e487b7160e01b5f52603260045260245ffd5b5f60c08284031215614cb3575f80fd5b60405160c081018181106001600160401b0382111715614cd557614cd5614796565b604052614ce1836147da565b8152614cef602084016147da565b6020820152614d00604084016147da565b6040820152614d11606084016147da565b6060820152614d22608084016147da565b6080820152614d3360a084016147da565b60a08201529392505050565b6001600160801b03818116838216019080821115614d5f57614d5f6146f4565b5092915050565b60018060a01b0384168152826020820152606060408201525f6143296060830184614522565b602081525f825160a06020840152614da760c0840182614522565b905060018060a01b0360208501511660408401526040840151606084015260608401516080840152608084015160a08401528091505092915050565b602081525f6121486020830184614522565b5f8251614e06818460208701614500565b919091019291505056fea2646970667358221220c39daddee3af7726ef9e98dda1cb16be488992fe33f2131303c1e00c86949e4f64736f6c63430008170033000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6200000000000000000000000000000000000000000000000000000000000000a00000000000000000000000007fb4d0f51544f24f385a421db6e7d4fc71ad8e5c000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db00000000000000000000000000000000000000000000000000000000000000207773744554482f57455448204b6174616e61204d6f7270686f204c6f6f706572

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106103d9575f3560e01c8063797bf34311610208578063cfaec0da11610123578063ecf70858116100b6578063f887ea4011610085578063f887ea40146108c5578063fc7f71b6146108d8578063fd9f5f75146108eb578063fde813a8146108fe578063ff831b0514610911576103d9565b8063ecf708581461085e578063efbb5cb014610867578063f0fa55a91461086f578063f3ce280a14610882576103d9565b8063d6968601116100f2578063d696860114610814578063d8fbc83314610827578063e86211491461084e578063ea9c840714610856576103d9565b8063cfaec0da146107bb578063d19a3bb8146107ce578063d472a43b146107e9578063d63a8e11146107f2576103d9565b80639b90fb161161019b578063b6a165061161016a578063b6a1650614610784578063b8c6f5791461078d578063bdc8144b146107a0578063c31443bb146107b3576103d9565b80639b90fb16146107245780639d7fb70c14610737578063ac00ff261461074a578063b2016bd41461075d576103d9565b806384d78a38116101d757806384d78a38146106e25780638ca6dd4d146106f6578063950b3d73146106fe57806398cdabc914610711576103d9565b8063797bf343146106ad5780637baf6f77146106b55780637d969932146106bd5780637d9f6db5146106cf576103d9565b806349317f1d116102f85780636687500e1161028b5780636ed71ede1161025a5780636ed71ede1461065757806371ee95c01461067e57806372b10dd514610691578063757a291f1461069a576103d9565b80636687500e146106035780636718835f1461060b5780636be36a1d146106275780636c7a0c911461062f576103d9565b8063503160d9116102c7578063503160d9146105cc578063580e0d81146105df5780635d265d3f146105f25780635ef76292146105fa576103d9565b806349317f1d146105895780634a5d0943146105915780634aca9482146105a15780635001f3b5146105b4576103d9565b80632e3ecf2c116103705780633d6cb5751161033f5780633d6cb575146105255780633e032a3b146105385780634697f05d1461056357806346aa2f1214610576576103d9565b80632e3ecf2c146104d657806331f57072146104e95780633259356e146104fc578063392f7a701461051d576103d9565b806318144367116103ac578063181443671461047457806320aa49ae1461047d578063219461ed146104905780632b0015e6146104c3576103d9565b806304bd46291461040e5780630870e1801461043557806309218e91146104485780630ea44a561461046b575b73d377919fa87120584b21279a491f82d5265a139c365f80375f80365f845af43d5f803e808015610408573d5ff35b3d5ffd5b005b61042261041c3660046143e3565b505f1990565b6040519081526020015b60405180910390f35b61040c6104433660046143fe565b610924565b61045061099f565b6040805193845260208401929092529082015260600161042c565b61042260015481565b61042260095481565b61040c61048b366004614422565b6109f4565b6104ab733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae81565b6040516001600160a01b03909116815260200161042c565b61040c6104d13660046143fe565b610a73565b61040c6104e436600461443d565b610b03565b61040c6104f736600461448c565b610bd3565b61050f61050a3660046143e3565b610cbe565b60405161042c92919061454d565b610422610df3565b61040c6105333660046143fe565b610e6b565b60045461054b906001600160401b031681565b6040516001600160401b03909116815260200161042c565b61040c610571366004614567565b610e7c565b6104226105843660046143e3565b610f19565b610422611062565b5f54610100900461ffff16610422565b6104226105af3660046143e3565b611081565b6010546104ab9061010090046001600160a01b031681565b61040c6105da3660046143fe565b61127c565b61040c6105ed3660046143fe565b611284565b61050f61130b565b61042260035481565b610422611348565b5f546106179060ff1681565b604051901515815260200161042c565b600f54610422565b61064261063d3660046143fe565b61140b565b6040805192835260208301919091520161042c565b6104227f22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db81565b61040c61068c3660046145e5565b611455565b61042260065481565b61040c6106a83660046143fe565b6114d1565b610422611558565b6104226115e1565b5f546301000000900461ffff16610422565b600a546104ab906001600160a01b031681565b600a5461061790600160a01b900460ff1681565b61040c61162f565b61040c61070c3660046143fe565b61172c565b61040c61071f3660046143fe565b6117a8565b61040c6107323660046143fe565b61182f565b61040c6107453660046143fe565b6118aa565b61040c610758366004614422565b6118bb565b6104ab7f0000000000000000000000007fb4d0f51544f24f385a421db6e7d4fc71ad8e5c81565b61042260055481565b61040c61079b3660046143e3565b611941565b61040c6107ae3660046143fe565b6119bd565b610422611a38565b61040c6107c93660046143fe565b611a94565b6104ab73d377919fa87120584b21279a491f82d5265a139c81565b61042260025481565b6106176108003660046143e3565b60086020525f908152604090205460ff1681565b61040c6108223660046143fe565b611b10565b6104ab7f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc81565b610422611b8c565b610422611b9e565b61042260075481565b610422611c10565b61040c61087d3660046143fe565b611c45565b6108b161089036600461469f565b601260209081525f928352604080842090915290825290205462ffffff1681565b60405162ffffff909116815260200161042c565b6011546104ab906001600160a01b031681565b6104226108e63660046143e3565b611d17565b61040c6108f93660046143fe565b611d9d565b61040c61090c3660046143fe565b611e24565b61040c61091f3660046146cb565b611e35565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015610981575f80fd5b505afa158015610993573d5f803e3d5ffd5b50505060069190915550565b5f805f806109ab611348565b90506109b6816120b5565b93506109c0610df3565b92505f84116109cf575f6109ec565b836109e2670de0b6b3a764000085614708565b6109ec919061471f565b915050909192565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015610a51575f80fd5b505afa158015610a63573d5f803e3d5ffd5b50505050610a70816120f0565b50565b6040516320b8029160e21b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906382e00a44906024015f6040518083038186803b158015610ad0575f80fd5b505afa158015610ae2573d5f803e3d5ffd5b50505050610aff610afa82610af56115e1565b612138565b612151565b5050565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015610b60575f80fd5b505afa158015610b72573d5f803e3d5ffd5b5050506001600160a01b038085165f8181526012602081815260408084209589168452948152848320805462ffffff1990811662ffffff8a16908117909255928252858420948452939052929020805490921617905550505050565b505050565b336001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc1614610c3a5760405162461bcd60e51b8152602060048201526007602482015266216d6f7270686f60c81b60448201526064015b60405180910390fd5b60105460ff16610c7f5760405162461bcd60e51b815260206004820152601060248201526f666c6173686c6f616e2061637469766560801b6044820152606401610c31565b610bce8383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506121a992505050565b600a545f906060906001600160a01b031680610d06575f6040518060400160405280600e81526020016d139bc8185d58dd1a5bdb881cd95d60921b8152509250925050915091565b600a54600160a01b900460ff16610d4c575f60405180604001604052806011815260200170105d58dd1a5bdb9cc8191a5cd8589b1959607a1b8152509250925050915091565b5f610d5685611081565b90508015801590610d6957506009548110155b15610dbb575050604080516001600160a01b0394909416602480860191909152815180860390910181526044909401905250506020810180516001600160e01b0316637e3fb8db60e11b179052600191565b5f604051806040016040528060138152602001726e6f7420656e6f756768206b69636b61626c6560681b815250935093505050915091565b6040805160a081018252600b546001600160a01b039081168252600c5481166020830152600d54811692820192909252600e5482166060820152600f5460808201525f91610e66917f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc9091169030612243565b905090565b610e73612289565b610a70816122c0565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015610ed9575f80fd5b505afa158015610eeb573d5f803e3d5ffd5b505050506001600160a01b03919091165f908152600860205260409020805460ff1916911515919091179055565b6001600160a01b0381165f9081526008602052604081205460ff16610f3f57505f919050565b5f7f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f9c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fc0919061473e565b90505f8160075411610fd2575f610fe0565b81600754610fe09190614755565b90505f610feb6122c9565b9050805f03610ffe57505f949350505050565b5f195f611009612311565b9050805f0361101e57505f9695505050505050565b5f8361103281670de0b6b3a7640000614755565b61103c9084614708565b611046919061471f565b905061105685610af58584612138565b98975050505050505050565b5f61106b612289565b6110736123a4565b905061107e816123c9565b90565b600a545f90600160a01b900460ff1661109b57505f919050565b600a546001600160a01b0316806110b457505f92915050565b604051639f8a13d760e01b81526001600160a01b038481166004830152821690639f8a13d790602401602060405180830381865afa1580156110f8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061111c9190614768565b801561119057506040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa15801561116a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118e919061473e565b115b1561119d57505f92915050565b6040516370a0823160e01b81526001600160a01b0382811660048301528416906370a0823190602401602060405180830381865afa1580156111e1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611205919061473e565b6040516370a0823160e01b81523060048201526001600160a01b038516906370a0823190602401602060405180830381865afa158015611247573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061126b919061473e565b6112759190614783565b9392505050565b610a70612289565b6040516320b8029160e21b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906382e00a44906024015f6040518083038186803b1580156112e1575f80fd5b505afa1580156112f3573d5f803e3d5ffd5b50505050610a7061130682610af5611348565b61250c565b5f6060611316612599565b6040805160048152602481019091526020810180516001600160e01b031663440368a360e01b17905290939092509050565b6040516349e2903160e11b81527f22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db60048201523060248201525f9081906001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906393c5206290604401606060405180830381865afa1580156113d4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113f891906147f0565b604001516001600160801b031692915050565b5f805f670de0b6b3a7640000600154856114259190614708565b61142f919061471f565b90505f84821161143f575f611449565b6114498583614755565b91959194509092505050565b6040516301c7ba5760e61b8152733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae906371ee95c09061149a908b908b908b908b908b908b908b908b906004016148c9565b5f604051808303815f87803b1580156114b1575f80fd5b505af11580156114c3573d5f803e3d5ffd5b505050505050505050505050565b6040516320b8029160e21b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906382e00a44906024015f6040518083038186803b15801561152e575f80fd5b505afa158015611540573d5f803e3d5ffd5b50505050610aff61155382610af5611558565b6126de565b6040516370a0823160e01b81523060048201525f907f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab626001600160a01b0316906370a08231906024015b602060405180830381865afa1580156115bd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e66919061473e565b6040516370a0823160e01b81523060048201525f907f0000000000000000000000007fb4d0f51544f24f385a421db6e7d4fc71ad8e5c6001600160a01b0316906370a08231906024016115a2565b6040516320b8029160e21b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906382e00a44906024015f6040518083038186803b15801561168c575f80fd5b505afa15801561169e573d5f803e3d5ffd5b5050505061172a7f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611701573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611725919061473e565b61273c565b565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611789575f80fd5b505afa15801561179b573d5f803e3d5ffd5b50505050610a708161289b565b6040516320b8029160e21b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906382e00a44906024015f6040518083038186803b158015611805575f80fd5b505afa158015611817573d5f803e3d5ffd5b50505050610a7061182a82610af5611558565b612934565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b15801561188c575f80fd5b505afa15801561189e573d5f803e3d5ffd5b50505060059190915550565b6118b2612289565b610a7081612ab6565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611918575f80fd5b505afa15801561192a573d5f803e3d5ffd5b50505f805460ff1916931515939093179092555050565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b15801561199e575f80fd5b505afa1580156119b0573d5f803e3d5ffd5b50505050610a7081612abf565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611a1a575f80fd5b505afa158015611a2c573d5f803e3d5ffd5b50505060079190915550565b5f805f611a4361099f565b5091509150815f03611a57575f9250505090565b818110611a67575f199250505090565b611a718183614755565b611a83670de0b6b3a764000084614708565b611a8d919061471f565b9250505090565b6040516320b8029160e21b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906382e00a44906024015f6040518083038186803b158015611af1575f80fd5b505afa158015611b03573d5f803e3d5ffd5b50505050610a7081612c18565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611b6d575f80fd5b505afa158015611b7f573d5f803e3d5ffd5b50505050610a7081612cb6565b5f80611b9661099f565b949350505050565b6040516370a0823160e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc811660048301525f917f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62909116906370a08231906024016115a2565b5f611c19610df3565b611c29611c24611348565b6120b5565b611c31611558565b611c3b9190614783565b610e669190614755565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611ca2575f80fd5b505afa158015611cb4573d5f803e3d5ffd5b505050506127108110611cf45760405162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b6044820152606401610c31565b6004805467ffffffffffffffff19166001600160401b0392909216919091179055565b60405163d43fdcf760e01b81523360048201525f907f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b03169063d43fdcf7906024015f6040518083038186803b158015611d76575f80fd5b505afa158015611d88573d5f803e3d5ffd5b50505050611d9582612d16565b90505b919050565b6040516320b8029160e21b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906382e00a44906024015f6040518083038186803b158015611dfa575f80fd5b505afa158015611e0c573d5f803e3d5ffd5b50505050610a70611e1f82610af56115e1565b612f97565b611e2c612289565b610a7081612ff2565b6040516348e4a64960e01b81523360048201527f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b0316906348e4a649906024015f6040518083038186803b158015611e92575f80fd5b505afa158015611ea4573d5f803e3d5ffd5b50505050825f03611f02578115611efd5760405162461bcd60e51b815260206004820152601f60248201527f627566666572206d7573742062652030206966207461726765742069732030006044820152606401610c31565b611fd5565b670de0b6b3a7640000831015611f4a5760405162461bcd60e51b815260206004820152600d60248201526c0d8caeccae4c2ceca40784062f609b1b6044820152606401610c31565b662386f26fc10000821015611f945760405162461bcd60e51b815260206004820152601060248201526f189d5999995c881d1bdbc81cdb585b1b60821b6044820152606401610c31565b818311611fd55760405162461bcd60e51b815260206004820152600f60248201526e3a30b933b2ba101e10313ab33332b960891b6044820152606401610c31565b611fdf8284614783565b81101561202e5760405162461bcd60e51b815260206004820152601e60248201527f6d6178206c65766572616765203c20746172676574202b2062756666657200006044820152606401610c31565b5f81612042670de0b6b3a764000080614708565b61204c919061471f565b61205e90670de0b6b3a7640000614755565b9050612069600f5490565b81106120a65760405162461bcd60e51b815260206004820152600c60248201526b32bc31b2b2b2399026262a2b60a11b6044820152606401610c31565b50600192909255600255600355565b5f815f036120c457505f919050565b6ec097ce7bc90715b34b9f10000000006120dc6130b0565b6120e69084614708565b611d95919061471f565b600a805460ff60a01b1916600160a01b831515908102919091179091556040517feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a250565b5f8183106121465781612148565b825b90505b92915050565b5f8061215c836130f7565b9050612168835f613152565b81101561214b5760405162461bcd60e51b815260206004820152600f60248201526e1cdb1a5c1c1859d94e88185cdcd95d608a1b6044820152606401610c31565b5f818060200190518101906121be91906149a4565b90505f815160018111156121d4576121d46149fc565b036121e357610bce83826131af565b6001815160018111156121f8576121f86149fc565b0361220757610bce83826131e6565b60405162461bcd60e51b815260206004820152601160248201527034b73b30b634b21037b832b930ba34b7b760791b6044820152606401610c31565b5f806122508460a0902090565b90505f6122676001600160a01b038716838661321a565b90505f8061227588886132cc565b9094509250611056915084905083836135c2565b33301461172a5760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b6044820152606401610c31565b610a708161273c565b5f670de0b6b3a7640000600154116122e057505f90565b6001546122f5670de0b6b3a764000080614708565b6122ff919061471f565b610e6690670de0b6b3a7640000614755565b6040805160a081018252600b546001600160a01b039081168252600c5481166020830152600d54811692820192909252600e5482166060820152600f5460808201525f9182918291612387917f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc909116906132cc565b50925050915080821161239a575f611a8d565b611a8d8183614755565b5f6123c16123bc6123b3611558565b610af530610f19565b6135e6565b610e66611c10565b5f5460ff166123e157505f805460ff19166001179055565b5f7f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa15801561243e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612462919061473e565b9050808211156124d5575f546127109061248590610100900461ffff1683614708565b61248f919061471f565b6124998284614755565b1115610aff5760405162461bcd60e51b815260206004820152600b60248201526a6865616c7468436865636b60a81b6044820152606401610c31565b81811115610aff575f54612710906124f8906301000000900461ffff1683614708565b612502919061471f565b6124998383614755565b805f036125165750565b604051638720316d60e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc1690638720316d9061256990600b90859030908190600401614a4e565b5f604051808303815f87803b158015612580575f80fd5b505af1158015612592573d5f803e3d5ffd5b5050505050565b5f6125a26137d8565b156125ad5750600190565b7f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612609573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061262d919061473e565b5f0361263857505f90565b5f612641611a38565b905060035481111561265557600191505090565b6001545f819003612675575f82118015611a8d5750600554481115611a8d565b600654612680611558565b111561269157600554481115611a8d565b5f600254826126a09190614783565b90505f600254836126b19190614755565b9050808410806126c057508184115b156126d45760055448111594505050505090565b5f94505050505090565b5f806126e98361398a565b90506126f6836001613152565b81101561214b5760405162461bcd60e51b81526020600482015260146024820152731cdb1a5c1c1859d94e8818dbdb1b185d195c985b60621b6044820152606401610c31565b5f8061274661099f565b5091509150805f0361277b575f61276761275f856139e5565b610af5611348565b90506127728161250c565b61259281612151565b5f6127868284614755565b90505f848211612796575f6127a0565b6127a08583614755565b90505f6127ac8261140b565b9150505f8185116127bd575f6127f5565b600454612710906127d7906001600160401b031682614783565b6127e18488614755565b6127eb9190614708565b6127f5919061471f565b90505f61280a6128058984614783565b6139e5565b90508115801561281957508015155b1561283b576128278161250c565b61283081612151565b505050505050505050565b60408051808201825260018152602080820184905291515f9261285f929101614a82565b60405160208183030381529060405290506128307f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab628483613a23565b5f81116128d95760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401610c31565b61ffff8111156129175760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401610c31565b5f805461ffff9092166101000262ffff0019909216919091179055565b805f0361293e5750565b6040805160a081018252600b546001600160a01b039081168252600c5481166020830152600d54811692820192909252600e549091166060820152600f5460808201525f9081906129b0907f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc906132cc565b9350935050505f612a196129c5858585613abc565b610af56001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc167f22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db3061321a565b6040516320b76e8160e01b81529091506001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906320b76e8190612a6f90600b905f9086903090600401614ab9565b60408051808303815f875af1158015612a8a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612aae9190614aff565b505050505050565b610a70816135e6565b6001600160a01b03811615612bcf57306001600160a01b0316816001600160a01b031663f7260d3e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612b14573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b389190614b21565b6001600160a01b031614612b7f5760405162461bcd60e51b815260206004820152600e60248201526d3bb937b733903932b1b2b4bb32b960911b6044820152606401610c31565b600a54600160a01b900460ff16612bcf57600a805460ff60a01b1916600160a01b1790556040516001907feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a25b600a80546001600160a01b0319166001600160a01b0383169081179091556040517f4da9b3b7ca08b559bc11eb42bb6961e0813372ed0b55f0e9b68b76cf0207fce8905f90a250565b805f03612c225750565b6040516350d8cd4b60e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906350d8cd4b90612c7790600b9085905f9030908190600401614b3c565b60408051808303815f875af1158015612c92573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bce9190614aff565b6127108110612cf55760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401610c31565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b600a545f90600160a01b900460ff16612d675760405162461bcd60e51b815260206004820152601360248201527275736541756374696f6e2069732066616c736560681b6044820152606401610c31565b600a54604051639f8a13d760e01b81526001600160a01b038481166004830152909116908190639f8a13d790602401602060405180830381865afa158015612db1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612dd59190614768565b15612eaa576040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa158015612e21573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e45919061473e565b1115612e5357505f92915050565b604051636a256b2960e01b81526001600160a01b038481166004830152821690636a256b29906024015f604051808303815f87803b158015612e93575f80fd5b505af1158015612ea5573d5f803e3d5ffd5b505050505b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa158015612eee573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f12919061473e565b90508015612f2e57612f2e6001600160a01b0385168383613ae0565b6040516396c5517560e01b81526001600160a01b0385811660048301528316906396c55175906024016020604051808303815f875af1158015612f73573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b96919061473e565b805f03612fa15750565b60405163238d657960e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc169063238d65799061256990600b9085903090600401614b78565b5f612ffb610df3565b9050801561308a57610aff611725837f000000000000000000000000619338d0dff9c86d4c9fa950ae5b4abcd90daf7a6001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015613066573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610af5919061473e565b8115610aff5761309c82610af5611348565b91506130a78261250c565b610bce82612151565b600d546040805163501ad8ff60e11b815290515f926001600160a01b03169163a035b1fe9160048083019260209291908290030181865afa1580156115bd573d5f803e3d5ffd5b5f815f0361310657505f919050565b611d957f0000000000000000000000007fb4d0f51544f24f385a421db6e7d4fc71ad8e5c7f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62845f613b43565b5f825f0361316157505f61214b565b5f8261317557613170846120b5565b61317e565b61317e846139e5565b6004549091506127109061319b906001600160401b031682614755565b6131a59083614708565b611b96919061471f565b5f8282602001516131c09190614783565b90505f6131cc826126de565b90506131d781612f97565b6131e084612c18565b50505050565b6131f561182a83610af5610df3565b5f6132068260200151610af5611348565b90506132118161250c565b6131e081612151565b5f8061322e6132298585613df5565b613e68565b604051637784c68560e01b81529091506001600160a01b03861690637784c6859061325d908490600401614bb8565b5f60405180830381865afa158015613277573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261329e9190810190614bfb565b5f815181106132af576132af614c8f565b60200260200101515f1c6001600160801b03169150509392505050565b5f805f805f6132dc8660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa158015613324573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133489190614ca3565b90505f81608001516001600160801b0316426133649190614755565b90508015801590613381575060408201516001600160801b031615155b8015613399575060608801516001600160a01b031615155b1561358e576060888101805160408051638c00bf6b60e01b81528c516001600160a01b0390811660048301526020808f015182166024840152838f0151821660448401529451811660648301526080808f0151608484015288516001600160801b0390811660a485015295890151861660c484015292880151851660e483015294870151841661010482015290860151831661012482015260a08601519092166101448301525f921690638c00bf6b9061016401602060405180830381865afa158015613468573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061348c919061473e565b90505f6134b061349c8385613eb1565b60408601516001600160801b031690613f0f565b90506134bb81613f23565b846040018181516134cc9190614d3f565b6001600160801b03169052506134e181613f23565b845185906134f0908390614d3f565b6001600160801b0390811690915260a08601511615905061358b575f61352c8560a001516001600160801b031683613f0f90919063ffffffff16565b90505f61356082875f01516001600160801b031661354a9190614755565b60208801518491906001600160801b0316613abc565b905061356b81613f23565b8660200181815161357c9190614d3f565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f611b966135d1600185614783565b6135de620f424085614783565b869190613f7f565b5f806135f061099f565b5090925090505f836136028385614755565b61360c9190614783565b90505f6136188261140b565b915050828111156136af575f61362e8483614755565b9050600654811161364857612aae61182a87610af5610df3565b6040805180820182525f80825260208083018a90529251909261366c929101614a82565b60405160208183030381529060405290506136a87f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab628383613a23565b5050612592565b808311156137c9575f6136c28285614755565b90508086106136fc576136d481612934565b5f6136df8288614755565b905080156136f3576136f3611e1f826126de565b50505050505050565b61370586612934565b6004545f9061271090613721906001600160401b031682614783565b61372e6128058a86614755565b6137389190614708565b613742919061471f565b90505f6040518060400160405280600180811115613762576137626149fc565b81526020018381525060405160200161377b9190614a82565b60408051601f1981840301815291905290506137c17f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab626137bb8a86614755565b83613a23565b505050612592565b61259261182a86610af5610df3565b6040516349e2903160e11b81527f22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db60048201523060248201525f9081906001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906393c5206290604401606060405180830381865afa158015613864573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061388891906147f0565b905080602001516001600160801b03165f036138a5575f91505090565b5f6ec097ce7bc90715b34b9f1000000000600b6002015f9054906101000a90046001600160a01b03166001600160a01b031663a035b1fe6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613909573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061392d919061473e565b83604001516001600160801b03166139459190614708565b61394f919061471f565b90505f670de0b6b3a7640000600b600401548361396c9190614708565b613976919061471f565b905080613981610df3565b11935050505090565b5f815f0361399957505f919050565b611d957f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab627f0000000000000000000000007fb4d0f51544f24f385a421db6e7d4fc71ad8e5c845f613b43565b5f815f036139f457505f919050565b5f6139fd6130b0565b905080613a196ec097ce7bc90715b34b9f100000000085614708565b611275919061471f565b6010805460ff1916600117905560405163701195a160e11b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc169063e0232b4290613a8090869086908690600401614d66565b5f604051808303815f87803b158015613a97575f80fd5b505af1158015613aa9573d5f803e3d5ffd5b50506010805460ff191690555050505050565b5f611b96613acd620f424084614783565b613ad8600186614783565b869190613fa0565b6040516001600160a01b038316602482015260448101829052610bce90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613fac565b5f8215801590613b5557506009548310155b15611b9657601154613b71906001600160a01b0316868561407f565b6010546001600160a01b03868116610100909204161480613ba457506010546001600160a01b0385811661010090920416145b15613cba5760408051610100810182526001600160a01b0387811680835287821660208085018281525f938452601282528684209284529190528482205462ffffff9081168587019081523060608701908152426080880190815260a088018c815260c089018c815260e08a019788526011549a5163414bf38960e01b81528a518a16600482015296518916602488015293519094166044860152905186166064850152516084840152905160a48301525160c48201529051821660e48201529192169063414bf38990610104016020604051808303815f875af1158015613c8e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613cb2919061473e565b915050611b96565b6001600160a01b038581165f90815260126020818152604080842060105461010090048087168652908352818520549383528185208a8716865283529381902054815160608c811b6bffffffffffffffffffffffff199081169583019590955260e895861b6001600160e81b0319908116603484015296811b851660378301529190941b909416604b8401529288901b16604e8201528151604281830301815260115461010283018452606283018281523060828501524260a285015260c2840189905260e2909301879052925163c04b8d5960e01b81529093929092169163c04b8d5991613dab91600401614d8c565b6020604051808303815f875af1158015613dc7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613deb919061473e565b9695505050505050565b5f600182846002604051602001613e16929190918252602082015260400190565b60408051601f1981840301815282825280516020918201206001600160a01b0390941690830152810191909152606001604051602081830303815290604052805190602001205f1c6121489190614783565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f81518110613ea057613ea0614c8f565b602090810291909101015292915050565b5f80613ebd8385614708565b90505f613edd8280613ed8670de0b6b3a76400006002614708565b613fa0565b90505f613ef88284613ed8670de0b6b3a76400006003614708565b905080613f058385614783565b613deb9190614783565b5f6121488383670de0b6b3a7640000613fa0565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b03831115613f785760405162461bcd60e51b8152600401610c319190614de3565b5090919050565b5f81613f8c600182614755565b613f968587614708565b6131a59190614783565b5f816131a58486614708565b5f614000826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661411e9092919063ffffffff16565b905080515f14806140205750808060200190518101906140209190614768565b610bce5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610c31565b604051636eb1769f60e11b81523060048201526001600160a01b03848116602483015282919084169063dd62ed3e90604401602060405180830381865afa1580156140cc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140f0919061473e565b1015610bce5761410a6001600160a01b038316845f61412c565b610bce6001600160a01b038316848361412c565b6060611b9684845f856141ba565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261417d8482614291565b6131e0576040516001600160a01b03841660248201525f60448201526141b090859063095ea7b360e01b90606401613b0c565b6131e08482613fac565b60608247101561421b5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610c31565b5f80866001600160a01b031685876040516142369190614df5565b5f6040518083038185875af1925050503d805f8114614270576040519150601f19603f3d011682016040523d82523d5f602084013e614275565b606091505b509150915061428687838387614332565b979650505050505050565b5f805f846001600160a01b0316846040516142ac9190614df5565b5f604051808303815f865af19150503d805f81146142e5576040519150601f19603f3d011682016040523d82523d5f602084013e6142ea565b606091505b50915091508180156143145750805115806143145750808060200190518101906143149190614768565b801561432957506001600160a01b0385163b15155b95945050505050565b606083156143a05782515f03614399576001600160a01b0385163b6143995760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610c31565b5081611b96565b611b9683838151156143b55781518083602001fd5b8060405162461bcd60e51b8152600401610c319190614de3565b6001600160a01b0381168114610a70575f80fd5b5f602082840312156143f3575f80fd5b8135611275816143cf565b5f6020828403121561440e575f80fd5b5035919050565b8015158114610a70575f80fd5b5f60208284031215614432575f80fd5b813561127581614415565b5f805f6060848603121561444f575f80fd5b833561445a816143cf565b9250602084013561446a816143cf565b9150604084013562ffffff81168114614481575f80fd5b809150509250925092565b5f805f6040848603121561449e575f80fd5b8335925060208401356001600160401b03808211156144bb575f80fd5b818601915086601f8301126144ce575f80fd5b8135818111156144dc575f80fd5b8760208285010111156144ed575f80fd5b6020830194508093505050509250925092565b5f5b8381101561451a578181015183820152602001614502565b50505f910152565b5f8151808452614539816020860160208601614500565b601f01601f19169290920160200192915050565b8215158152604060208201525f611b966040830184614522565b5f8060408385031215614578575f80fd5b8235614583816143cf565b9150602083013561459381614415565b809150509250929050565b5f8083601f8401126145ae575f80fd5b5081356001600160401b038111156145c4575f80fd5b6020830191508360208260051b85010111156145de575f80fd5b9250929050565b5f805f805f805f806080898b0312156145fc575f80fd5b88356001600160401b0380821115614612575f80fd5b61461e8c838d0161459e565b909a50985060208b0135915080821115614636575f80fd5b6146428c838d0161459e565b909850965060408b013591508082111561465a575f80fd5b6146668c838d0161459e565b909650945060608b013591508082111561467e575f80fd5b5061468b8b828c0161459e565b999c989b5096995094979396929594505050565b5f80604083850312156146b0575f80fd5b82356146bb816143cf565b91506020830135614593816143cf565b5f805f606084860312156146dd575f80fd5b505081359360208301359350604090920135919050565b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141761214b5761214b6146f4565b5f8261473957634e487b7160e01b5f52601260045260245ffd5b500490565b5f6020828403121561474e575f80fd5b5051919050565b8181038181111561214b5761214b6146f4565b5f60208284031215614778575f80fd5b815161127581614415565b8082018082111561214b5761214b6146f4565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b03811182821017156147d2576147d2614796565b604052919050565b80516001600160801b0381168114611d98575f80fd5b5f60608284031215614800575f80fd5b604051606081018181106001600160401b038211171561482257614822614796565b60405282518152614835602084016147da565b6020820152614846604084016147da565b60408201529392505050565b8183525f60208085019450825f5b8581101561488e578135614873816143cf565b6001600160a01b031687529582019590820190600101614860565b509495945050505050565b8183525f6001600160fb1b038311156148b0575f80fd5b8260051b80836020870137939093016020019392505050565b608081525f6148dc608083018a8c614852565b6020838203818501526148f0828a8c614852565b9150838203604085015261490582888a614899565b84810360608601528581529150808201600586811b84018301885f5b8981101561498f57868303601f190185528135368c9003601e19018112614946575f80fd5b8b0186810190356001600160401b03811115614960575f80fd5b80861b3603821315614970575f80fd5b61497b858284614899565b968801969450505090850190600101614921565b50909f9e505050505050505050505050505050565b5f604082840312156149b4575f80fd5b604051604081018181106001600160401b03821117156149d6576149d6614796565b6040528251600281106149e7575f80fd5b81526020928301519281019290925250919050565b634e487b7160e01b5f52602160045260245ffd5b80546001600160a01b039081168352600182015481166020840152600282015481166040840152600382015416606083015260040154608090910152565b6101008101614a5d8287614a10565b60a08201949094526001600160a01b0392831660c0820152911660e090910152919050565b8151604082019060028110614aa557634e487b7160e01b5f52602160045260245ffd5b808352506020830151602083015292915050565b5f610120614ac78388614a10565b60a08301959095525060c08101929092526001600160a01b031660e082015261010081018290525f9181019190915261014001919050565b5f8060408385031215614b10575f80fd5b505080516020909101519092909150565b5f60208284031215614b31575f80fd5b8151611275816143cf565b6101208101614b4b8288614a10565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b5f610100614b868387614a10565b60a0830194909452506001600160a01b039190911660c082015260e081018290525f9181019190915261012001919050565b602080825282518282018190525f9190848201906040850190845b81811015614bef57835183529284019291840191600101614bd3565b50909695505050505050565b5f6020808385031215614c0c575f80fd5b82516001600160401b0380821115614c22575f80fd5b818501915085601f830112614c35575f80fd5b815181811115614c4757614c47614796565b8060051b9150614c588483016147aa565b8181529183018401918481019088841115614c71575f80fd5b938501935b8385101561105657845182529385019390850190614c76565b634e487b7160e01b5f52603260045260245ffd5b5f60c08284031215614cb3575f80fd5b60405160c081018181106001600160401b0382111715614cd557614cd5614796565b604052614ce1836147da565b8152614cef602084016147da565b6020820152614d00604084016147da565b6040820152614d11606084016147da565b6060820152614d22608084016147da565b6080820152614d3360a084016147da565b60a08201529392505050565b6001600160801b03818116838216019080821115614d5f57614d5f6146f4565b5092915050565b60018060a01b0384168152826020820152606060408201525f6143296060830184614522565b602081525f825160a06020840152614da760c0840182614522565b905060018060a01b0360208501511660408401526040840151606084015260608401516080840152608084015160a08401528091505092915050565b602081525f6121486020830184614522565b5f8251614e06818460208701614500565b919091019291505056fea2646970667358221220c39daddee3af7726ef9e98dda1cb16be488992fe33f2131303c1e00c86949e4f64736f6c63430008170033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6200000000000000000000000000000000000000000000000000000000000000a00000000000000000000000007fb4d0f51544f24f385a421db6e7d4fc71ad8e5c000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db00000000000000000000000000000000000000000000000000000000000000207773744554482f57455448204b6174616e61204d6f7270686f204c6f6f706572

-----Decoded View---------------
Arg [0] : _asset (address): 0xEE7D8BCFb72bC1880D0Cf19822eB0A2e6577aB62
Arg [1] : _name (string): wstETH/WETH Katana Morpho Looper
Arg [2] : _collateralToken (address): 0x7Fb4D0f51544F24F385a421Db6e7D4fC71Ad8e5C
Arg [3] : _morpho (address): 0xD50F2DffFd62f94Ee4AEd9ca05C61d0753268aBc
Arg [4] : _marketId (bytes32): 0x22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db

-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62
Arg [1] : 00000000000000000000000000000000000000000000000000000000000000a0
Arg [2] : 0000000000000000000000007fb4d0f51544f24f385a421db6e7d4fc71ad8e5c
Arg [3] : 000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc
Arg [4] : 22f9f76056c10ee3496dea6fefeaf2f98198ef597eda6f480c148c6d3aaa70db
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000020
Arg [6] : 7773744554482f57455448204b6174616e61204d6f7270686f204c6f6f706572


Loading...
Loading
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.