ETH Price: $2,928.50 (+0.43%)

Contract

0xfF513347Aea1734324B9E7852c685221Cf899fA8

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Token Holdings

More Info

Private Name Tags

TokenTracker

Multichain Info

No addresses found
Transaction Hash
Block
From
To
Report194261092025-12-19 18:28:404 days ago1766168920IN
0xfF513347...1Cf899fA8
0 ETH0.000001870.00100026
Set Do Health Ch...194261052025-12-19 18:28:364 days ago1766168916IN
0xfF513347...1Cf899fA8
0 ETH0.000001380.00100026
Tend192665172025-12-17 22:08:486 days ago1766009328IN
0xfF513347...1Cf899fA8
0 ETH0.000001760.00100026
Set Allowed192648652025-12-17 21:41:166 days ago1766007676IN
0xfF513347...1Cf899fA8
0 ETH0.00000140.00100026
Set Allowed192643992025-12-17 21:33:306 days ago1766007210IN
0xfF513347...1Cf899fA8
0 ETH0.000001370.00100026
Tend192636842025-12-17 21:21:356 days ago1766006495IN
0xfF513347...1Cf899fA8
0 ETH0.00000180.00100026
Set Base192636792025-12-17 21:21:306 days ago1766006490IN
0xfF513347...1Cf899fA8
0 ETH0.000001380.00100026
Set Leverage Par...192635602025-12-17 21:19:316 days ago1766006371IN
0xfF513347...1Cf899fA8
0 ETH0.000001390.00100026
Deposit192635222025-12-17 21:18:536 days ago1766006333IN
0xfF513347...1Cf899fA8
0 ETH0.000001560.00100026
Set Allowed192635182025-12-17 21:18:496 days ago1766006329IN
0xfF513347...1Cf899fA8
0 ETH0.00000140.00100026
Set Allowed192634842025-12-17 21:18:156 days ago1766006295IN
0xfF513347...1Cf899fA8
0 ETH0.00000140.00100026

View more zero value Internal Transactions in Advanced View mode

Advanced mode:

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
VaultMorphoLooper

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 {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";

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

/**
 * @notice VaultMorphoLooper 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 VaultMorphoLooper is BaseMorphoLooper, UniswapV3Swapper {
    using SafeERC20 for ERC20;

    address public immutable vaultAsset;

    constructor(
        address _asset,
        string memory _name,
        address _collateralToken,
        address _morpho,
        Id _marketId,
        address _router
    ) BaseMorphoLooper(_asset, _name, _collateralToken, _morpho, _marketId) {
        vaultAsset = IERC4626(_collateralToken).asset();
        _setUniFees(address(asset), address(vaultAsset), 100);
        router = _router;

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

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

    function setBase(address _base) external onlyManagement {
        base = _base;
    }

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

    function _convertAssetToCollateral(
        uint256 amount
    ) internal override returns (uint256) {
        if (amount == 0) return 0;
        // Swap to underly asset then deposit into vault
        uint256 amountOut = _swapFrom(address(asset), address(vaultAsset), amount, 0);
        return IERC4626(collateralToken).deposit(amountOut, address(this));
    }

    function _convertCollateralToAsset(
        uint256 amount
    ) internal override returns (uint256) {
        if (amount == 0) return 0;
        // Redeem from vault then swap to asset
        uint256 amountOut = IERC4626(collateralToken).redeem(amount, address(this), address(this));
        return _swapFrom(address(vaultAsset), address(asset), amountOut, 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: 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: 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);

    Id public immutable marketId;

    IMorpho public immutable morpho;

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

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

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

    /// @notice The maximum amount of asset that can be deposited
    uint256 public depositLimit;

    /// @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 Target leverage ratio in WAD (e.g., 3e18 = 3x leverage)
    /// @dev leverage = collateralValue / (collateralValue - debtValue) = 1 / (1 - LTV)
    uint256 public targetLeverageRatio;

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

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

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

    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);
            debtToRepay -= _amount;

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

            bytes memory data = abi.encode(
                FlashLoanData({
                    operation: FlashLoanOperation.DELEVERAGE,
                    targetAmount: collateralToWithdraw
                })
            );
            _executeFlashloan(address(asset), debtToRepay, 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 16 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 17 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 21 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 31 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 33 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: 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"},{"internalType":"address","name":"_router","type":"address"}],"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":"address","name":"_base","type":"address"}],"name":"setBase","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"},{"inputs":[],"name":"vaultAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

6101406040525f805462ffffff191662271001179055600f8054610100600160a81b03191674c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2001790556010805473e592427a0aece92de3edee1f18e0157c058615646001600160a01b031990911617905534801562000071575f80fd5b5060405162005f0b38038062005f0b833981016040819052620000949162000a7c565b6001600160a01b0386166080523060a0526040518690869086908690869085908590859083908390829082906200011190620000dd908490849033908190819060240162000b95565b60408051601f198184030181529190526020810180516001600160e01b03908116634b839d7360e11b179091526200047316565b505073d377919fa87120584b21279a491f82d5265a139c7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc555050506001600160a01b03811660c0525f196001908155305f908152600760205260408120805460ff19169092179091556729a2241af62c00006004556703782dace9d90000600255673782dace9d900000600355642e90edd0006005558054600160281b600160681b03191665320000000000179055620001cd600a62000502565b620001da6103e862000564565b5050506001600160a01b03821661010081905260e0829052604051632c3c915760e01b815260048101839052632c3c91579060240160a060405180830381865afa1580156200022b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000251919062000bd7565b8051600a80546001600160a01b03199081166001600160a01b039384169081179092556020840151600b805483169185169190911790556040840151600c805483169185169190911790556060840151600d8054909216908416179055608090920151600e55861614620002f95760405162461bcd60e51b815260206004820152600a60248201526910b637b0b72a37b5b2b760b11b60448201526064015b60405180910390fd5b600b546001600160a01b03848116911614620003465760405162461bcd60e51b815260206004820152600b60248201526a0858dbdb1b185d195c985b60aa1b6044820152606401620002f0565b6200035d6001600160a01b038616835f1962000601565b620003746001600160a01b038416835f1962000601565b5050505050836001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620003b6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620003dc919062000c6a565b6001600160a01b039081166101208190526080519091165f8181526011602081815260408084209584529481528483208054606462ffffff1991821681179092559282528584209484529390529290208054909216179055601080546001600160a01b0319166001600160a01b038381169190911790915561012051620004679116855f1962000601565b50505050505062000cd8565b60605f8073d377919fa87120584b21279a491f82d5265a139c6001600160a01b031684604051620004a5919062000c86565b5f60405180830381855af49150503d805f8114620004df576040519150601f19603f3d011682016040523d82523d5f602084013e620004e4565b606091505b509150915081620004fb576040513d805f833e8082fd5b9392505050565b6127108110620005435760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401620002f0565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b5f8111620005a45760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401620002f0565b61ffff811115620005e45760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401620002f0565b5f805461ffff9092166101000262ffff0019909216919091179055565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b0390811663095ea7b360e01b179091526200065b9085908390620006d616565b620006d0576040516001600160a01b03841660248201525f6044820152620006c490859063095ea7b360e01b9060640160408051808303601f190181529190526020810180516001600160e01b0319939093166001600160e01b03938416179052906200078016565b620006d0848262000780565b50505050565b5f805f846001600160a01b031684604051620006f3919062000c86565b5f604051808303815f865af19150503d805f81146200072e576040519150601f19603f3d011682016040523d82523d5f602084013e62000733565b606091505b5091509150818015620007615750805115806200076157508080602001905181019062000761919062000ca3565b80156200077757506001600160a01b0385163b15155b95945050505050565b6040805180820190915260208082527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564908201525f90620007ce906001600160a01b03851690849062000857565b905080515f1480620007f1575080806020019051810190620007f1919062000ca3565b620008525760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401620002f0565b505050565b60606200086784845f856200086f565b949350505050565b606082471015620008d25760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401620002f0565b5f80866001600160a01b03168587604051620008ef919062000c86565b5f6040518083038185875af1925050503d805f81146200092b576040519150601f19603f3d011682016040523d82523d5f602084013e62000930565b606091505b50909250905062000944878383876200094f565b979650505050505050565b60608315620009c25782515f03620009ba576001600160a01b0385163b620009ba5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401620002f0565b508162000867565b620008678383815115620009d95781518083602001fd5b8060405162461bcd60e51b8152600401620002f0919062000cc4565b80516001600160a01b038116811462000a0c575f80fd5b919050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b038111828210171562000a505762000a5062000a11565b604052919050565b5f5b8381101562000a7457818101518382015260200162000a5a565b50505f910152565b5f805f805f8060c0878903121562000a92575f80fd5b62000a9d87620009f5565b60208801519096506001600160401b038082111562000aba575f80fd5b818901915089601f83011262000ace575f80fd5b81518181111562000ae35762000ae362000a11565b62000af8601f8201601f191660200162000a25565b91508082528a602082850101111562000b0f575f80fd5b62000b2281602084016020860162000a58565b50955062000b35905060408801620009f5565b935062000b4560608801620009f5565b92506080870151915062000b5c60a08801620009f5565b90509295509295509295565b5f815180845262000b8181602086016020860162000a58565b601f01601f19169290920160200192915050565b5f60018060a01b03808816835260a0602084015262000bb860a084018862000b68565b9581166040840152938416606083015250911660809091015292915050565b5f60a0828403121562000be8575f80fd5b60405160a081016001600160401b038111828210171562000c0d5762000c0d62000a11565b60405262000c1b83620009f5565b815262000c2b60208401620009f5565b602082015262000c3e60408401620009f5565b604082015262000c5160608401620009f5565b6060820152608083015160808201528091505092915050565b5f6020828403121562000c7b575f80fd5b620004fb82620009f5565b5f825162000c9981846020870162000a58565b9190910192915050565b5f6020828403121562000cb4575f80fd5b81518015158114620004fb575f80fd5b602081525f620004fb602083018462000b68565b60805160a05160c05160e051610100516101205161507f62000e8c5f395f81816105c2015281816132a70152613b6701525f818161088201528181610c3401528181610e93015281816113e501528181611ca70152818161245c0152818161262a01528181612a8e01528181612ad501528181612b3601528181612d3c015281816130bb015281816139c60152613c8001525f818161069f015281816113ad01528181612af7015261398e01525f81816107a50152818161164e0152818161322e0152613bac01525f818161098f01528181610a5f01528181610ade01528181610b6e01528181610ee701528181610f98015281816112ef0152818161153c0152818161169a015281816116fd01528181611797015281816118130152818161189a01528181611926015281816119ac01528181611a2801528181611aa301528181611b9b01528181611c1701528181611d4c01528181611e2b01528181611eaf01528181611f47015281816124e1015281816126ac015261310f01525f81816115c501528181611cd101528181612978015281816132c801528181613824015281816139420152613b46015261507f5ff3fe608060405234801561000f575f80fd5b50600436106103ef575f3560e01c8063797bf34311610213578063cfaec0da11610123578063ecf70858116100b6578063f887ea4011610085578063f887ea401461091b578063fc7f71b61461092e578063fd9f5f7514610941578063fde813a814610954578063ff831b0514610967576103ef565b8063ecf70858146108b4578063efbb5cb0146108bd578063f0fa55a9146108c5578063f3ce280a146108d8576103ef565b8063d6968601116100f2578063d69686011461086a578063d8fbc8331461087d578063e8621149146108a4578063ea9c8407146108ac576103ef565b8063cfaec0da14610811578063d19a3bb814610824578063d472a43b1461083f578063d63a8e1114610848576103ef565b80639b90fb16116101a6578063b6a1650611610175578063b6a16506146107c7578063b8c6f579146107d0578063bdc8144b146107e3578063be17fe62146107f6578063c31443bb14610809576103ef565b80639b90fb16146107675780639d7fb70c1461077a578063ac00ff261461078d578063b2016bd4146107a0576103ef565b806384d78a38116101e257806384d78a38146107255780638ca6dd4d14610739578063950b3d731461074157806398cdabc914610754576103ef565b8063797bf343146106f05780637baf6f77146106f85780637d969932146107005780637d9f6db514610712576103ef565b806349317f1d1161030e5780635ef76292116102a15780636c7a0c91116102705780636c7a0c91146106725780636ed71ede1461069a57806371ee95c0146106c157806372b10dd5146106d4578063757a291f146106dd576103ef565b80635ef762921461063d5780636687500e146106465780636718835f1461064e5780636be36a1d1461066a576103ef565b80635001f3b5116102dd5780635001f3b5146105f7578063503160d91461060f578063580e0d81146106225780635d265d3f14610635576103ef565b806349317f1d146105a55780634a5d0943146105ad5780634ab9e16b146105bd5780634aca9482146105e4576103ef565b80632e3ecf2c116103865780633d6cb575116103555780633d6cb5751461053b5780633e032a3b1461054e5780634697f05d1461057f57806346aa2f1214610592576103ef565b80632e3ecf2c146104ec57806331f57072146104ff5780633259356e14610512578063392f7a7014610533576103ef565b806318144367116103c2578063181443671461048a57806320aa49ae14610493578063219461ed146104a65780632b0015e6146104d9576103ef565b806304bd4629146104245780630870e1801461044b57806309218e911461045e5780630ea44a5614610481575b73d377919fa87120584b21279a491f82d5265a139c365f80375f80365f845af43d5f803e80801561041e573d5ff35b3d5ffd5b005b61043861043236600461461c565b505f1990565b6040519081526020015b60405180910390f35b610422610459366004614637565b61097a565b6104666109f5565b60408051938452602084019290925290820152606001610442565b61043860045481565b61043860085481565b6104226104a136600461465b565b610a4a565b6104c1733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae81565b6040516001600160a01b039091168152602001610442565b6104226104e7366004614637565b610ac9565b6104226104fa366004614676565b610b59565b61042261050d3660046146c5565b610c29565b61052561052036600461461c565b610d14565b604051610442929190614786565b610438610e49565b610422610549366004614637565b610ec1565b5f5461056790600160281b90046001600160401b031681565b6040516001600160401b039091168152602001610442565b61042261058d3660046147a0565b610ed2565b6104386105a036600461461c565b610f6f565b6104386110b8565b5f54610100900461ffff16610438565b6104c17f000000000000000000000000000000000000000000000000000000000000000081565b6104386105f236600461461c565b6110d7565b600f546104c19061010090046001600160a01b031681565b61042261061d366004614637565b6112d2565b610422610630366004614637565b6112da565b610525611361565b61043860035481565b61043861139e565b5f5461065a9060ff1681565b6040519015158152602001610442565b600e54610438565b610685610680366004614637565b611461565b60408051928352602083019190915201610442565b6104387f000000000000000000000000000000000000000000000000000000000000000081565b6104226106cf36600461481e565b6114ab565b61043860065481565b6104226106eb366004614637565b611527565b6104386115ae565b610438611637565b5f546301000000900461ffff16610438565b6009546104c1906001600160a01b031681565b60095461065a90600160a01b900460ff1681565b610422611685565b61042261074f366004614637565b611782565b610422610762366004614637565b6117fe565b610422610775366004614637565b611885565b610422610788366004614637565b611900565b61042261079b36600461465b565b611911565b6104c17f000000000000000000000000000000000000000000000000000000000000000081565b61043860055481565b6104226107de36600461461c565b611997565b6104226107f1366004614637565b611a13565b61042261080436600461461c565b611a8e565b610438611b2a565b61042261081f366004614637565b611b86565b6104c173d377919fa87120584b21279a491f82d5265a139c81565b61043860025481565b61065a61085636600461461c565b60076020525f908152604090205460ff1681565b610422610878366004614637565b611c02565b6104c17f000000000000000000000000000000000000000000000000000000000000000081565b610438611c7e565b610438611c90565b61043860015481565b610438611d02565b6104226108d3366004614637565b611d37565b6109076108e63660046148d8565b601160209081525f928352604080842090915290825290205462ffffff1681565b60405162ffffff9091168152602001610442565b6010546104c1906001600160a01b031681565b61043861093c36600461461c565b611e14565b61042261094f366004614637565b611e9a565b610422610962366004614637565b611f21565b610422610975366004614904565b611f32565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b1580156109d7575f80fd5b505afa1580156109e9573d5f803e3d5ffd5b50505060069190915550565b5f805f80610a0161139e565b9050610a0c816121b2565b9350610a16610e49565b92505f8411610a25575f610a42565b83610a38670de0b6b3a764000085614941565b610a429190614958565b915050909192565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610aa7575f80fd5b505afa158015610ab9573d5f803e3d5ffd5b50505050610ac6816121ed565b50565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015610b26575f80fd5b505afa158015610b38573d5f803e3d5ffd5b50505050610b55610b5082610b4b611637565b612235565b61224e565b5050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610bb6575f80fd5b505afa158015610bc8573d5f803e3d5ffd5b5050506001600160a01b038085165f8181526011602081815260408084209589168452948152848320805462ffffff1990811662ffffff8a16908117909255928252858420948452939052929020805490921617905550505050565b505050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610c905760405162461bcd60e51b8152602060048201526007602482015266216d6f7270686f60c81b60448201526064015b60405180910390fd5b600f5460ff16610cd55760405162461bcd60e51b815260206004820152601060248201526f666c6173686c6f616e2061637469766560801b6044820152606401610c87565b610c248383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506122a692505050565b6009545f906060906001600160a01b031680610d5c575f6040518060400160405280600e81526020016d139bc8185d58dd1a5bdb881cd95d60921b8152509250925050915091565b600954600160a01b900460ff16610da2575f60405180604001604052806011815260200170105d58dd1a5bdb9cc8191a5cd8589b1959607a1b8152509250925050915091565b5f610dac856110d7565b90508015801590610dbf57506008548110155b15610e11575050604080516001600160a01b0394909416602480860191909152815180860390910181526044909401905250506020810180516001600160e01b0316637e3fb8db60e11b179052600191565b5f604051806040016040528060138152602001726e6f7420656e6f756768206b69636b61626c6560681b815250935093505050915091565b6040805160a081018252600a546001600160a01b039081168252600b5481166020830152600c54811692820192909252600d5482166060820152600e5460808201525f91610ebc917f00000000000000000000000000000000000000000000000000000000000000009091169030612340565b905090565b610ec9612386565b610ac6816123bd565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015610f2f575f80fd5b505afa158015610f41573d5f803e3d5ffd5b505050506001600160a01b03919091165f908152600760205260409020805460ff1916911515919091179055565b6001600160a01b0381165f9081526007602052604081205460ff16610f9557505f919050565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ff2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110169190614977565b90505f8160015411611028575f611036565b81600154611036919061498e565b90505f6110416123c6565b9050805f0361105457505f949350505050565b5f195f61105f61240e565b9050805f0361107457505f9695505050505050565b5f8361108881670de0b6b3a764000061498e565b6110929084614941565b61109c9190614958565b90506110ac85610b4b8584612235565b98975050505050505050565b5f6110c1612386565b6110c96124a1565b90506110d4816124c6565b90565b6009545f90600160a01b900460ff166110f157505f919050565b6009546001600160a01b03168061110a57505f92915050565b604051639f8a13d760e01b81526001600160a01b038481166004830152821690639f8a13d790602401602060405180830381865afa15801561114e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061117291906149a1565b80156111e657506040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa1580156111c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111e49190614977565b115b156111f357505f92915050565b6040516370a0823160e01b81526001600160a01b0382811660048301528416906370a0823190602401602060405180830381865afa158015611237573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061125b9190614977565b6040516370a0823160e01b81523060048201526001600160a01b038516906370a0823190602401602060405180830381865afa15801561129d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112c19190614977565b6112cb91906149bc565b9392505050565b610ac6612386565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611337575f80fd5b505afa158015611349573d5f803e3d5ffd5b50505050610ac661135c82610b4b61139e565b612609565b5f606061136c612696565b6040805160048152602481019091526020810180516001600160e01b031663440368a360e01b17905290939092509050565b6040516349e2903160e11b81527f000000000000000000000000000000000000000000000000000000000000000060048201523060248201525f9081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906393c5206290604401606060405180830381865afa15801561142a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061144e9190614a29565b604001516001600160801b031692915050565b5f805f670de0b6b3a76400006004548561147b9190614941565b6114859190614958565b90505f848211611495575f61149f565b61149f858361498e565b91959194509092505050565b6040516301c7ba5760e61b8152733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae906371ee95c0906114f0908b908b908b908b908b908b908b908b90600401614b02565b5f604051808303815f87803b158015611507575f80fd5b505af1158015611519573d5f803e3d5ffd5b505050505050505050505050565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611584575f80fd5b505afa158015611596573d5f803e3d5ffd5b50505050610b556115a982610b4b6115ae565b6127db565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a08231906024015b602060405180830381865afa158015611613573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ebc9190614977565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a08231906024016115f8565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b1580156116e2575f80fd5b505afa1580156116f4573d5f803e3d5ffd5b505050506117807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611757573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061177b9190614977565b612839565b565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b1580156117df575f80fd5b505afa1580156117f1573d5f803e3d5ffd5b50505050610ac68161299e565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b15801561185b575f80fd5b505afa15801561186d573d5f803e3d5ffd5b50505050610ac661188082610b4b6115ae565b612a37565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b1580156118e2575f80fd5b505afa1580156118f4573d5f803e3d5ffd5b50505060059190915550565b611908612386565b610ac681612bb9565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b15801561196e575f80fd5b505afa158015611980573d5f803e3d5ffd5b50505f805460ff1916931515939093179092555050565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b1580156119f4575f80fd5b505afa158015611a06573d5f803e3d5ffd5b50505050610ac681612bc2565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611a70575f80fd5b505afa158015611a82573d5f803e3d5ffd5b50505060019190915550565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611aeb575f80fd5b505afa158015611afd573d5f803e3d5ffd5b5050600f80546001600160a01b0390941661010002610100600160a81b0319909416939093179092555050565b5f805f611b356109f5565b5091509150815f03611b49575f9250505090565b818110611b59575f199250505090565b611b63818361498e565b611b75670de0b6b3a764000084614941565b611b7f9190614958565b9250505090565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611be3575f80fd5b505afa158015611bf5573d5f803e3d5ffd5b50505050610ac681612d1b565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611c5f575f80fd5b505afa158015611c71573d5f803e3d5ffd5b50505050610ac681612db9565b5f80611c886109f5565b949350505050565b6040516370a0823160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f917f0000000000000000000000000000000000000000000000000000000000000000909116906370a08231906024016115f8565b5f611d0b610e49565b611d1b611d1661139e565b6121b2565b611d236115ae565b611d2d91906149bc565b610ebc919061498e565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611d94575f80fd5b505afa158015611da6573d5f803e3d5ffd5b505050506127108110611de65760405162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b6044820152606401610c87565b5f80546001600160401b03909216600160281b026cffffffffffffffff000000000019909216919091179055565b60405163d43fdcf760e01b81523360048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063d43fdcf7906024015f6040518083038186803b158015611e73575f80fd5b505afa158015611e85573d5f803e3d5ffd5b50505050611e9282612e19565b90505b919050565b6040516320b8029160e21b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906382e00a44906024015f6040518083038186803b158015611ef7575f80fd5b505afa158015611f09573d5f803e3d5ffd5b50505050610ac6611f1c82610b4b611637565b61309a565b611f29612386565b610ac6816130f5565b6040516348e4a64960e01b81523360048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906348e4a649906024015f6040518083038186803b158015611f8f575f80fd5b505afa158015611fa1573d5f803e3d5ffd5b50505050825f03611fff578115611ffa5760405162461bcd60e51b815260206004820152601f60248201527f627566666572206d7573742062652030206966207461726765742069732030006044820152606401610c87565b6120d2565b670de0b6b3a76400008310156120475760405162461bcd60e51b815260206004820152600d60248201526c0d8caeccae4c2ceca40784062f609b1b6044820152606401610c87565b662386f26fc100008210156120915760405162461bcd60e51b815260206004820152601060248201526f189d5999995c881d1bdbc81cdb585b1b60821b6044820152606401610c87565b8183116120d25760405162461bcd60e51b815260206004820152600f60248201526e3a30b933b2ba101e10313ab33332b960891b6044820152606401610c87565b6120dc82846149bc565b81101561212b5760405162461bcd60e51b815260206004820152601e60248201527f6d6178206c65766572616765203c20746172676574202b2062756666657200006044820152606401610c87565b5f8161213f670de0b6b3a764000080614941565b6121499190614958565b61215b90670de0b6b3a764000061498e565b9050612166600e5490565b81106121a35760405162461bcd60e51b815260206004820152600c60248201526b32bc31b2b2b2399026262a2b60a11b6044820152606401610c87565b50600492909255600255600355565b5f815f036121c157505f919050565b6ec097ce7bc90715b34b9f10000000006121d96131b3565b6121e39084614941565b611e929190614958565b6009805460ff60a01b1916600160a01b831515908102919091179091556040517feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a250565b5f8183106122435781612245565b825b90505b92915050565b5f80612259836131fa565b9050612265835f6132ee565b8110156122485760405162461bcd60e51b815260206004820152600f60248201526e1cdb1a5c1c1859d94e88185cdcd95d608a1b6044820152606401610c87565b5f818060200190518101906122bb9190614bdd565b90505f815160018111156122d1576122d1614c35565b036122e057610c248382613351565b6001815160018111156122f5576122f5614c35565b0361230457610c248382613388565b60405162461bcd60e51b815260206004820152601160248201527034b73b30b634b21037b832b930ba34b7b760791b6044820152606401610c87565b5f8061234d8460a0902090565b90505f6123646001600160a01b03871683866133bc565b90505f80612372888861346e565b90945092506110ac91508490508383613764565b3330146117805760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b6044820152606401610c87565b610ac681612839565b5f670de0b6b3a7640000600454116123dd57505f90565b6004546123f2670de0b6b3a764000080614941565b6123fc9190614958565b610ebc90670de0b6b3a764000061498e565b6040805160a081018252600a546001600160a01b039081168252600b5481166020830152600c54811692820192909252600d5482166060820152600e5460808201525f9182918291612484917f00000000000000000000000000000000000000000000000000000000000000009091169061346e565b509250509150808211612497575f611b7f565b611b7f818361498e565b5f6124be6124b96124b06115ae565b610b4b30610f6f565b613788565b610ebc611d02565b5f5460ff166124de57505f805460ff19166001179055565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa15801561253b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061255f9190614977565b9050808211156125d2575f546127109061258290610100900461ffff1683614941565b61258c9190614958565b612596828461498e565b1115610b555760405162461bcd60e51b815260206004820152600b60248201526a6865616c7468436865636b60a81b6044820152606401610c87565b81811115610b55575f54612710906125f5906301000000900461ffff1683614941565b6125ff9190614958565b612596838361498e565b805f036126135750565b604051638720316d60e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690638720316d9061266690600a90859030908190600401614c87565b5f604051808303815f87803b15801561267d575f80fd5b505af115801561268f573d5f803e3d5ffd5b5050505050565b5f61269f61397f565b156126aa5750600190565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612706573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061272a9190614977565b5f0361273557505f90565b5f61273e611b2a565b905060035481111561275257600191505090565b6004545f819003612772575f82118015611b7f5750600554481115611b7f565b60065461277d6115ae565b111561278e57600554481115611b7f565b5f6002548261279d91906149bc565b90505f600254836127ae919061498e565b9050808410806127bd57508184115b156127d15760055448111594505050505090565b5f94505050505090565b5f806127e683613b31565b90506127f38360016132ee565b8110156122485760405162461bcd60e51b81526020600482015260146024820152731cdb1a5c1c1859d94e8818dbdb1b185d195c985b60621b6044820152606401610c87565b5f806128436109f5565b5091509150805f03612878575f61286461285c85613c1e565b610b4b61139e565b905061286f81612609565b61268f8161224e565b5f612883828461498e565b90505f848211612893575f61289d565b61289d858361498e565b90505f6128a982611461565b9150505f8185116128ba575f6128f8565b5f54612710906128da90600160281b90046001600160401b0316826149bc565b6128e4848861498e565b6128ee9190614941565b6128f89190614958565b90505f61290d61290889846149bc565b613c1e565b90508115801561291c57508015155b1561293e5761292a81612609565b6129338161224e565b505050505050505050565b60408051808201825260018152602080820184905291515f92612962929101614cbb565b60405160208183030381529060405290506129337f00000000000000000000000000000000000000000000000000000000000000008483613c5c565b5f81116129dc5760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401610c87565b61ffff811115612a1a5760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401610c87565b5f805461ffff9092166101000262ffff0019909216919091179055565b805f03612a415750565b6040805160a081018252600a546001600160a01b039081168252600b5481166020830152600c54811692820192909252600d549091166060820152600e5460808201525f908190612ab3907f00000000000000000000000000000000000000000000000000000000000000009061346e565b9350935050505f612b1c612ac8858585613cf5565b610b4b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f0000000000000000000000000000000000000000000000000000000000000000306133bc565b6040516320b76e8160e01b81529091506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906320b76e8190612b7290600a905f9086903090600401614cf2565b60408051808303815f875af1158015612b8d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bb19190614d38565b505050505050565b610ac681613788565b6001600160a01b03811615612cd257306001600160a01b0316816001600160a01b031663f7260d3e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c17573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c3b9190614d5a565b6001600160a01b031614612c825760405162461bcd60e51b815260206004820152600e60248201526d3bb937b733903932b1b2b4bb32b960911b6044820152606401610c87565b600954600160a01b900460ff16612cd2576009805460ff60a01b1916600160a01b1790556040516001907feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a25b600980546001600160a01b0319166001600160a01b0383169081179091556040517f4da9b3b7ca08b559bc11eb42bb6961e0813372ed0b55f0e9b68b76cf0207fce8905f90a250565b805f03612d255750565b6040516350d8cd4b60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906350d8cd4b90612d7a90600a9085905f9030908190600401614d75565b60408051808303815f875af1158015612d95573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c249190614d38565b6127108110612df85760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401610c87565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b6009545f90600160a01b900460ff16612e6a5760405162461bcd60e51b815260206004820152601360248201527275736541756374696f6e2069732066616c736560681b6044820152606401610c87565b600954604051639f8a13d760e01b81526001600160a01b038481166004830152909116908190639f8a13d790602401602060405180830381865afa158015612eb4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ed891906149a1565b15612fad576040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa158015612f24573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f489190614977565b1115612f5657505f92915050565b604051636a256b2960e01b81526001600160a01b038481166004830152821690636a256b29906024015f604051808303815f87803b158015612f96575f80fd5b505af1158015612fa8573d5f803e3d5ffd5b505050505b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa158015612ff1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130159190614977565b90508015613031576130316001600160a01b0385168383613d19565b6040516396c5517560e01b81526001600160a01b0385811660048301528316906396c55175906024016020604051808303815f875af1158015613076573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c889190614977565b805f036130a45750565b60405163238d657960e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063238d65799061266690600a9085903090600401614db1565b5f6130fe610e49565b9050801561318d57610b5561177b837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015613169573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b4b9190614977565b8115610b555761319f82610b4b61139e565b91506131aa82612609565b610c248261224e565b600c546040805163501ad8ff60e11b815290515f926001600160a01b03169163a035b1fe9160048083019260209291908290030181865afa158015611613573d5f803e3d5ffd5b5f815f0361320957505f919050565b604051635d043b2960e11b815260048101839052306024820181905260448201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063ba087652906064016020604051808303815f875af115801561327c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132a09190614977565b90506112cb7f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000835f613d7c565b5f825f036132fd57505f612248565b5f826133115761330c846121b2565b61331a565b61331a84613c1e565b5f549091506127109061333d90600160281b90046001600160401b03168261498e565b6133479083614941565b611c889190614958565b5f82826020015161336291906149bc565b90505f61336e826127db565b90506133798161309a565b61338284612d1b565b50505050565b61339761188083610b4b610e49565b5f6133a88260200151610b4b61139e565b90506133b381612609565b6133828161224e565b5f806133d06133cb858561402e565b6140a1565b604051637784c68560e01b81529091506001600160a01b03861690637784c685906133ff908490600401614df1565b5f60405180830381865afa158015613419573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526134409190810190614e34565b5f8151811061345157613451614ec8565b60200260200101515f1c6001600160801b03169150509392505050565b5f805f805f61347e8660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa1580156134c6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134ea9190614edc565b90505f81608001516001600160801b031642613506919061498e565b90508015801590613523575060408201516001600160801b031615155b801561353b575060608801516001600160a01b031615155b15613730576060888101805160408051638c00bf6b60e01b81528c516001600160a01b0390811660048301526020808f015182166024840152838f0151821660448401529451811660648301526080808f0151608484015288516001600160801b0390811660a485015295890151861660c484015292880151851660e483015294870151841661010482015290860151831661012482015260a08601519092166101448301525f921690638c00bf6b9061016401602060405180830381865afa15801561360a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061362e9190614977565b90505f61365261363e83856140ea565b60408601516001600160801b031690614148565b905061365d8161415c565b8460400181815161366e9190614f78565b6001600160801b03169052506136838161415c565b84518590613692908390614f78565b6001600160801b0390811690915260a08601511615905061372d575f6136ce8560a001516001600160801b03168361414890919063ffffffff16565b90505f61370282875f01516001600160801b03166136ec919061498e565b60208801518491906001600160801b0316613cf5565b905061370d8161415c565b8660200181815161371e9190614f78565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f611c886137736001856149bc565b613780620f4240856149bc565b8691906141b8565b5f806137926109f5565b5090925090505f836137a4838561498e565b6137ae91906149bc565b90505f6137ba82611461565b91505082811115613851575f6137d0848361498e565b905060065481116137ea57612bb161188087610b4b610e49565b6040805180820182525f80825260208083018a90529251909261380e929101614cbb565b604051602081830303815290604052905061384a7f00000000000000000000000000000000000000000000000000000000000000008383613c5c565b505061268f565b80831115613970575f613864828561498e565b905080861061389e5761387681612a37565b5f613881828861498e565b9050801561389557613895611f1c826127db565b50505050505050565b6138a786612a37565b6138b1868261498e565b5f805491925090612710906138d690600160281b90046001600160401b0316826149bc565b6138df84613c1e565b6138e99190614941565b6138f39190614958565b90505f604051806040016040528060018081111561391357613913614c35565b81526020018381525060405160200161392c9190614cbb565b60405160208183030381529060405290506139687f00000000000000000000000000000000000000000000000000000000000000008483613c5c565b50505061268f565b61268f61188086610b4b610e49565b6040516349e2903160e11b81527f000000000000000000000000000000000000000000000000000000000000000060048201523060248201525f9081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906393c5206290604401606060405180830381865afa158015613a0b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a2f9190614a29565b905080602001516001600160801b03165f03613a4c575f91505090565b5f6ec097ce7bc90715b34b9f1000000000600a6002015f9054906101000a90046001600160a01b03166001600160a01b031663a035b1fe6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613ab0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ad49190614977565b83604001516001600160801b0316613aec9190614941565b613af69190614958565b90505f670de0b6b3a7640000600a6004015483613b139190614941565b613b1d9190614958565b905080613b28610e49565b11935050505090565b5f815f03613b4057505f919050565b5f613b8d7f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000855f613d7c565b604051636e553f6560e01b8152600481018290523060248201529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636e553f65906044016020604051808303815f875af1158015613bfa573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112cb9190614977565b5f815f03613c2d57505f919050565b5f613c366131b3565b905080613c526ec097ce7bc90715b34b9f100000000085614941565b6112cb9190614958565b600f805460ff1916600117905560405163701195a160e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063e0232b4290613cb990869086908690600401614f9f565b5f604051808303815f87803b158015613cd0575f80fd5b505af1158015613ce2573d5f803e3d5ffd5b5050600f805460ff191690555050505050565b5f611c88613d06620f4240846149bc565b613d116001866149bc565b8691906141d9565b6040516001600160a01b038316602482015260448101829052610c2490849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526141e5565b5f8215801590613d8e57506008548310155b15611c8857601054613daa906001600160a01b031686856142b8565b600f546001600160a01b03868116610100909204161480613ddd5750600f546001600160a01b0385811661010090920416145b15613ef35760408051610100810182526001600160a01b0387811680835287821660208085018281525f938452601182528684209284529190528482205462ffffff9081168587019081523060608701908152426080880190815260a088018c815260c089018c815260e08a019788526010549a5163414bf38960e01b81528a518a16600482015296518916602488015293519094166044860152905186166064850152516084840152905160a48301525160c48201529051821660e48201529192169063414bf38990610104016020604051808303815f875af1158015613ec7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613eeb9190614977565b915050611c88565b6001600160a01b038581165f908152601160208181526040808420600f5461010090048087168652908352818520549383528185208a8716865283529381902054815160608c811b6bffffffffffffffffffffffff199081169583019590955260e895861b6001600160e81b0319908116603484015296811b851660378301529190941b909416604b8401529288901b16604e8201528151604281830301815260105461010283018452606283018281523060828501524260a285015260c2840189905260e2909301879052925163c04b8d5960e01b81529093929092169163c04b8d5991613fe491600401614fc5565b6020604051808303815f875af1158015614000573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140249190614977565b9695505050505050565b5f60018284600260405160200161404f929190918252602082015260400190565b60408051601f1981840301815282825280516020918201206001600160a01b0390941690830152810191909152606001604051602081830303815290604052805190602001205f1c61224591906149bc565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f815181106140d9576140d9614ec8565b602090810291909101015292915050565b5f806140f68385614941565b90505f6141168280614111670de0b6b3a76400006002614941565b6141d9565b90505f6141318284614111670de0b6b3a76400006003614941565b90508061413e83856149bc565b61402491906149bc565b5f6122458383670de0b6b3a76400006141d9565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b038311156141b15760405162461bcd60e51b8152600401610c87919061501c565b5090919050565b5f816141c560018261498e565b6141cf8587614941565b61334791906149bc565b5f816133478486614941565b5f614239826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166143579092919063ffffffff16565b905080515f148061425957508080602001905181019061425991906149a1565b610c245760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610c87565b604051636eb1769f60e11b81523060048201526001600160a01b03848116602483015282919084169063dd62ed3e90604401602060405180830381865afa158015614305573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143299190614977565b1015610c24576143436001600160a01b038316845f614365565b610c246001600160a01b0383168483614365565b6060611c8884845f856143f3565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526143b684826144ca565b613382576040516001600160a01b03841660248201525f60448201526143e990859063095ea7b360e01b90606401613d45565b61338284826141e5565b6060824710156144545760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610c87565b5f80866001600160a01b0316858760405161446f919061502e565b5f6040518083038185875af1925050503d805f81146144a9576040519150601f19603f3d011682016040523d82523d5f602084013e6144ae565b606091505b50915091506144bf8783838761456b565b979650505050505050565b5f805f846001600160a01b0316846040516144e5919061502e565b5f604051808303815f865af19150503d805f811461451e576040519150601f19603f3d011682016040523d82523d5f602084013e614523565b606091505b509150915081801561454d57508051158061454d57508080602001905181019061454d91906149a1565b801561456257506001600160a01b0385163b15155b95945050505050565b606083156145d95782515f036145d2576001600160a01b0385163b6145d25760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610c87565b5081611c88565b611c8883838151156145ee5781518083602001fd5b8060405162461bcd60e51b8152600401610c87919061501c565b6001600160a01b0381168114610ac6575f80fd5b5f6020828403121561462c575f80fd5b81356112cb81614608565b5f60208284031215614647575f80fd5b5035919050565b8015158114610ac6575f80fd5b5f6020828403121561466b575f80fd5b81356112cb8161464e565b5f805f60608486031215614688575f80fd5b833561469381614608565b925060208401356146a381614608565b9150604084013562ffffff811681146146ba575f80fd5b809150509250925092565b5f805f604084860312156146d7575f80fd5b8335925060208401356001600160401b03808211156146f4575f80fd5b818601915086601f830112614707575f80fd5b813581811115614715575f80fd5b876020828501011115614726575f80fd5b6020830194508093505050509250925092565b5f5b8381101561475357818101518382015260200161473b565b50505f910152565b5f8151808452614772816020860160208601614739565b601f01601f19169290920160200192915050565b8215158152604060208201525f611c88604083018461475b565b5f80604083850312156147b1575f80fd5b82356147bc81614608565b915060208301356147cc8161464e565b809150509250929050565b5f8083601f8401126147e7575f80fd5b5081356001600160401b038111156147fd575f80fd5b6020830191508360208260051b8501011115614817575f80fd5b9250929050565b5f805f805f805f806080898b031215614835575f80fd5b88356001600160401b038082111561484b575f80fd5b6148578c838d016147d7565b909a50985060208b013591508082111561486f575f80fd5b61487b8c838d016147d7565b909850965060408b0135915080821115614893575f80fd5b61489f8c838d016147d7565b909650945060608b01359150808211156148b7575f80fd5b506148c48b828c016147d7565b999c989b5096995094979396929594505050565b5f80604083850312156148e9575f80fd5b82356148f481614608565b915060208301356147cc81614608565b5f805f60608486031215614916575f80fd5b505081359360208301359350604090920135919050565b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176122485761224861492d565b5f8261497257634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215614987575f80fd5b5051919050565b818103818111156122485761224861492d565b5f602082840312156149b1575f80fd5b81516112cb8161464e565b808201808211156122485761224861492d565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b0381118282101715614a0b57614a0b6149cf565b604052919050565b80516001600160801b0381168114611e95575f80fd5b5f60608284031215614a39575f80fd5b604051606081018181106001600160401b0382111715614a5b57614a5b6149cf565b60405282518152614a6e60208401614a13565b6020820152614a7f60408401614a13565b60408201529392505050565b8183525f60208085019450825f5b85811015614ac7578135614aac81614608565b6001600160a01b031687529582019590820190600101614a99565b509495945050505050565b8183525f6001600160fb1b03831115614ae9575f80fd5b8260051b80836020870137939093016020019392505050565b608081525f614b15608083018a8c614a8b565b602083820381850152614b29828a8c614a8b565b91508382036040850152614b3e82888a614ad2565b84810360608601528581529150808201600586811b84018301885f5b89811015614bc857868303601f190185528135368c9003601e19018112614b7f575f80fd5b8b0186810190356001600160401b03811115614b99575f80fd5b80861b3603821315614ba9575f80fd5b614bb4858284614ad2565b968801969450505090850190600101614b5a565b50909f9e505050505050505050505050505050565b5f60408284031215614bed575f80fd5b604051604081018181106001600160401b0382111715614c0f57614c0f6149cf565b604052825160028110614c20575f80fd5b81526020928301519281019290925250919050565b634e487b7160e01b5f52602160045260245ffd5b80546001600160a01b039081168352600182015481166020840152600282015481166040840152600382015416606083015260040154608090910152565b6101008101614c968287614c49565b60a08201949094526001600160a01b0392831660c0820152911660e090910152919050565b8151604082019060028110614cde57634e487b7160e01b5f52602160045260245ffd5b808352506020830151602083015292915050565b5f610120614d008388614c49565b60a08301959095525060c08101929092526001600160a01b031660e082015261010081018290525f9181019190915261014001919050565b5f8060408385031215614d49575f80fd5b505080516020909101519092909150565b5f60208284031215614d6a575f80fd5b81516112cb81614608565b6101208101614d848288614c49565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b5f610100614dbf8387614c49565b60a0830194909452506001600160a01b039190911660c082015260e081018290525f9181019190915261012001919050565b602080825282518282018190525f9190848201906040850190845b81811015614e2857835183529284019291840191600101614e0c565b50909695505050505050565b5f6020808385031215614e45575f80fd5b82516001600160401b0380821115614e5b575f80fd5b818501915085601f830112614e6e575f80fd5b815181811115614e8057614e806149cf565b8060051b9150614e918483016149e3565b8181529183018401918481019088841115614eaa575f80fd5b938501935b838510156110ac57845182529385019390850190614eaf565b634e487b7160e01b5f52603260045260245ffd5b5f60c08284031215614eec575f80fd5b60405160c081018181106001600160401b0382111715614f0e57614f0e6149cf565b604052614f1a83614a13565b8152614f2860208401614a13565b6020820152614f3960408401614a13565b6040820152614f4a60608401614a13565b6060820152614f5b60808401614a13565b6080820152614f6c60a08401614a13565b60a08201529392505050565b6001600160801b03818116838216019080821115614f9857614f9861492d565b5092915050565b60018060a01b0384168152826020820152606060408201525f614562606083018461475b565b602081525f825160a06020840152614fe060c084018261475b565b905060018060a01b0360208501511660408401526040840151606084015260608401516080840152608084015160a08401528091505092915050565b602081525f612245602083018461475b565b5f825161503f818460208701614739565b919091019291505056fea2646970667358221220b660661ed134c773b56916c9a6d4e39e22e29405e3df2e9f33a41afd4f2f3a4364736f6c63430008170033000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd3600000000000000000000000000000000000000000000000000000000000000c00000000000000000000000009a6bd7b6fd5c4f87eb66356441502fc7dcdd185b000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abccdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc0000000000000000000000004e1d81a3e627b9294532e990109e4c21d217376c00000000000000000000000000000000000000000000000000000000000000197976555344542f55534443204d6f7270686f204c6f6f70657200000000000000

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106103ef575f3560e01c8063797bf34311610213578063cfaec0da11610123578063ecf70858116100b6578063f887ea4011610085578063f887ea401461091b578063fc7f71b61461092e578063fd9f5f7514610941578063fde813a814610954578063ff831b0514610967576103ef565b8063ecf70858146108b4578063efbb5cb0146108bd578063f0fa55a9146108c5578063f3ce280a146108d8576103ef565b8063d6968601116100f2578063d69686011461086a578063d8fbc8331461087d578063e8621149146108a4578063ea9c8407146108ac576103ef565b8063cfaec0da14610811578063d19a3bb814610824578063d472a43b1461083f578063d63a8e1114610848576103ef565b80639b90fb16116101a6578063b6a1650611610175578063b6a16506146107c7578063b8c6f579146107d0578063bdc8144b146107e3578063be17fe62146107f6578063c31443bb14610809576103ef565b80639b90fb16146107675780639d7fb70c1461077a578063ac00ff261461078d578063b2016bd4146107a0576103ef565b806384d78a38116101e257806384d78a38146107255780638ca6dd4d14610739578063950b3d731461074157806398cdabc914610754576103ef565b8063797bf343146106f05780637baf6f77146106f85780637d969932146107005780637d9f6db514610712576103ef565b806349317f1d1161030e5780635ef76292116102a15780636c7a0c91116102705780636c7a0c91146106725780636ed71ede1461069a57806371ee95c0146106c157806372b10dd5146106d4578063757a291f146106dd576103ef565b80635ef762921461063d5780636687500e146106465780636718835f1461064e5780636be36a1d1461066a576103ef565b80635001f3b5116102dd5780635001f3b5146105f7578063503160d91461060f578063580e0d81146106225780635d265d3f14610635576103ef565b806349317f1d146105a55780634a5d0943146105ad5780634ab9e16b146105bd5780634aca9482146105e4576103ef565b80632e3ecf2c116103865780633d6cb575116103555780633d6cb5751461053b5780633e032a3b1461054e5780634697f05d1461057f57806346aa2f1214610592576103ef565b80632e3ecf2c146104ec57806331f57072146104ff5780633259356e14610512578063392f7a7014610533576103ef565b806318144367116103c2578063181443671461048a57806320aa49ae14610493578063219461ed146104a65780632b0015e6146104d9576103ef565b806304bd4629146104245780630870e1801461044b57806309218e911461045e5780630ea44a5614610481575b73d377919fa87120584b21279a491f82d5265a139c365f80375f80365f845af43d5f803e80801561041e573d5ff35b3d5ffd5b005b61043861043236600461461c565b505f1990565b6040519081526020015b60405180910390f35b610422610459366004614637565b61097a565b6104666109f5565b60408051938452602084019290925290820152606001610442565b61043860045481565b61043860085481565b6104226104a136600461465b565b610a4a565b6104c1733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae81565b6040516001600160a01b039091168152602001610442565b6104226104e7366004614637565b610ac9565b6104226104fa366004614676565b610b59565b61042261050d3660046146c5565b610c29565b61052561052036600461461c565b610d14565b604051610442929190614786565b610438610e49565b610422610549366004614637565b610ec1565b5f5461056790600160281b90046001600160401b031681565b6040516001600160401b039091168152602001610442565b61042261058d3660046147a0565b610ed2565b6104386105a036600461461c565b610f6f565b6104386110b8565b5f54610100900461ffff16610438565b6104c17f0000000000000000000000002dca96907fde857dd3d816880a0df407eeb2d2f281565b6104386105f236600461461c565b6110d7565b600f546104c19061010090046001600160a01b031681565b61042261061d366004614637565b6112d2565b610422610630366004614637565b6112da565b610525611361565b61043860035481565b61043861139e565b5f5461065a9060ff1681565b6040519015158152602001610442565b600e54610438565b610685610680366004614637565b611461565b60408051928352602083019190915201610442565b6104387fcdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc81565b6104226106cf36600461481e565b6114ab565b61043860065481565b6104226106eb366004614637565b611527565b6104386115ae565b610438611637565b5f546301000000900461ffff16610438565b6009546104c1906001600160a01b031681565b60095461065a90600160a01b900460ff1681565b610422611685565b61042261074f366004614637565b611782565b610422610762366004614637565b6117fe565b610422610775366004614637565b611885565b610422610788366004614637565b611900565b61042261079b36600461465b565b611911565b6104c17f0000000000000000000000009a6bd7b6fd5c4f87eb66356441502fc7dcdd185b81565b61043860055481565b6104226107de36600461461c565b611997565b6104226107f1366004614637565b611a13565b61042261080436600461461c565b611a8e565b610438611b2a565b61042261081f366004614637565b611b86565b6104c173d377919fa87120584b21279a491f82d5265a139c81565b61043860025481565b61065a61085636600461461c565b60076020525f908152604090205460ff1681565b610422610878366004614637565b611c02565b6104c17f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc81565b610438611c7e565b610438611c90565b61043860015481565b610438611d02565b6104226108d3366004614637565b611d37565b6109076108e63660046148d8565b601160209081525f928352604080842090915290825290205462ffffff1681565b60405162ffffff9091168152602001610442565b6010546104c1906001600160a01b031681565b61043861093c36600461461c565b611e14565b61042261094f366004614637565b611e9a565b610422610962366004614637565b611f21565b610422610975366004614904565b611f32565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b1580156109d7575f80fd5b505afa1580156109e9573d5f803e3d5ffd5b50505060069190915550565b5f805f80610a0161139e565b9050610a0c816121b2565b9350610a16610e49565b92505f8411610a25575f610a42565b83610a38670de0b6b3a764000085614941565b610a429190614958565b915050909192565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015610aa7575f80fd5b505afa158015610ab9573d5f803e3d5ffd5b50505050610ac6816121ed565b50565b6040516320b8029160e21b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906382e00a44906024015f6040518083038186803b158015610b26575f80fd5b505afa158015610b38573d5f803e3d5ffd5b50505050610b55610b5082610b4b611637565b612235565b61224e565b5050565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015610bb6575f80fd5b505afa158015610bc8573d5f803e3d5ffd5b5050506001600160a01b038085165f8181526011602081815260408084209589168452948152848320805462ffffff1990811662ffffff8a16908117909255928252858420948452939052929020805490921617905550505050565b505050565b336001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc1614610c905760405162461bcd60e51b8152602060048201526007602482015266216d6f7270686f60c81b60448201526064015b60405180910390fd5b600f5460ff16610cd55760405162461bcd60e51b815260206004820152601060248201526f666c6173686c6f616e2061637469766560801b6044820152606401610c87565b610c248383838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506122a692505050565b6009545f906060906001600160a01b031680610d5c575f6040518060400160405280600e81526020016d139bc8185d58dd1a5bdb881cd95d60921b8152509250925050915091565b600954600160a01b900460ff16610da2575f60405180604001604052806011815260200170105d58dd1a5bdb9cc8191a5cd8589b1959607a1b8152509250925050915091565b5f610dac856110d7565b90508015801590610dbf57506008548110155b15610e11575050604080516001600160a01b0394909416602480860191909152815180860390910181526044909401905250506020810180516001600160e01b0316637e3fb8db60e11b179052600191565b5f604051806040016040528060138152602001726e6f7420656e6f756768206b69636b61626c6560681b815250935093505050915091565b6040805160a081018252600a546001600160a01b039081168252600b5481166020830152600c54811692820192909252600d5482166060820152600e5460808201525f91610ebc917f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc9091169030612340565b905090565b610ec9612386565b610ac6816123bd565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015610f2f575f80fd5b505afa158015610f41573d5f803e3d5ffd5b505050506001600160a01b03919091165f908152600760205260409020805460ff1916911515919091179055565b6001600160a01b0381165f9081526007602052604081205460ff16610f9557505f919050565b5f7f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ff2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110169190614977565b90505f8160015411611028575f611036565b81600154611036919061498e565b90505f6110416123c6565b9050805f0361105457505f949350505050565b5f195f61105f61240e565b9050805f0361107457505f9695505050505050565b5f8361108881670de0b6b3a764000061498e565b6110929084614941565b61109c9190614958565b90506110ac85610b4b8584612235565b98975050505050505050565b5f6110c1612386565b6110c96124a1565b90506110d4816124c6565b90565b6009545f90600160a01b900460ff166110f157505f919050565b6009546001600160a01b03168061110a57505f92915050565b604051639f8a13d760e01b81526001600160a01b038481166004830152821690639f8a13d790602401602060405180830381865afa15801561114e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061117291906149a1565b80156111e657506040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa1580156111c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111e49190614977565b115b156111f357505f92915050565b6040516370a0823160e01b81526001600160a01b0382811660048301528416906370a0823190602401602060405180830381865afa158015611237573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061125b9190614977565b6040516370a0823160e01b81523060048201526001600160a01b038516906370a0823190602401602060405180830381865afa15801561129d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112c19190614977565b6112cb91906149bc565b9392505050565b610ac6612386565b6040516320b8029160e21b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906382e00a44906024015f6040518083038186803b158015611337575f80fd5b505afa158015611349573d5f803e3d5ffd5b50505050610ac661135c82610b4b61139e565b612609565b5f606061136c612696565b6040805160048152602481019091526020810180516001600160e01b031663440368a360e01b17905290939092509050565b6040516349e2903160e11b81527fcdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc60048201523060248201525f9081906001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906393c5206290604401606060405180830381865afa15801561142a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061144e9190614a29565b604001516001600160801b031692915050565b5f805f670de0b6b3a76400006004548561147b9190614941565b6114859190614958565b90505f848211611495575f61149f565b61149f858361498e565b91959194509092505050565b6040516301c7ba5760e61b8152733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae906371ee95c0906114f0908b908b908b908b908b908b908b908b90600401614b02565b5f604051808303815f87803b158015611507575f80fd5b505af1158015611519573d5f803e3d5ffd5b505050505050505050505050565b6040516320b8029160e21b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906382e00a44906024015f6040518083038186803b158015611584575f80fd5b505afa158015611596573d5f803e3d5ffd5b50505050610b556115a982610b4b6115ae565b6127db565b6040516370a0823160e01b81523060048201525f907f000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd366001600160a01b0316906370a08231906024015b602060405180830381865afa158015611613573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ebc9190614977565b6040516370a0823160e01b81523060048201525f907f0000000000000000000000009a6bd7b6fd5c4f87eb66356441502fc7dcdd185b6001600160a01b0316906370a08231906024016115f8565b6040516320b8029160e21b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906382e00a44906024015f6040518083038186803b1580156116e2575f80fd5b505afa1580156116f4573d5f803e3d5ffd5b505050506117807f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015611757573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061177b9190614977565b612839565b565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b1580156117df575f80fd5b505afa1580156117f1573d5f803e3d5ffd5b50505050610ac68161299e565b6040516320b8029160e21b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906382e00a44906024015f6040518083038186803b15801561185b575f80fd5b505afa15801561186d573d5f803e3d5ffd5b50505050610ac661188082610b4b6115ae565b612a37565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b1580156118e2575f80fd5b505afa1580156118f4573d5f803e3d5ffd5b50505060059190915550565b611908612386565b610ac681612bb9565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b15801561196e575f80fd5b505afa158015611980573d5f803e3d5ffd5b50505f805460ff1916931515939093179092555050565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b1580156119f4575f80fd5b505afa158015611a06573d5f803e3d5ffd5b50505050610ac681612bc2565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015611a70575f80fd5b505afa158015611a82573d5f803e3d5ffd5b50505060019190915550565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015611aeb575f80fd5b505afa158015611afd573d5f803e3d5ffd5b5050600f80546001600160a01b0390941661010002610100600160a81b0319909416939093179092555050565b5f805f611b356109f5565b5091509150815f03611b49575f9250505090565b818110611b59575f199250505090565b611b63818361498e565b611b75670de0b6b3a764000084614941565b611b7f9190614958565b9250505090565b6040516320b8029160e21b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906382e00a44906024015f6040518083038186803b158015611be3575f80fd5b505afa158015611bf5573d5f803e3d5ffd5b50505050610ac681612d1b565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015611c5f575f80fd5b505afa158015611c71573d5f803e3d5ffd5b50505050610ac681612db9565b5f80611c886109f5565b949350505050565b6040516370a0823160e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc811660048301525f917f000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd36909116906370a08231906024016115f8565b5f611d0b610e49565b611d1b611d1661139e565b6121b2565b611d236115ae565b611d2d91906149bc565b610ebc919061498e565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015611d94575f80fd5b505afa158015611da6573d5f803e3d5ffd5b505050506127108110611de65760405162461bcd60e51b8152602060048201526008602482015267736c69707061676560c01b6044820152606401610c87565b5f80546001600160401b03909216600160281b026cffffffffffffffff000000000019909216919091179055565b60405163d43fdcf760e01b81523360048201525f907f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b03169063d43fdcf7906024015f6040518083038186803b158015611e73575f80fd5b505afa158015611e85573d5f803e3d5ffd5b50505050611e9282612e19565b90505b919050565b6040516320b8029160e21b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906382e00a44906024015f6040518083038186803b158015611ef7575f80fd5b505afa158015611f09573d5f803e3d5ffd5b50505050610ac6611f1c82610b4b611637565b61309a565b611f29612386565b610ac6816130f5565b6040516348e4a64960e01b81523360048201527f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b0316906348e4a649906024015f6040518083038186803b158015611f8f575f80fd5b505afa158015611fa1573d5f803e3d5ffd5b50505050825f03611fff578115611ffa5760405162461bcd60e51b815260206004820152601f60248201527f627566666572206d7573742062652030206966207461726765742069732030006044820152606401610c87565b6120d2565b670de0b6b3a76400008310156120475760405162461bcd60e51b815260206004820152600d60248201526c0d8caeccae4c2ceca40784062f609b1b6044820152606401610c87565b662386f26fc100008210156120915760405162461bcd60e51b815260206004820152601060248201526f189d5999995c881d1bdbc81cdb585b1b60821b6044820152606401610c87565b8183116120d25760405162461bcd60e51b815260206004820152600f60248201526e3a30b933b2ba101e10313ab33332b960891b6044820152606401610c87565b6120dc82846149bc565b81101561212b5760405162461bcd60e51b815260206004820152601e60248201527f6d6178206c65766572616765203c20746172676574202b2062756666657200006044820152606401610c87565b5f8161213f670de0b6b3a764000080614941565b6121499190614958565b61215b90670de0b6b3a764000061498e565b9050612166600e5490565b81106121a35760405162461bcd60e51b815260206004820152600c60248201526b32bc31b2b2b2399026262a2b60a11b6044820152606401610c87565b50600492909255600255600355565b5f815f036121c157505f919050565b6ec097ce7bc90715b34b9f10000000006121d96131b3565b6121e39084614941565b611e929190614958565b6009805460ff60a01b1916600160a01b831515908102919091179091556040517feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a250565b5f8183106122435781612245565b825b90505b92915050565b5f80612259836131fa565b9050612265835f6132ee565b8110156122485760405162461bcd60e51b815260206004820152600f60248201526e1cdb1a5c1c1859d94e88185cdcd95d608a1b6044820152606401610c87565b5f818060200190518101906122bb9190614bdd565b90505f815160018111156122d1576122d1614c35565b036122e057610c248382613351565b6001815160018111156122f5576122f5614c35565b0361230457610c248382613388565b60405162461bcd60e51b815260206004820152601160248201527034b73b30b634b21037b832b930ba34b7b760791b6044820152606401610c87565b5f8061234d8460a0902090565b90505f6123646001600160a01b03871683866133bc565b90505f80612372888861346e565b90945092506110ac91508490508383613764565b3330146117805760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b6044820152606401610c87565b610ac681612839565b5f670de0b6b3a7640000600454116123dd57505f90565b6004546123f2670de0b6b3a764000080614941565b6123fc9190614958565b610ebc90670de0b6b3a764000061498e565b6040805160a081018252600a546001600160a01b039081168252600b5481166020830152600c54811692820192909252600d5482166060820152600e5460808201525f9182918291612484917f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc9091169061346e565b509250509150808211612497575f611b7f565b611b7f818361498e565b5f6124be6124b96124b06115ae565b610b4b30610f6f565b613788565b610ebc611d02565b5f5460ff166124de57505f805460ff19166001179055565b5f7f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa15801561253b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061255f9190614977565b9050808211156125d2575f546127109061258290610100900461ffff1683614941565b61258c9190614958565b612596828461498e565b1115610b555760405162461bcd60e51b815260206004820152600b60248201526a6865616c7468436865636b60a81b6044820152606401610c87565b81811115610b55575f54612710906125f5906301000000900461ffff1683614941565b6125ff9190614958565b612596838361498e565b805f036126135750565b604051638720316d60e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc1690638720316d9061266690600a90859030908190600401614c87565b5f604051808303815f87803b15801561267d575f80fd5b505af115801561268f573d5f803e3d5ffd5b5050505050565b5f61269f61397f565b156126aa5750600190565b7f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015612706573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061272a9190614977565b5f0361273557505f90565b5f61273e611b2a565b905060035481111561275257600191505090565b6004545f819003612772575f82118015611b7f5750600554481115611b7f565b60065461277d6115ae565b111561278e57600554481115611b7f565b5f6002548261279d91906149bc565b90505f600254836127ae919061498e565b9050808410806127bd57508184115b156127d15760055448111594505050505090565b5f94505050505090565b5f806127e683613b31565b90506127f38360016132ee565b8110156122485760405162461bcd60e51b81526020600482015260146024820152731cdb1a5c1c1859d94e8818dbdb1b185d195c985b60621b6044820152606401610c87565b5f806128436109f5565b5091509150805f03612878575f61286461285c85613c1e565b610b4b61139e565b905061286f81612609565b61268f8161224e565b5f612883828461498e565b90505f848211612893575f61289d565b61289d858361498e565b90505f6128a982611461565b9150505f8185116128ba575f6128f8565b5f54612710906128da90600160281b90046001600160401b0316826149bc565b6128e4848861498e565b6128ee9190614941565b6128f89190614958565b90505f61290d61290889846149bc565b613c1e565b90508115801561291c57508015155b1561293e5761292a81612609565b6129338161224e565b505050505050505050565b60408051808201825260018152602080820184905291515f92612962929101614cbb565b60405160208183030381529060405290506129337f000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd368483613c5c565b5f81116129dc5760405162461bcd60e51b815260206004820152600c60248201526b085e995c9bc81c1c9bd99a5d60a21b6044820152606401610c87565b61ffff811115612a1a5760405162461bcd60e51b8152602060048201526009602482015268042e8dede40d0d2ced60bb1b6044820152606401610c87565b5f805461ffff9092166101000262ffff0019909216919091179055565b805f03612a415750565b6040805160a081018252600a546001600160a01b039081168252600b5481166020830152600c54811692820192909252600d549091166060820152600e5460808201525f908190612ab3907f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc9061346e565b9350935050505f612b1c612ac8858585613cf5565b610b4b6001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc167fcdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc306133bc565b6040516320b76e8160e01b81529091506001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906320b76e8190612b7290600a905f9086903090600401614cf2565b60408051808303815f875af1158015612b8d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bb19190614d38565b505050505050565b610ac681613788565b6001600160a01b03811615612cd257306001600160a01b0316816001600160a01b031663f7260d3e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c17573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c3b9190614d5a565b6001600160a01b031614612c825760405162461bcd60e51b815260206004820152600e60248201526d3bb937b733903932b1b2b4bb32b960911b6044820152606401610c87565b600954600160a01b900460ff16612cd2576009805460ff60a01b1916600160a01b1790556040516001907feefe960f8bad43dcec78179fc0f7c5df660581e221185a4bc5f126f87cd817e1905f90a25b600980546001600160a01b0319166001600160a01b0383169081179091556040517f4da9b3b7ca08b559bc11eb42bb6961e0813372ed0b55f0e9b68b76cf0207fce8905f90a250565b805f03612d255750565b6040516350d8cd4b60e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906350d8cd4b90612d7a90600a9085905f9030908190600401614d75565b60408051808303815f875af1158015612d95573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c249190614d38565b6127108110612df85760405162461bcd60e51b815260206004820152600b60248201526a085b1bdcdcc81b1a5b5a5d60aa1b6044820152606401610c87565b5f805461ffff90921663010000000264ffff00000019909216919091179055565b6009545f90600160a01b900460ff16612e6a5760405162461bcd60e51b815260206004820152601360248201527275736541756374696f6e2069732066616c736560681b6044820152606401610c87565b600954604051639f8a13d760e01b81526001600160a01b038481166004830152909116908190639f8a13d790602401602060405180830381865afa158015612eb4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ed891906149a1565b15612fad576040516310098ad560e01b81526001600160a01b0384811660048301525f91908316906310098ad590602401602060405180830381865afa158015612f24573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f489190614977565b1115612f5657505f92915050565b604051636a256b2960e01b81526001600160a01b038481166004830152821690636a256b29906024015f604051808303815f87803b158015612f96575f80fd5b505af1158015612fa8573d5f803e3d5ffd5b505050505b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa158015612ff1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130159190614977565b90508015613031576130316001600160a01b0385168383613d19565b6040516396c5517560e01b81526001600160a01b0385811660048301528316906396c55175906024016020604051808303815f875af1158015613076573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c889190614977565b805f036130a45750565b60405163238d657960e01b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc169063238d65799061266690600a9085903090600401614db1565b5f6130fe610e49565b9050801561318d57610b5561177b837f000000000000000000000000ff513347aea1734324b9e7852c685221cf899fa86001600160a01b03166301e1d1146040518163ffffffff1660e01b8152600401602060405180830381865afa158015613169573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b4b9190614977565b8115610b555761319f82610b4b61139e565b91506131aa82612609565b610c248261224e565b600c546040805163501ad8ff60e11b815290515f926001600160a01b03169163a035b1fe9160048083019260209291908290030181865afa158015611613573d5f803e3d5ffd5b5f815f0361320957505f919050565b604051635d043b2960e11b815260048101839052306024820181905260448201525f907f0000000000000000000000009a6bd7b6fd5c4f87eb66356441502fc7dcdd185b6001600160a01b03169063ba087652906064016020604051808303815f875af115801561327c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132a09190614977565b90506112cb7f0000000000000000000000002dca96907fde857dd3d816880a0df407eeb2d2f27f000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd36835f613d7c565b5f825f036132fd57505f612248565b5f826133115761330c846121b2565b61331a565b61331a84613c1e565b5f549091506127109061333d90600160281b90046001600160401b03168261498e565b6133479083614941565b611c889190614958565b5f82826020015161336291906149bc565b90505f61336e826127db565b90506133798161309a565b61338284612d1b565b50505050565b61339761188083610b4b610e49565b5f6133a88260200151610b4b61139e565b90506133b381612609565b6133828161224e565b5f806133d06133cb858561402e565b6140a1565b604051637784c68560e01b81529091506001600160a01b03861690637784c685906133ff908490600401614df1565b5f60405180830381865afa158015613419573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526134409190810190614e34565b5f8151811061345157613451614ec8565b60200260200101515f1c6001600160801b03169150509392505050565b5f805f805f61347e8660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa1580156134c6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134ea9190614edc565b90505f81608001516001600160801b031642613506919061498e565b90508015801590613523575060408201516001600160801b031615155b801561353b575060608801516001600160a01b031615155b15613730576060888101805160408051638c00bf6b60e01b81528c516001600160a01b0390811660048301526020808f015182166024840152838f0151821660448401529451811660648301526080808f0151608484015288516001600160801b0390811660a485015295890151861660c484015292880151851660e483015294870151841661010482015290860151831661012482015260a08601519092166101448301525f921690638c00bf6b9061016401602060405180830381865afa15801561360a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061362e9190614977565b90505f61365261363e83856140ea565b60408601516001600160801b031690614148565b905061365d8161415c565b8460400181815161366e9190614f78565b6001600160801b03169052506136838161415c565b84518590613692908390614f78565b6001600160801b0390811690915260a08601511615905061372d575f6136ce8560a001516001600160801b03168361414890919063ffffffff16565b90505f61370282875f01516001600160801b03166136ec919061498e565b60208801518491906001600160801b0316613cf5565b905061370d8161415c565b8660200181815161371e9190614f78565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f611c886137736001856149bc565b613780620f4240856149bc565b8691906141b8565b5f806137926109f5565b5090925090505f836137a4838561498e565b6137ae91906149bc565b90505f6137ba82611461565b91505082811115613851575f6137d0848361498e565b905060065481116137ea57612bb161188087610b4b610e49565b6040805180820182525f80825260208083018a90529251909261380e929101614cbb565b604051602081830303815290604052905061384a7f000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd368383613c5c565b505061268f565b80831115613970575f613864828561498e565b905080861061389e5761387681612a37565b5f613881828861498e565b9050801561389557613895611f1c826127db565b50505050505050565b6138a786612a37565b6138b1868261498e565b5f805491925090612710906138d690600160281b90046001600160401b0316826149bc565b6138df84613c1e565b6138e99190614941565b6138f39190614958565b90505f604051806040016040528060018081111561391357613913614c35565b81526020018381525060405160200161392c9190614cbb565b60405160208183030381529060405290506139687f000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd368483613c5c565b50505061268f565b61268f61188086610b4b610e49565b6040516349e2903160e11b81527fcdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc60048201523060248201525f9081906001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc16906393c5206290604401606060405180830381865afa158015613a0b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a2f9190614a29565b905080602001516001600160801b03165f03613a4c575f91505090565b5f6ec097ce7bc90715b34b9f1000000000600a6002015f9054906101000a90046001600160a01b03166001600160a01b031663a035b1fe6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613ab0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ad49190614977565b83604001516001600160801b0316613aec9190614941565b613af69190614958565b90505f670de0b6b3a7640000600a6004015483613b139190614941565b613b1d9190614958565b905080613b28610e49565b11935050505090565b5f815f03613b4057505f919050565b5f613b8d7f000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd367f0000000000000000000000002dca96907fde857dd3d816880a0df407eeb2d2f2855f613d7c565b604051636e553f6560e01b8152600481018290523060248201529091507f0000000000000000000000009a6bd7b6fd5c4f87eb66356441502fc7dcdd185b6001600160a01b031690636e553f65906044016020604051808303815f875af1158015613bfa573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112cb9190614977565b5f815f03613c2d57505f919050565b5f613c366131b3565b905080613c526ec097ce7bc90715b34b9f100000000085614941565b6112cb9190614958565b600f805460ff1916600117905560405163701195a160e11b81526001600160a01b037f000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc169063e0232b4290613cb990869086908690600401614f9f565b5f604051808303815f87803b158015613cd0575f80fd5b505af1158015613ce2573d5f803e3d5ffd5b5050600f805460ff191690555050505050565b5f611c88613d06620f4240846149bc565b613d116001866149bc565b8691906141d9565b6040516001600160a01b038316602482015260448101829052610c2490849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526141e5565b5f8215801590613d8e57506008548310155b15611c8857601054613daa906001600160a01b031686856142b8565b600f546001600160a01b03868116610100909204161480613ddd5750600f546001600160a01b0385811661010090920416145b15613ef35760408051610100810182526001600160a01b0387811680835287821660208085018281525f938452601182528684209284529190528482205462ffffff9081168587019081523060608701908152426080880190815260a088018c815260c089018c815260e08a019788526010549a5163414bf38960e01b81528a518a16600482015296518916602488015293519094166044860152905186166064850152516084840152905160a48301525160c48201529051821660e48201529192169063414bf38990610104016020604051808303815f875af1158015613ec7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613eeb9190614977565b915050611c88565b6001600160a01b038581165f908152601160208181526040808420600f5461010090048087168652908352818520549383528185208a8716865283529381902054815160608c811b6bffffffffffffffffffffffff199081169583019590955260e895861b6001600160e81b0319908116603484015296811b851660378301529190941b909416604b8401529288901b16604e8201528151604281830301815260105461010283018452606283018281523060828501524260a285015260c2840189905260e2909301879052925163c04b8d5960e01b81529093929092169163c04b8d5991613fe491600401614fc5565b6020604051808303815f875af1158015614000573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906140249190614977565b9695505050505050565b5f60018284600260405160200161404f929190918252602082015260400190565b60408051601f1981840301815282825280516020918201206001600160a01b0390941690830152810191909152606001604051602081830303815290604052805190602001205f1c61224591906149bc565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f815181106140d9576140d9614ec8565b602090810291909101015292915050565b5f806140f68385614941565b90505f6141168280614111670de0b6b3a76400006002614941565b6141d9565b90505f6141318284614111670de0b6b3a76400006003614941565b90508061413e83856149bc565b61402491906149bc565b5f6122458383670de0b6b3a76400006141d9565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b038311156141b15760405162461bcd60e51b8152600401610c87919061501c565b5090919050565b5f816141c560018261498e565b6141cf8587614941565b61334791906149bc565b5f816133478486614941565b5f614239826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166143579092919063ffffffff16565b905080515f148061425957508080602001905181019061425991906149a1565b610c245760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610c87565b604051636eb1769f60e11b81523060048201526001600160a01b03848116602483015282919084169063dd62ed3e90604401602060405180830381865afa158015614305573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906143299190614977565b1015610c24576143436001600160a01b038316845f614365565b610c246001600160a01b0383168483614365565b6060611c8884845f856143f3565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526143b684826144ca565b613382576040516001600160a01b03841660248201525f60448201526143e990859063095ea7b360e01b90606401613d45565b61338284826141e5565b6060824710156144545760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610c87565b5f80866001600160a01b0316858760405161446f919061502e565b5f6040518083038185875af1925050503d805f81146144a9576040519150601f19603f3d011682016040523d82523d5f602084013e6144ae565b606091505b50915091506144bf8783838761456b565b979650505050505050565b5f805f846001600160a01b0316846040516144e5919061502e565b5f604051808303815f865af19150503d805f811461451e576040519150601f19603f3d011682016040523d82523d5f602084013e614523565b606091505b509150915081801561454d57508051158061454d57508080602001905181019061454d91906149a1565b801561456257506001600160a01b0385163b15155b95945050505050565b606083156145d95782515f036145d2576001600160a01b0385163b6145d25760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610c87565b5081611c88565b611c8883838151156145ee5781518083602001fd5b8060405162461bcd60e51b8152600401610c87919061501c565b6001600160a01b0381168114610ac6575f80fd5b5f6020828403121561462c575f80fd5b81356112cb81614608565b5f60208284031215614647575f80fd5b5035919050565b8015158114610ac6575f80fd5b5f6020828403121561466b575f80fd5b81356112cb8161464e565b5f805f60608486031215614688575f80fd5b833561469381614608565b925060208401356146a381614608565b9150604084013562ffffff811681146146ba575f80fd5b809150509250925092565b5f805f604084860312156146d7575f80fd5b8335925060208401356001600160401b03808211156146f4575f80fd5b818601915086601f830112614707575f80fd5b813581811115614715575f80fd5b876020828501011115614726575f80fd5b6020830194508093505050509250925092565b5f5b8381101561475357818101518382015260200161473b565b50505f910152565b5f8151808452614772816020860160208601614739565b601f01601f19169290920160200192915050565b8215158152604060208201525f611c88604083018461475b565b5f80604083850312156147b1575f80fd5b82356147bc81614608565b915060208301356147cc8161464e565b809150509250929050565b5f8083601f8401126147e7575f80fd5b5081356001600160401b038111156147fd575f80fd5b6020830191508360208260051b8501011115614817575f80fd5b9250929050565b5f805f805f805f806080898b031215614835575f80fd5b88356001600160401b038082111561484b575f80fd5b6148578c838d016147d7565b909a50985060208b013591508082111561486f575f80fd5b61487b8c838d016147d7565b909850965060408b0135915080821115614893575f80fd5b61489f8c838d016147d7565b909650945060608b01359150808211156148b7575f80fd5b506148c48b828c016147d7565b999c989b5096995094979396929594505050565b5f80604083850312156148e9575f80fd5b82356148f481614608565b915060208301356147cc81614608565b5f805f60608486031215614916575f80fd5b505081359360208301359350604090920135919050565b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176122485761224861492d565b5f8261497257634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215614987575f80fd5b5051919050565b818103818111156122485761224861492d565b5f602082840312156149b1575f80fd5b81516112cb8161464e565b808201808211156122485761224861492d565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f191681016001600160401b0381118282101715614a0b57614a0b6149cf565b604052919050565b80516001600160801b0381168114611e95575f80fd5b5f60608284031215614a39575f80fd5b604051606081018181106001600160401b0382111715614a5b57614a5b6149cf565b60405282518152614a6e60208401614a13565b6020820152614a7f60408401614a13565b60408201529392505050565b8183525f60208085019450825f5b85811015614ac7578135614aac81614608565b6001600160a01b031687529582019590820190600101614a99565b509495945050505050565b8183525f6001600160fb1b03831115614ae9575f80fd5b8260051b80836020870137939093016020019392505050565b608081525f614b15608083018a8c614a8b565b602083820381850152614b29828a8c614a8b565b91508382036040850152614b3e82888a614ad2565b84810360608601528581529150808201600586811b84018301885f5b89811015614bc857868303601f190185528135368c9003601e19018112614b7f575f80fd5b8b0186810190356001600160401b03811115614b99575f80fd5b80861b3603821315614ba9575f80fd5b614bb4858284614ad2565b968801969450505090850190600101614b5a565b50909f9e505050505050505050505050505050565b5f60408284031215614bed575f80fd5b604051604081018181106001600160401b0382111715614c0f57614c0f6149cf565b604052825160028110614c20575f80fd5b81526020928301519281019290925250919050565b634e487b7160e01b5f52602160045260245ffd5b80546001600160a01b039081168352600182015481166020840152600282015481166040840152600382015416606083015260040154608090910152565b6101008101614c968287614c49565b60a08201949094526001600160a01b0392831660c0820152911660e090910152919050565b8151604082019060028110614cde57634e487b7160e01b5f52602160045260245ffd5b808352506020830151602083015292915050565b5f610120614d008388614c49565b60a08301959095525060c08101929092526001600160a01b031660e082015261010081018290525f9181019190915261014001919050565b5f8060408385031215614d49575f80fd5b505080516020909101519092909150565b5f60208284031215614d6a575f80fd5b81516112cb81614608565b6101208101614d848288614c49565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b5f610100614dbf8387614c49565b60a0830194909452506001600160a01b039190911660c082015260e081018290525f9181019190915261012001919050565b602080825282518282018190525f9190848201906040850190845b81811015614e2857835183529284019291840191600101614e0c565b50909695505050505050565b5f6020808385031215614e45575f80fd5b82516001600160401b0380821115614e5b575f80fd5b818501915085601f830112614e6e575f80fd5b815181811115614e8057614e806149cf565b8060051b9150614e918483016149e3565b8181529183018401918481019088841115614eaa575f80fd5b938501935b838510156110ac57845182529385019390850190614eaf565b634e487b7160e01b5f52603260045260245ffd5b5f60c08284031215614eec575f80fd5b60405160c081018181106001600160401b0382111715614f0e57614f0e6149cf565b604052614f1a83614a13565b8152614f2860208401614a13565b6020820152614f3960408401614a13565b6040820152614f4a60608401614a13565b6060820152614f5b60808401614a13565b6080820152614f6c60a08401614a13565b60a08201529392505050565b6001600160801b03818116838216019080821115614f9857614f9861492d565b5092915050565b60018060a01b0384168152826020820152606060408201525f614562606083018461475b565b602081525f825160a06020840152614fe060c084018261475b565b905060018060a01b0360208501511660408401526040840151606084015260608401516080840152608084015160a08401528091505092915050565b602081525f612245602083018461475b565b5f825161503f818460208701614739565b919091019291505056fea2646970667358221220b660661ed134c773b56916c9a6d4e39e22e29405e3df2e9f33a41afd4f2f3a4364736f6c63430008170033

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

000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd3600000000000000000000000000000000000000000000000000000000000000c00000000000000000000000009a6bd7b6fd5c4f87eb66356441502fc7dcdd185b000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abccdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc0000000000000000000000004e1d81a3e627b9294532e990109e4c21d217376c00000000000000000000000000000000000000000000000000000000000000197976555344542f55534443204d6f7270686f204c6f6f70657200000000000000

-----Decoded View---------------
Arg [0] : _asset (address): 0x203A662b0BD271A6ed5a60EdFbd04bFce608FD36
Arg [1] : _name (string): yvUSDT/USDC Morpho Looper
Arg [2] : _collateralToken (address): 0x9A6bd7B6Fd5C4F87eb66356441502fc7dCdd185B
Arg [3] : _morpho (address): 0xD50F2DffFd62f94Ee4AEd9ca05C61d0753268aBc
Arg [4] : _marketId (bytes32): 0xcdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc
Arg [5] : _router (address): 0x4e1d81A3E627b9294532e990109e4c21d217376C

-----Encoded View---------------
8 Constructor Arguments found :
Arg [0] : 000000000000000000000000203a662b0bd271a6ed5a60edfbd04bfce608fd36
Arg [1] : 00000000000000000000000000000000000000000000000000000000000000c0
Arg [2] : 0000000000000000000000009a6bd7b6fd5c4f87eb66356441502fc7dcdd185b
Arg [3] : 000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc
Arg [4] : cdaf57d98c2f75bffb8f0d3f7aa79bbacda4a479c47e316aab14af1ca6d85ffc
Arg [5] : 0000000000000000000000004e1d81a3e627b9294532e990109e4c21d217376c
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000019
Arg [7] : 7976555344542f55534443204d6f7270686f204c6f6f70657200000000000000


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.