// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../utils/Context.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

// File: @openzeppelin/contracts/math/SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

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

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

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

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

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a % b;
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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 `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool);

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

// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "./IERC20.sol";
import "../../math/SafeMath.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 SafeMath for uint256;
    using Address for address;

    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    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'
        // solhint-disable-next-line max-line-length
        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));
    }

    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    /**
     * @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");
        if (returndata.length > 0) { // Return data is optional
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

// File: @openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @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
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 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://diligence.consensys.net/posts/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.5.11/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");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (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 functionCall(target, data, "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");
        require(isContract(target), "Address: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(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) {
        require(isContract(target), "Address: static call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(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) {
        require(isContract(target), "Address: delegate call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // 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

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <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 GSN 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 payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: contracts/common/ERC4626/IERC4626.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

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

import "../../interfaces/IERC20Metadata.sol";

// Copy from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/interfaces/IERC4626.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);
}

// File: contracts/helpers/converter/ConverterBase.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

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

import { IWETH } from "../../interfaces/IWETH.sol";
import { ITokenConverter } from "./ITokenConverter.sol";

abstract contract ConverterBase is ITokenConverter {
  using SafeERC20 for IERC20;

  /*************
   * Constants *
   *************/

  /// @inheritdoc ITokenConverter
  address public immutable override registry;

  /// @dev The address of ETH which is commonly used.
  address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

  /// @dev The address of WETH token.
  address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

  /***************
   * Constructor *
   ***************/

  constructor(address _registry) {
    registry = _registry;
  }

  /****************************
   * Public Mutated Functions *
   ****************************/

  // solhint-disable-next-line no-empty-blocks
  receive() external payable {}

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @inheritdoc ITokenConverter
  function withdrawFund(address _token, address _recipient) external override {
    require(msg.sender == registry, "only registry");

    if (_token == address(0)) {
      (bool success, ) = _recipient.call{ value: address(this).balance }("");
      require(success, "withdraw ETH failed");
    } else {
      IERC20(_token).safeTransfer(_recipient, IERC20(_token).balanceOf(address(this)));
    }
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to get the pool type of the route.
  /// @param encoding The route encoding.
  function _getPoolType(uint256 encoding) internal pure returns (uint256) {
    return encoding & 255;
  }

  /// @dev Internal function to get the action of the route.
  /// @param encoding The route encoding.
  function _getAction(uint256 encoding) internal pure returns (uint256) {
    return (encoding >> 8) & 3;
  }

  function _isETH(address _token) internal pure returns (bool) {
    return _token == ETH || _token == address(0);
  }

  function _wrapTokenIfNeeded(address _token, uint256 _amount) internal {
    if (_token == WETH && IERC20(_token).balanceOf(address(this)) < _amount) {
      IWETH(_token).deposit{ value: _amount }();
    }
  }

  function _unwrapIfNeeded(uint256 _amount) internal {
    if (address(this).balance < _amount) {
      IWETH(WETH).withdraw(_amount);
    }
  }

  function _approve(
    address _token,
    address _spender,
    uint256 _amount
  ) internal {
    if (!_isETH(_token) && IERC20(_token).allowance(address(this), _spender) < _amount) {
      // hBTC cannot approve 0
      if (_token != 0x0316EB71485b0Ab14103307bf65a021042c6d380) {
        IERC20(_token).safeApprove(_spender, 0);
      }
      IERC20(_token).safeApprove(_spender, uint256(-1));
    }
  }
}

// File: contracts/helpers/converter/GeneralTokenConverter.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;
pragma abicoder v2;

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

import { IConverterRegistry } from "./IConverterRegistry.sol";
import { ITokenConverter } from "./ITokenConverter.sol";

import { IERC4626 } from "../../common/ERC4626/IERC4626.sol";
import { IBalancerPool } from "../../interfaces/IBalancerPool.sol";
import { IBalancerV1Pool } from "../../interfaces/IBalancerV1Pool.sol";
import { IBalancerVault } from "../../interfaces/IBalancerVault.sol";
import { ICurveAPool } from "../../interfaces/ICurveAPool.sol";
import { ICurvePlainPool } from "../../interfaces/ICurvePlainPool.sol";
import { ICurveYPoolSwap, ICurveYPoolDeposit } from "../../interfaces/ICurveYPool.sol";
import { ICurveMetaPoolSwap } from "../../interfaces/ICurveMetaPool.sol";
import { ICurveCryptoPool } from "../../interfaces/ICurveCryptoPool.sol";
import { ICurveTriCryptoPool } from "../../interfaces/ICurveCryptoPool.sol";
import { IUniswapV2Pair } from "../../interfaces/IUniswapV2Pair.sol";
import { IUniswapV3Pool } from "../../interfaces/IUniswapV3Pool.sol";
import { IUniswapV3Router } from "../../interfaces/IUniswapV3Router.sol";
import { IUniswapV3Quoter } from "../../interfaces/IUniswapV3Quoter.sol";
import { IWETH } from "../../interfaces/IWETH.sol";

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

// solhint-disable no-empty-blocks
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// solhint-disable var-name-mixedcase

/// @title GeneralTokenConverter
/// @notice This implements token converting for `pool_type` from 0 to 9 (both inclusive).
/// For other types, it will retrieve the implementation from
/// `ConverterRegistry` contract and delegate call.
contract GeneralTokenConverter is Ownable, ConverterBase {
  using SafeERC20 for IERC20;

  /*************
   * Constants *
   *************/

  /// @dev The address of Balancer V2 Vault
  address private constant BALANCER_VAULT = 0xBA12222222228d8Ba445958a75a0704d566BF2C8;

  /// @dev The address of Uniswap V3 Router
  address private constant UNISWAP_V3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;

  /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
  uint160 private constant MIN_SQRT_RATIO = 4295128739;

  /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
  uint160 private constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

  /*************
   * Variables *
   *************/

  /// @notice The mask of supported pool types.
  /// @dev If the `i`-th bit is `1`, the `i`-th pool type is supported in this contract.
  uint256 public supportedPoolTypes;

  /// @notice Mapping from token address to token minter.
  /// @dev It is used to determine the pool address for lp token address.
  mapping(address => address) public tokenMinter;

  /// @dev Execution context used in fallback function.
  uint256 private context;

  /***************
   * Constructor *
   ***************/

  constructor(address _registry) ConverterBase(_registry) {
    supportedPoolTypes = 1023;

    // setup 3pool, compound, susd
    tokenMinter[0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490] = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
    tokenMinter[0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2] = 0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56;
    tokenMinter[0xC25a3A3b969415c80451098fa907EC722572917F] = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD;
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @inheritdoc ITokenConverter
  function getTokenPair(uint256 _route) external view override returns (address, address) {
    uint256 _poolType = _route & 255;
    uint256 _action = (_route >> 8) & 3;

    return _getTokenPair(_poolType, _action, _route >> 10);
  }

  /// @inheritdoc ITokenConverter
  function queryConvert(uint256 _encoding, uint256 _amountIn) external override returns (uint256 _amountOut) {
    uint256 _poolType = _encoding & 255;
    uint256 _action = (_encoding >> 8) & 3;

    if (((supportedPoolTypes >> _poolType) & 1) == 1) {
      _encoding = _encoding >> 10;
      if (_action == 0) _amountOut = _querySwap(_poolType, _encoding, _amountIn);
      else if (_action == 1) _amountOut = _queryWrap(_poolType, _encoding, _amountIn);
      else if (_action == 2) _amountOut = _queryUnwrap(_poolType, _encoding, _amountIn);
      else revert("invalid action");
    } else {
      address _converter = IConverterRegistry(registry).getConverter(_poolType);
      _amountOut = ITokenConverter(_converter).queryConvert(_encoding, _amountIn);
    }
  }

  /****************************
   * Public Mutated Functions *
   ****************************/

  // solhint-disable-next-line no-complex-fallback
  fallback() external payable {
    uint256 _context = context;
    if (address(_context) == _msgSender() || _context == 1) {
      // handle uniswap v3 swap callback or uniswap v3 quote callback
      // | 4 bytes |   32 bytes   |   32 bytes   |   32 bytes  |   32 bytes  | 32 bytes |
      // |   sig   | amount0Delta | amount1Delta | data.offset | data.length |  tokenIn |
      int256 amount0Delta;
      int256 amount1Delta;
      address tokenIn;
      assembly {
        amount0Delta := calldataload(4)
        amount1Delta := calldataload(36)
        tokenIn := calldataload(132)
      }
      (uint256 amountToPay, uint256 amountReceived) = amount0Delta > 0
        ? (uint256(amount0Delta), uint256(-amount1Delta))
        : (uint256(amount1Delta), uint256(-amount0Delta));
      if (_context == 1) {
        assembly {
          let ptr := mload(0x40)
          mstore(ptr, amountReceived)
          revert(ptr, 32)
        }
      } else {
        IERC20(tokenIn).safeTransfer(address(_context), amountToPay);
      }
    } else {
      revert("invalid call");
    }
  }

  /// @inheritdoc ITokenConverter
  function convert(
    uint256 _encoding,
    uint256 _amountIn,
    address _recipient
  ) external payable override returns (uint256 _amountOut) {
    uint256 _poolType = _encoding & 255;
    uint256 _action = (_encoding >> 8) & 3;

    if (((supportedPoolTypes >> _poolType) & 1) == 1) {
      _encoding = _encoding >> 10;
      if (_action == 0) _amountOut = _swap(_poolType, _encoding, _amountIn, _recipient);
      else if (_action == 1) _amountOut = _wrap(_poolType, _encoding, _amountIn, _recipient);
      else if (_action == 2) _amountOut = _unwrap(_poolType, _encoding, _amountIn, _recipient);
      else revert("invalid action");
    } else {
      address _converter = IConverterRegistry(registry).getConverter(_poolType);
      // solhint-disable-next-line avoid-low-level-calls
      (bool _success, bytes memory _result) = _converter.delegatecall(
        abi.encodeWithSelector(ITokenConverter.convert.selector, _encoding, _amountIn, _recipient)
      );
      // below lines will propagate inner error up
      if (!_success) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
          let ptr := mload(0x40)
          let size := returndatasize()
          returndatacopy(ptr, 0, size)
          revert(ptr, size)
        }
      }
      _amountOut = abi.decode(_result, (uint256));
    }
  }

  /*******************************
   * Public Restricted Functions *
   *******************************/

  /// @notice Update the pool types supported by this contract by default.
  /// @param _supportedPoolTypes The mask of pool types supported.
  function updateSupportedPoolTypes(uint256 _supportedPoolTypes) external onlyOwner {
    supportedPoolTypes = _supportedPoolTypes;
  }

  /// @notice Update the token minter mapping.
  /// @param _tokens The address list of tokens to update.
  /// @param _minters The address list of corresponding minters.
  function updateTokenMinter(address[] memory _tokens, address[] memory _minters) external onlyOwner {
    for (uint256 i = 0; i < _tokens.length; i++) {
      tokenMinter[_tokens[i]] = _minters[i];
    }
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to find token pair based on route encoding.
  /// @param _poolType The type of the route.
  /// @param _action The action of the route.
  /// @param _encoding The customized encoding of the route.
  /// @return _tokenIn The address of input token.
  /// @return _tokenOut The address of output token.
  function _getTokenPair(
    uint256 _poolType,
    uint256 _action,
    uint256 _encoding
  ) internal view returns (address _tokenIn, address _tokenOut) {
    address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975);

    if (_action == 0) {
      // swap
      if (_poolType <= 1) {
        // UniswapV2 or UniswapV3
        _tokenIn = IUniswapV2Pair(_pool).token0();
        _tokenOut = IUniswapV2Pair(_pool).token1();
        uint256 zero_for_one = (_encoding >> 184) & 1;
        if (zero_for_one == 0) {
          (_tokenIn, _tokenOut) = (_tokenOut, _tokenIn);
        }
      } else if (_poolType == 2) {
        // BalancerV1
        address[] memory _tokens = IBalancerV1Pool(_pool).getCurrentTokens();
        _tokenIn = _tokens[(_encoding >> 163) & 7];
        _tokenOut = _tokens[(_encoding >> 166) & 7];
      } else if (_poolType == 3) {
        // BalancerV2
        bytes32 _poolId = IBalancerPool(_pool).getPoolId();
        (address[] memory _tokens, , ) = IBalancerVault(BALANCER_VAULT).getPoolTokens(_poolId);
        _tokenIn = _tokens[(_encoding >> 163) & 7];
        _tokenOut = _tokens[(_encoding >> 166) & 7];
      } else if (_poolType <= 8) {
        // Curve
        _tokenIn = _getCurveTokenByIndex(_pool, _poolType, (_encoding >> 163) & 7, _encoding);
        _tokenOut = _getCurveTokenByIndex(_pool, _poolType, (_encoding >> 166) & 7, _encoding);
      }
    } else if (_action == 1) {
      _tokenOut = _pool;
      if (4 <= _poolType && _poolType <= 8) {
        if (_poolType == 6 && (((_encoding >> 169) & 1) == 1)) {
          _tokenOut = ICurveYPoolDeposit(_pool).token();
        } else {
          _pool = _getTokenMinter(_pool);
        }
        _tokenIn = _getCurveTokenByIndex(_pool, _poolType, (_encoding >> 163) & 7, _encoding);
      } else if (_poolType == 9) {
        _tokenIn = IERC4626(_pool).asset();
      } else {
        _tokenOut = address(0);
      }
    } else if (_action == 2) {
      _tokenIn = _pool;
      if (4 <= _poolType && _poolType <= 8) {
        if (_poolType == 6 && (((_encoding >> 169) & 1) == 1)) {
          _tokenIn = ICurveYPoolDeposit(_pool).token();
        } else {
          _pool = _getTokenMinter(_pool);
        }
        _tokenOut = _getCurveTokenByIndex(_pool, _poolType, (_encoding >> 166) & 7, _encoding);
      } else if (_poolType == 9) {
        _tokenOut = IERC4626(_pool).asset();
      } else {
        _tokenIn = address(0);
      }
    }
    if (_tokenIn == ETH) _tokenIn = WETH;
    if (_tokenOut == ETH) _tokenOut = WETH;
  }

  /// @dev Internal function to return the minter for curve lp token.
  /// @param _token The address of token.
  /// @return _minter The address of minter for the token.
  function _getTokenMinter(address _token) internal view returns (address _minter) {
    _minter = tokenMinter[_token];
    if (_minter == address(0)) {
      // solhint-disable-next-line no-inline-assembly
      assembly {
        // keccack("minter()")
        mstore(0x00, 0x0754617200000000000000000000000000000000000000000000000000000000)
        let success := staticcall(gas(), _token, 0x00, 0x04, 0x00, 0x20)
        if success {
          _minter := and(mload(0x00), 0xffffffffffffffffffffffffffffffffffffffff)
        }
        if iszero(_minter) {
          _minter := _token
        }
      }
    }
  }

  /// @dev Internal function to get the curve token by index.
  /// @param _poolType The pool type.
  /// @param _index The index of the token.
  /// @param _encoding The customized encoding of the route.
  /// @return _token The address of the token.
  function _getCurveTokenByIndex(
    address _pool,
    uint256 _poolType,
    uint256 _index,
    uint256 _encoding
  ) internal view returns (address _token) {
    if ((_poolType == 5 || _poolType == 6) && (((_encoding >> 169) & 1) == 1)) {
      if (_poolType == 5) {
        _token = ICurveAPool(_pool).underlying_coins(_index);
      } else {
        _token = ICurveYPoolSwap(_pool).underlying_coins(int128(_index));
      }
    } else {
      try ICurvePlainPool(_pool).coins(_index) returns (address result) {
        _token = result;
      } catch {
        _token = ICurvePlainPool(_pool).coins(int128(_index));
      }
    }
  }

  /*************************************
   * Internal Functions for Token Swap *
   *************************************/

  /// @dev Query the amount of output token by swapping.
  /// @param _poolType The pool type.
  /// @param _encoding The customized encoding of the route.
  /// @param _amountIn The amount of input token.
  /// @return _amountOut The amount of output token.
  function _querySwap(
    uint256 _poolType,
    uint256 _encoding,
    uint256 _amountIn
  ) internal returns (uint256 _amountOut) {
    (address _tokenIn, address _tokenOut) = _getTokenPair(_poolType, 0, _encoding);
    address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975);
    if (_poolType == 0) {
      if (((_encoding >> 185) & 1) == 1) {
        IUniswapV2Pair(_pool).executeVirtualOrders(block.timestamp);
      }
      uint256 zero_for_one = (_encoding >> 184) & 1;
      (uint256 rIn, uint256 rOut, ) = IUniswapV2Pair(_pool).getReserves();
      if (zero_for_one == 0) {
        (rIn, rOut) = (rOut, rIn);
      }
      // We won't handle fee on transfer token here.
      _amountOut = _amountIn * ((_encoding >> 160) & 16777215);
      _amountOut = (_amountOut * rOut) / (rIn * 1000000 + _amountOut);
    } else if (_poolType == 1) {
      bool zeroForOne = _tokenIn < _tokenOut;
      context = 1;
      try
        IUniswapV3Pool(_pool).swap(
          address(this),
          zeroForOne,
          int256(_amountIn),
          (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1),
          new bytes(0)
        )
      {} catch (bytes memory reason) {
        _amountOut = abi.decode(reason, (uint256));
      }
      context = 0;
    } else if (_poolType == 2) {
      _amountOut = IBalancerV1Pool(_pool).calcOutGivenIn(
        IBalancerV1Pool(_pool).getBalance(_tokenIn),
        IBalancerV1Pool(_pool).getDenormalizedWeight(_tokenIn),
        IBalancerV1Pool(_pool).getBalance(_tokenOut),
        IBalancerV1Pool(_pool).getDenormalizedWeight(_tokenOut),
        _amountIn,
        IBalancerV1Pool(_pool).getSwapFee()
      );
    } else if (_poolType == 3) {
      address[] memory _assets = new address[](2);
      _assets[0] = _tokenIn;
      _assets[1] = _tokenOut;
      IBalancerVault.BatchSwapStep[] memory _swaps = new IBalancerVault.BatchSwapStep[](1);
      _swaps[0] = IBalancerVault.BatchSwapStep({
        poolId: IBalancerPool(_pool).getPoolId(),
        assetInIndex: 0,
        assetOutIndex: 1,
        amount: _amountIn,
        userData: new bytes(0)
      });
      int256[] memory _deltas = IBalancerVault(BALANCER_VAULT).queryBatchSwap(
        IBalancerVault.SwapKind.GIVEN_IN,
        _swaps,
        _assets,
        IBalancerVault.FundManagement({
          sender: address(this),
          fromInternalBalance: false,
          recipient: payable(address(this)),
          toInternalBalance: false
        })
      );
      _amountOut = uint256(-_deltas[1]);
    } else if (_poolType <= 8) {
      uint256 indexIn = (_encoding >> 163) & 7;
      uint256 indexOut = (_encoding >> 166) & 7;
      if (_poolType == 8) {
        _amountOut = ICurveCryptoPool(_pool).get_dy(indexIn, indexOut, _amountIn);
      } else if (_poolType == 5 && ((_encoding >> 169) & 1) == 1) {
        _amountOut = ICurveAPool(_pool).get_dy_underlying(int128(indexIn), int128(indexOut), _amountIn);
      } else if (_poolType == 6 && ((_encoding >> 169) & 1) == 1) {
        _pool = ICurveYPoolDeposit(_pool).curve();
        _amountOut = ICurveYPoolSwap(_pool).get_dy_underlying(int128(indexIn), int128(indexOut), _amountIn);
      } else {
        _amountOut = ICurvePlainPool(_pool).get_dy(int128(indexIn), int128(indexOut), _amountIn);
      }
    }
  }

  /// @dev Swap from one token to another token.
  /// @param _poolType The pool type.
  /// @param _encoding The customized encoding of the route.
  /// @param _amountIn The amount of input token.
  /// @param _recipient The address of output token receiver.
  /// @return _amountOut The amount of output token.
  function _swap(
    uint256 _poolType,
    uint256 _encoding,
    uint256 _amountIn,
    address _recipient
  ) internal returns (uint256 _amountOut) {
    (address _tokenIn, address _tokenOut) = _getTokenPair(_poolType, 0, _encoding);
    address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975);

    if ((_poolType == 4 || _poolType == 8) && ((_encoding >> 169) & 1) == 1) {
      // tokenIn is (W)ETH and we are going to use ETH.
      _unwrapIfNeeded(_amountIn);
    } else {
      _wrapTokenIfNeeded(_tokenIn, _amountIn);
    }

    uint256 _balanceBefore = IERC20(_tokenOut).balanceOf(address(this));
    if (_poolType == 0) {
      // Uniswap V2
      if (((_encoding >> 185) & 1) == 1) {
        IUniswapV2Pair(_pool).executeVirtualOrders(block.timestamp);
      }
      uint256 zero_for_one = (_encoding >> 184) & 1;
      (uint256 rIn, uint256 rOut, ) = IUniswapV2Pair(_pool).getReserves();
      if (zero_for_one == 0) {
        (rIn, rOut) = (rOut, rIn);
      }

      // We won't handle fee on transfer token here.
      _amountOut = _amountIn * ((_encoding >> 160) & 16777215);
      _amountOut = (_amountOut * rOut) / (rIn * 1000000 + _amountOut);

      IERC20(_tokenIn).safeTransfer(_pool, _amountIn);
      if (zero_for_one == 1) {
        IUniswapV2Pair(_pool).swap(0, _amountOut, _recipient, new bytes(0));
      } else {
        IUniswapV2Pair(_pool).swap(_amountOut, 0, _recipient, new bytes(0));
      }
      return _amountOut;
    } else if (_poolType == 1) {
      // UniswapV3
      bool zeroForOne = _tokenIn < _tokenOut;
      bytes memory _data = new bytes(32);
      assembly {
        mstore(add(_data, 0x20), _tokenIn)
      }
      context = uint256(_pool);
      (int256 amount0, int256 amount1) = IUniswapV3Pool(_pool).swap(
        _recipient,
        zeroForOne,
        int256(_amountIn),
        (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1),
        _data
      );
      context = 0;
      return zeroForOne ? uint256(-amount1) : uint256(amount0);
    } else if (_poolType == 2) {
      // BalancerV1
      _approve(_tokenIn, _pool, _amountIn);
      (_amountOut, ) = IBalancerV1Pool(_pool).swapExactAmountIn(_tokenIn, _amountIn, _tokenOut, 0, uint256(-1));
    } else if (_poolType == 3) {
      bytes32 _poolId = IBalancerPool(_pool).getPoolId();
      _wrapTokenIfNeeded(_tokenIn, _amountIn);
      _approve(_tokenIn, BALANCER_VAULT, _amountIn);
      return
        IBalancerVault(BALANCER_VAULT).swap(
          IBalancerVault.SingleSwap({
            poolId: _poolId,
            kind: IBalancerVault.SwapKind.GIVEN_IN,
            assetIn: _tokenIn,
            assetOut: _tokenOut,
            amount: _amountIn,
            userData: new bytes(0)
          }),
          IBalancerVault.FundManagement({
            sender: address(this),
            fromInternalBalance: false,
            recipient: payable(_recipient),
            toInternalBalance: false
          }),
          0,
          // solhint-disable-next-line not-rely-on-time
          block.timestamp
        );
    } else if (_poolType <= 8) {
      uint256 indexIn = (_encoding >> 163) & 7;
      uint256 indexOut = (_encoding >> 166) & 7;
      _approve(_tokenIn, _pool, _amountIn);
      if (_poolType == 4) {
        if (((_encoding >> 169) & 1) == 0) {
          _approve(_tokenIn, _pool, _amountIn);
          ICurvePlainPool(_pool).exchange(int128(indexIn), int128(indexOut), _amountIn, 0);
        } else {
          ICurvePlainPool(_pool).exchange{ value: _amountIn }(int128(indexIn), int128(indexOut), _amountIn, 0);
        }
      } else if (_poolType == 5) {
        _approve(_tokenIn, _pool, _amountIn);
        if (((_encoding >> 169) & 1) == 0) {
          ICurveAPool(_pool).exchange(int128(indexIn), int128(indexOut), _amountIn, 0);
        } else {
          ICurveAPool(_pool).exchange_underlying(int128(indexIn), int128(indexOut), _amountIn, 0);
        }
      } else if (_poolType == 6) {
        if (((_encoding >> 169) & 1) == 1) {
          _pool = ICurveYPoolDeposit(_pool).curve();
        }
        _approve(_tokenIn, _pool, _amountIn);
        if (((_encoding >> 169) & 1) == 0) {
          ICurveYPoolSwap(_pool).exchange(int128(indexIn), int128(indexOut), _amountIn, 0);
        } else {
          ICurveYPoolSwap(_pool).exchange_underlying(int128(indexIn), int128(indexOut), _amountIn, 0);
        }
      } else if (_poolType == 7) {
        _approve(_tokenIn, _pool, _amountIn);
        ICurveMetaPoolSwap(_pool).exchange(int128(indexIn), int128(indexOut), _amountIn, 0);
      } else if (_poolType == 8) {
        if (((_encoding >> 169) & 1) == 0) {
          _approve(_tokenIn, _pool, _amountIn);
          ICurveCryptoPool(_pool).exchange(indexIn, indexOut, _amountIn, 0);
        } else {
          ICurveCryptoPool(_pool).exchange{ value: _amountIn }(indexIn, indexOut, _amountIn, 0, true);
        }
      }
    } else {
      revert("invalid poolType");
    }

    if (_tokenOut == WETH) {
      _wrapTokenIfNeeded(_tokenOut, address(this).balance);
    }
    if (_amountOut == 0) {
      _amountOut = IERC20(_tokenOut).balanceOf(address(this)) - _balanceBefore;
    }
    if (_recipient != address(this)) {
      IERC20(_tokenOut).safeTransfer(_recipient, _amountOut);
    }
  }

  /*****************************************
   * Internal Functions for Token Wrapping *
   *****************************************/

  /// @dev Query the amount of output token by wrapping.
  /// @param _poolType The pool type.
  /// @param _encoding The customized encoding of the route.
  /// @param _amountIn The amount of input token.
  /// @return _amountOut The amount of output token.
  function _queryWrap(
    uint256 _poolType,
    uint256 _encoding,
    uint256 _amountIn
  ) internal view returns (uint256 _amountOut) {
    address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975);
    if (4 <= _poolType && _poolType <= 8) {
      uint256 _tokens = ((_encoding >> 160) & 7) + 1;
      uint256 _indexIn = (_encoding >> 166) & 7;
      require(2 <= _tokens && _tokens <= 4, "invalid tokens");

      // compute actual token amount and actual pool
      if (_poolType == 6 && ((_encoding >> 169) & 1) == 1) {
        address _token = ICurveYPoolDeposit(_pool).coins(int128(_indexIn));
        address _underlying = ICurveYPoolDeposit(_pool).underlying_coins(int128(_indexIn));
        if (_token != _underlying) {
          assembly {
            // keccack("exchangeRateStored()")
            mstore(0x00, 0x182df0f500000000000000000000000000000000000000000000000000000000)
            let success := staticcall(gas(), _token, 0x00, 0x04, 0x00, 0x20)
            if success {
              _amountIn := div(mul(_amountIn, 1000000000000000000), mload(0x00))
            }
          }
        }
        _pool = ICurveYPoolDeposit(_pool).curve();
      } else {
        _pool = _getTokenMinter(_pool);
      }

      if (_tokens == 2) {
        uint256[2] memory _amounts;
        _amounts[_indexIn] = _amountIn;
        // some old pools are using `calc_token_amount(uint256[2])`
        // we use `calc_token_amount(uint256[2],bool)` first and then try `calc_token_amount(uint256[2])`
        assembly {
          // keccack("calc_token_amount(uint256[2],bool)")
          let p := mload(0x40)
          mstore(p, 0xed8e84f300000000000000000000000000000000000000000000000000000000)
          switch _indexIn
          case 0 {
            mstore(add(p, 0x04), _amountIn)
            mstore(add(p, 0x24), 0)
          }
          default {
            mstore(add(p, 0x04), 0)
            mstore(add(p, 0x24), _amountIn)
          }
          mstore(add(p, 0x44), 1)
          mstore(0x00, 0)
          let success := staticcall(gas(), _pool, p, 0x64, 0x00, 0x20)
          if success {
            _amountOut := mload(0x00)
          }
        }
        if (_amountOut == 0) {
          _amountOut = ICurvePlainPool(_pool).calc_token_amount(_amounts);
        }
      } else if (_tokens == 3) {
        uint256[3] memory _amounts;
        _amounts[_indexIn] = _amountIn;
        _amountOut = ICurvePlainPool(_pool).calc_token_amount(_amounts, true);
      } else {
        uint256[4] memory _amounts;
        _amounts[_indexIn] = _amountIn;
        _amountOut = ICurvePlainPool(_pool).calc_token_amount(_amounts, true);
      }
    } else if (_poolType == 9) {
      _amountOut = IERC4626(_pool).previewDeposit(_amountIn);
    }
  }

  /// @dev Wrap from one token to another token.
  /// @param _poolType The pool type.
  /// @param _encoding The customized encoding of the route.
  /// @param _amountIn The amount of input token.
  /// @param _recipient The address of output token receiver.
  /// @return _amountOut The amount of output token.
  function _wrap(
    uint256 _poolType,
    uint256 _encoding,
    uint256 _amountIn,
    address _recipient
  ) internal returns (uint256 _amountOut) {
    (address _tokenIn, address _tokenOut) = _getTokenPair(_poolType, 1, _encoding);
    address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975);

    if ((_poolType == 4 || _poolType == 8) && ((_encoding >> 169) & 1) == 1) {
      // tokenIn is (W)ETH and we are going to use ETH.
      _unwrapIfNeeded(_amountIn);
    } else {
      _wrapTokenIfNeeded(_tokenIn, _amountIn);
    }

    uint256 _balanceBefore = IERC20(_tokenOut).balanceOf(address(this));
    if (4 <= _poolType && _poolType <= 8) {
      _pool = _getTokenMinter(_pool);
      uint256 _tokens = ((_encoding >> 160) & 7) + 1;
      uint256 _indexIn = (_encoding >> 163) & 7;
      require(2 <= _tokens && _tokens <= 4, "invalid tokens");

      if (_poolType == 5) {
        bool _use_underlying = ((_encoding >> 169) & 1) == 1;
        _approve(_tokenIn, _pool, _amountIn);
        if (_tokens == 2) {
          uint256[2] memory _amounts;
          _amounts[_indexIn] = _amountIn;
          ICurveAPool(_pool).add_liquidity(_amounts, 0, _use_underlying);
        } else if (_tokens == 3) {
          uint256[3] memory _amounts;
          _amounts[_indexIn] = _amountIn;
          ICurveAPool(_pool).add_liquidity(_amounts, 0, _use_underlying);
        } else {
          uint256[4] memory _amounts;
          _amounts[_indexIn] = _amountIn;
          ICurveAPool(_pool).add_liquidity(_amounts, 0, _use_underlying);
        }
      } else {
        bool _use_eth = (_poolType == 4 || _poolType == 8) && (((_encoding >> 169) & 1) == 1);
        if (!_use_eth) {
          _approve(_tokenIn, _pool, _amountIn);
        }
        if (_tokens == 2) {
          uint256[2] memory _amounts;
          _amounts[_indexIn] = _amountIn;
          if (_use_eth) {
            if (_poolType == 8) {
              ICurveCryptoPool(_pool).add_liquidity{ value: _amountIn }(_amounts, 0, true);
            } else {
              ICurvePlainPool(_pool).add_liquidity{ value: _amountIn }(_amounts, 0);
            }
          } else {
            ICurvePlainPool(_pool).add_liquidity(_amounts, 0);
          }
        } else if (_tokens == 3) {
          uint256[3] memory _amounts;
          _amounts[_indexIn] = _amountIn;
          if (_use_eth) {
            if (_poolType == 8) {
              ICurveTriCryptoPool(_pool).add_liquidity{ value: _amountIn }(_amounts, 0, true);
            } else {
              ICurvePlainPool(_pool).add_liquidity{ value: _amountIn }(_amounts, 0);
            }
          } else {
            ICurvePlainPool(_pool).add_liquidity(_amounts, 0);
          }
        } else {
          uint256[4] memory _amounts;
          _amounts[_indexIn] = _amountIn;
          if (_use_eth) {
            ICurvePlainPool(_pool).add_liquidity{ value: _amountIn }(_amounts, 0);
          } else {
            ICurvePlainPool(_pool).add_liquidity(_amounts, 0);
          }
        }
      }
    } else if (_poolType == 9) {
      _approve(_tokenIn, _pool, _amountIn);
      _amountOut = IERC4626(_pool).deposit(_amountIn, _recipient);
      return _amountOut;
    } else {
      revert("invalid poolType");
    }

    _amountOut = IERC20(_tokenOut).balanceOf(address(this)) - _balanceBefore;
    if (_recipient != address(this)) {
      IERC20(_tokenOut).safeTransfer(_recipient, _amountOut);
    }
  }

  /*******************************************
   * Internal Functions for Token Unwrapping *
   *******************************************/

  /// @dev Query the amount of output token by unwrapping.
  /// @param _poolType The pool type.
  /// @param _encoding The customized encoding of the route.
  /// @param _amountIn The amount of input token.
  /// @return _amountOut The amount of output token.
  function _queryUnwrap(
    uint256 _poolType,
    uint256 _encoding,
    uint256 _amountIn
  ) internal view returns (uint256 _amountOut) {
    address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975);

    if (4 <= _poolType && _poolType <= 8) {
      if (_poolType != 6) {
        _pool = _getTokenMinter(_pool);
      }
      uint256 _indexOut = (_encoding >> 166) & 7;
      if (_poolType == 8) {
        _amountOut = ICurveCryptoPool(_pool).calc_withdraw_one_coin(_amountIn, _indexOut);
      } else {
        _amountOut = ICurvePlainPool(_pool).calc_withdraw_one_coin(_amountIn, int128(_indexOut));
      }
    } else if (_poolType == 9) {
      _amountOut = IERC4626(_pool).previewRedeem(_amountIn);
    }
  }

  /// @dev Unwrap from one token to another token.
  /// @param _poolType The pool type.
  /// @param _encoding The customized encoding of the route.
  /// @param _amountIn The amount of input token.
  /// @param _recipient The address of output token receiver.
  /// @return _amountOut The amount of output token.
  function _unwrap(
    uint256 _poolType,
    uint256 _encoding,
    uint256 _amountIn,
    address _recipient
  ) internal returns (uint256 _amountOut) {
    (address _tokenIn, address _tokenOut) = _getTokenPair(_poolType, 2, _encoding);
    address _pool = address(_encoding & 1461501637330902918203684832716283019655932542975);

    uint256 _balanceBefore = IERC20(_tokenOut).balanceOf(address(this));
    if (4 <= _poolType && _poolType <= 8) {
      if (_poolType != 6) {
        _pool = _getTokenMinter(_pool);
      }
      uint256 _tokens = ((_encoding >> 160) & 7) + 1;
      uint256 _indexOut = (_encoding >> 166) & 7;
      require(2 <= _tokens && _tokens <= 4, "invalid tokens");

      if (_poolType == 4) {
        ICurvePlainPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0);
      } else if (_poolType == 5) {
        bool _use_underlying = ((_encoding >> 169) & 1) == 1;
        ICurveAPool(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, _use_underlying);
      } else if (_poolType == 6) {
        _approve(_tokenIn, _pool, _amountIn);
        ICurveYPoolDeposit(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0, true);
      } else if (_poolType == 7) {
        ICurveMetaPoolSwap(_pool).remove_liquidity_one_coin(_amountIn, int128(_indexOut), 0);
      } else {
        ICurveCryptoPool(_pool).remove_liquidity_one_coin(_amountIn, _indexOut, 0);
      }
    } else if (_poolType == 9) {
      _amountOut = IERC4626(_pool).redeem(_amountIn, _recipient, address(this));
      return _amountOut;
    } else {
      revert("invalid poolType");
    }

    if (_tokenOut == WETH) {
      _wrapTokenIfNeeded(_tokenOut, address(this).balance);
    }

    _amountOut = IERC20(_tokenOut).balanceOf(address(this)) - _balanceBefore;
    if (_recipient != address(this)) {
      IERC20(_tokenOut).safeTransfer(_recipient, _amountOut);
    }
  }
}

// File: contracts/helpers/converter/IConverterRegistry.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0 || ^0.8.0;

interface IConverterRegistry {
  /**********
   * Events *
   **********/

  /// @notice Emitted when the converter route is updated.
  /// @param src The address of source token.
  /// @param dst The address of destination token.
  /// @param routes The list of route encodings.
  event UpdateRoute(address indexed src, address indexed dst, uint256[] routes);

  /// @notice Emitted when the token converter is updated for some pool type.
  /// @param poolType The pool type updated.
  /// @param oldConverter The address of previous converter.
  /// @param newConverter The address of current converter.
  event UpdateConverter(uint256 indexed poolType, address indexed oldConverter, address indexed newConverter);

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Return the routes used to convert source token to destination token.
  /// @param src The address of source token.
  /// @param dst The address of destination token.
  /// @return routes The list of route encodings.
  function getRoutes(address src, address dst) external view returns (uint256[] memory routes);

  /// @notice Return the input token and output token for the route.
  /// @param route The encoding of the route.
  /// @return tokenIn The address of input token.
  /// @return tokenOut The address of output token.
  function getTokenPair(uint256 route) external view returns (address tokenIn, address tokenOut);

  /// @notice Return the address of converter for a specific pool type.
  /// @param poolType The type of converter.
  /// @return converter The address of converter.
  function getConverter(uint256 poolType) external view returns (address converter);
}

// File: contracts/helpers/converter/ITokenConverter.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0 || ^0.8.0;

interface ITokenConverter {
  /*************************
   * Public View Functions *
   *************************/

  /// @notice The address of Converter Registry.
  function registry() external view returns (address);

  /// @notice Return the input token and output token for the route.
  /// @param route The encoding of the route.
  /// @return tokenIn The address of input token.
  /// @return tokenOut The address of output token.
  function getTokenPair(uint256 route) external view returns (address tokenIn, address tokenOut);

  /// @notice Query the output token amount according to the encoding.
  ///
  /// @dev See the comments in `convert` for the meaning of encoding.
  ///
  /// @param encoding The encoding used to convert.
  /// @param amountIn The amount of input token.
  /// @param amountOut The amount of output token received.
  function queryConvert(uint256 encoding, uint256 amountIn) external returns (uint256 amountOut);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Convert input token to output token according to the encoding.
  /// Assuming that the input token is already in the contract.
  ///
  /// @dev encoding for single route
  /// |   8 bits  | 2 bits |  246 bits  |
  /// | pool_type | action | customized |
  ///
  /// + pool_type = 0: UniswapV2, only action = 0
  ///   customized = |   160 bits   | 24 bits |     1 bit    | 1 bit | ... |
  ///                | pool address | fee_num | zero_for_one | twamm | ... |
  /// + pool_type = 1: UniswapV3, only action = 0
  ///   customized = |   160 bits   | 24 bits |     1 bit    | ... |
  ///                | pool address | fee_num | zero_for_one | ... |
  /// + pool_type = 2: BalancerV1, only action = 0
  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |
  ///                | pool address | tokens | index in | index out | ... |
  /// + pool_type = 3: BalancerV2, only action = 0
  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |
  ///                | pool address | tokens | index in | index out | ... |
  /// + pool_type = 4: CurvePlainPool or CurveFactoryPlainPool
  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |  1 bit  | ... |
  ///                | pool address | tokens | index in | index out | use_eth | ... |
  /// + pool_type = 5: CurveAPool
  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |     1 bits     | ... |
  ///                | pool address | tokens | index in | index out | use_underlying | ... |
  /// + pool_type = 6: CurveYPool
  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |     1 bits     | ... |
  ///                | pool address | tokens | index in | index out | use_underlying | ... |
  /// + pool_type = 7: CurveMetaPool or CurveFactoryMetaPool
  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |
  ///                | pool address | tokens | index in | index out | ... |
  /// + pool_type = 8: CurveCryptoPool or CurveFactoryCryptoPool
  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |  1 bit  | ... |
  ///                | pool address | tokens | index in | index out | use_eth | ... |
  /// + pool_type = 9: ERC4626, no action 0
  ///   customized = |   160 bits   | ... |
  ///                | pool address | ... |
  /// + pool_type = 10: Lido, no action 0
  ///   customized = |   160 bits   | ... |
  ///                | pool address | ... |
  ///
  /// Note: tokens + 1 is the number of tokens of the pool
  ///
  /// + action = 0: swap
  /// + action = 1: add liquidity / wrap / stake
  /// + action = 2: remove liquidity / unwrap / unstake
  ///
  /// @param encoding The encoding used to convert.
  /// @param amountIn The amount of input token.
  /// @param recipient The address of token receiver.
  /// @return amountOut The amount of output token received.
  function convert(
    uint256 encoding,
    uint256 amountIn,
    address recipient
  ) external payable returns (uint256 amountOut);

  /// @notice Withdraw dust assets in this contract.
  /// @param token The address of token to withdraw.
  /// @param recipient The address of token receiver.
  function withdrawFund(address token, address recipient) external;
}

// File: contracts/interfaces/IBalancerPool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

interface IBalancerPool {
  function getPoolId() external view returns (bytes32);
}

// File: contracts/interfaces/IBalancerV1Pool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

interface IBalancerV1Pool {
  function getCurrentTokens() external view returns (address[] memory tokens);

  function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;

  function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;

  function swapExactAmountIn(
    address tokenIn,
    uint256 tokenAmountIn,
    address tokenOut,
    uint256 minAmountOut,
    uint256 maxPrice
  ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);

  function swapExactAmountOut(
    address tokenIn,
    uint256 maxAmountIn,
    address tokenOut,
    uint256 tokenAmountOut,
    uint256 maxPrice
  ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter);

  function joinswapExternAmountIn(
    address tokenIn,
    uint256 tokenAmountIn,
    uint256 minPoolAmountOut
  ) external returns (uint256 poolAmountOut);

  function joinswapPoolAmountOut(
    address tokenIn,
    uint256 poolAmountOut,
    uint256 maxAmountIn
  ) external returns (uint256 tokenAmountIn);

  function exitswapPoolAmountIn(
    address tokenOut,
    uint256 poolAmountIn,
    uint256 minAmountOut
  ) external returns (uint256 tokenAmountOut);

  function exitswapExternAmountOut(
    address tokenOut,
    uint256 tokenAmountOut,
    uint256 maxPoolAmountIn
  ) external returns (uint256 poolAmountIn);

  function getBalance(address token) external view returns (uint256);

  function getDenormalizedWeight(address token) external view returns (uint256);

  function getSwapFee() external view returns (uint256);

  /**********************************************************************************************
    // calcOutGivenIn                                                                            //
    // aO = tokenAmountOut                                                                       //
    // bO = tokenBalanceOut                                                                      //
    // bI = tokenBalanceIn              /      /            bI             \    (wI / wO) \      //
    // aI = tokenAmountIn    aO = bO * |  1 - | --------------------------  | ^            |     //
    // wI = tokenWeightIn               \      \ ( bI + ( aI * ( 1 - sF )) /              /      //
    // wO = tokenWeightOut                                                                       //
    // sF = swapFee                                                                              //
    **********************************************************************************************/
  function calcOutGivenIn(
    uint256 tokenBalanceIn,
    uint256 tokenWeightIn,
    uint256 tokenBalanceOut,
    uint256 tokenWeightOut,
    uint256 tokenAmountIn,
    uint256 swapFee
  ) external view returns (uint256 tokenAmountOut);
}

// File: contracts/interfaces/IBalancerVault.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;
pragma abicoder v2;

interface IBalancerVault {
  enum JoinKind {
    INIT,
    EXACT_TOKENS_IN_FOR_BPT_OUT,
    TOKEN_IN_FOR_EXACT_BPT_OUT,
    ALL_TOKENS_IN_FOR_EXACT_BPT_OUT
  }

  enum ExitKind {
    EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
    EXACT_BPT_IN_FOR_TOKENS_OUT,
    BPT_IN_FOR_EXACT_TOKENS_OUT
  }

  enum SwapKind {
    GIVEN_IN,
    GIVEN_OUT
  }

  struct SingleSwap {
    bytes32 poolId;
    SwapKind kind;
    address assetIn;
    address assetOut;
    uint256 amount;
    bytes userData;
  }

  struct FundManagement {
    address sender;
    bool fromInternalBalance;
    address payable recipient;
    bool toInternalBalance;
  }

  function getPoolTokens(bytes32 poolId)
    external
    view
    returns (
      address[] memory tokens,
      uint256[] memory balances,
      uint256 lastChangeBlock
    );

  function swap(
    SingleSwap memory singleSwap,
    FundManagement memory funds,
    uint256 limit,
    uint256 deadline
  ) external payable returns (uint256 amountCalculated);

  struct JoinPoolRequest {
    address[] assets;
    uint256[] maxAmountsIn;
    bytes userData;
    bool fromInternalBalance;
  }

  function joinPool(
    bytes32 poolId,
    address sender,
    address recipient,
    JoinPoolRequest memory request
  ) external payable;

  struct ExitPoolRequest {
    address[] assets;
    uint256[] minAmountsOut;
    bytes userData;
    bool toInternalBalance;
  }

  function exitPool(
    bytes32 poolId,
    address sender,
    address payable recipient,
    ExitPoolRequest memory request
  ) external;

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

  // This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy
  function queryBatchSwap(
    SwapKind kind,
    BatchSwapStep[] memory swaps,
    address[] memory assets,
    FundManagement memory funds
  ) external returns (int256[] memory);
}

// File: contracts/interfaces/ICurveAPool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

// solhint-disable var-name-mixedcase, func-name-mixedcase

interface ICurveAPool {
  function remove_liquidity_one_coin(
    uint256 _token_amount,
    int128 i,
    uint256 _min_amount,
    bool _use_underlying
  ) external returns (uint256);

  function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);

  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  function exchange_underlying(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  function get_dy(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  function get_dy_underlying(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  function add_liquidity(
    uint256[2] memory _amounts,
    uint256 _min_mint_amount,
    bool _use_underlying
  ) external returns (uint256);

  function calc_token_amount(uint256[2] memory amounts, bool is_deposit) external view returns (uint256);

  function add_liquidity(
    uint256[3] memory _amounts,
    uint256 _min_mint_amount,
    bool _use_underlying
  ) external returns (uint256);

  function calc_token_amount(uint256[3] memory amounts, bool is_deposit) external view returns (uint256);

  function add_liquidity(
    uint256[4] memory _amounts,
    uint256 _min_mint_amount,
    bool _use_underlying
  ) external returns (uint256);

  function calc_token_amount(uint256[4] memory amounts, bool is_deposit) external view returns (uint256);

  function coins(uint256 index) external view returns (address);

  function underlying_coins(uint256 index) external view returns (address);

  function lp_token() external view returns (address);
}

/// @dev This is the interface of Curve aave-style Pool with 2 tokens, examples:
/// + saave: https://curve.fi/saave
interface ICurveA2Pool is ICurveAPool {

}

/// @dev This is the interface of Curve aave-style Pool with 3 tokens, examples:
/// aave: https://curve.fi/aave
/// ironbank: https://curve.fi/ib
interface ICurveA3Pool is ICurveAPool {

}

/// @dev This is the interface of Curve aave-style Pool with 3 tokens, examples:
interface ICurveA4Pool is ICurveAPool {

}

// File: contracts/interfaces/ICurveCryptoPool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0 || ^0.8.0;

// solhint-disable func-name-mixedcase, var-name-mixedcase

/// @dev This is the interface of Curve Crypto Pools (including Factory Pool), examples:
/// + cvxeth: https://curve.fi/cvxeth
/// + crveth: https://curve.fi/crveth
/// + eursusd: https://curve.fi/eursusd
/// + teth: https://curve.fi/teth
/// + spelleth: https://curve.fi/spelleth

/// + FXS/ETH: https://curve.fi/factory-crypto/3
/// + YFI/ETH: https://curve.fi/factory-crypto/8
/// + AAVE/palStkAAVE: https://curve.fi/factory-crypto/9
/// + DYDX/ETH: https://curve.fi/factory-crypto/10
/// + SDT/ETH: https://curve.fi/factory-crypto/11
/// + BTRFLY/ETH: https://curve.fi/factory-crypto/17
/// + cvxFXS/FXS: https://curve.fi/factory-crypto/18
interface ICurveCryptoPool {
  function lp_price() external view returns (uint256);

  function price_oracle() external view returns (uint256);

  function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external payable returns (uint256);

  function add_liquidity(
    uint256[2] memory amounts,
    uint256 min_mint_amount,
    bool use_eth
  ) external payable returns (uint256);

  function calc_token_amount(uint256[2] memory amounts) external view returns (uint256);

  function remove_liquidity_one_coin(
    uint256 token_amount,
    uint256 i,
    uint256 min_amount
  ) external returns (uint256);

  function calc_withdraw_one_coin(uint256 token_amount, uint256 i) external view returns (uint256);

  function exchange(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy
  ) external payable;

  function exchange(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy,
    bool use_eth
  ) external payable;

  function exchange(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy,
    bool use_eth,
    address receiver
  ) external payable;

  function exchange_underlying(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy
  ) external payable returns (uint256);

  function exchange_underlying(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy,
    address receiver
  ) external payable returns (uint256);

  function get_dy(
    uint256 i,
    uint256 j,
    uint256 dx
  ) external view returns (uint256);

  function coins(uint256 index) external view returns (address);

  function token() external view returns (address);
}

/// @dev This is the interface of Zap Contract for Curve Meta Crypto Pools, examples:
/// + eurtusd: https://curve.fi/eurtusd
/// + xautusd: https://curve.fi/xautusd
interface IZapCurveMetaCryptoPool {
  function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external returns (uint256);

  function calc_token_amount(uint256[4] memory amounts) external view returns (uint256);

  function remove_liquidity_one_coin(
    uint256 token_amount,
    uint256 i,
    uint256 min_amount
  ) external;

  function calc_withdraw_one_coin(uint256 token_amount, uint256 i) external view returns (uint256);

  function exchange_underlying(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  function get_dy_underlying(
    uint256 i,
    uint256 j,
    uint256 dx
  ) external view returns (uint256);

  function coins(uint256 index) external view returns (address);

  function underlying_coins(uint256 index) external view returns (address);

  function token() external view returns (address);

  function base_pool() external view returns (address);

  function pool() external view returns (address);
}

/// @dev This is the interface of Curve Tri Crypto Pools, examples:
/// + tricrypto2: https://curve.fi/tricrypto2
/// + tricrypto: https://curve.fi/tricrypto
interface ICurveTriCryptoPool {
  function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external payable;

  function add_liquidity(
    uint256[3] memory amounts,
    uint256 min_mint_amount,
    bool use_eth
  ) external payable;

  function calc_token_amount(uint256[3] memory amounts, bool deposit) external view returns (uint256);

  function remove_liquidity_one_coin(
    uint256 token_amount,
    uint256 i,
    uint256 min_amount
  ) external;

  function calc_withdraw_one_coin(uint256 token_amount, uint256 i) external view returns (uint256);

  function exchange(
    uint256 i,
    uint256 j,
    uint256 dx,
    uint256 min_dy,
    bool use_eth
  ) external;

  function get_dy(
    uint256 i,
    uint256 j,
    uint256 dx
  ) external view returns (uint256);

  function token() external view returns (address);

  function coins(uint256 index) external returns (address);
}

// File: contracts/interfaces/ICurveMetaPool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

// solhint-disable var-name-mixedcase, func-name-mixedcase

/// @dev This is the interface of Curve Meta Pool with (3pool or sbtc), examples:
/// + ust: https://curve.fi/ust
/// + dusd: https://www.curve.fi/dusd
/// + gusd: https://curve.fi/gusd
/// + husd: https://curve.fi/husd
/// + rai: https://curve.fi/rai
/// + musd: https://curve.fi/musd
///
/// + bbtc: https://curve.fi/bbtc
/// + obtc: https://www.curve.fi/obtc
/// + pbtc: https://www.curve.fi/pbtc
/// + tbtc: https://www.curve.fi/tbtc
interface ICurveMetaPoolSwap {
  function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external returns (uint256);

  function calc_token_amount(uint256[2] memory amounts, bool is_deposit) external view returns (uint256);

  function remove_liquidity_one_coin(
    uint256 token_amount,
    int128 i,
    uint256 min_amount
  ) external returns (uint256);

  function calc_withdraw_one_coin(uint256 token_amount, int128 i) external view returns (uint256);

  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  function exchange_underlying(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  function get_dy(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  function get_dy_underlying(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  function base_pool() external view returns (address);

  function base_coins(uint256 index) external view returns (address);

  function coins(uint256 index) external view returns (address);

  function token() external view returns (address);
}

interface ICurveMetaPoolDeposit {
  function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external returns (uint256);

  function calc_token_amount(uint256[4] memory amounts, bool is_deposit) external view returns (uint256);

  function remove_liquidity_one_coin(
    uint256 token_amount,
    int128 i,
    uint256 min_amount
  ) external returns (uint256);

  function calc_withdraw_one_coin(uint256 token_amount, int128 i) external view returns (uint256);

  function token() external view returns (address);

  function base_pool() external view returns (address);

  function pool() external view returns (address);

  function coins(uint256 index) external view returns (address);

  function base_coins(uint256 index) external view returns (address);
}

// File: contracts/interfaces/ICurvePlainPool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

// solhint-disable var-name-mixedcase, func-name-mixedcase

interface ICurvePlainPool {
  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external payable;

  function get_dy(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external payable;

  function calc_token_amount(uint256[2] memory amounts) external view returns (uint256);

  function calc_token_amount(uint256[2] memory amounts, bool deposit) external view returns (uint256);

  function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external payable;

  function calc_token_amount(uint256[3] memory amounts, bool deposit) external view returns (uint256);

  function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external payable;

  function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256);

  function remove_liquidity_one_coin(
    uint256 _token_amount,
    int128 i,
    uint256 min_amount
  ) external;

  function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);

  function coins(uint256 index) external view returns (address);

  function balances(uint256 index) external view returns (uint256);

  // ren and sbtc pool
  function coins(int128 index) external view returns (address);

  // ren and sbtc pool
  function balances(int128 index) external view returns (uint256);

  function get_virtual_price() external view returns (uint256);
}

// File: contracts/interfaces/ICurveYPool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

// solhint-disable var-name-mixedcase, func-name-mixedcase

interface ICurveYPoolSwap {
  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external;

  function exchange_underlying(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external;

  function get_dy(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  function get_dy_underlying(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external;

  function add_liquidity(uint256[3] memory _amounts, uint256 _min_mint_amount) external;

  function add_liquidity(uint256[4] memory _amounts, uint256 _min_mint_amount) external;

  function coins(uint256 index) external view returns (address);

  function underlying_coins(uint256 index) external view returns (address);

  function coins(int128 index) external view returns (address);

  function underlying_coins(int128 index) external view returns (address);
}

interface ICurveYPoolDeposit {
  function remove_liquidity_one_coin(
    uint256 _token_amount,
    int128 i,
    uint256 _min_amount,
    bool donate_dust
  ) external;

  function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);

  function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external;

  function add_liquidity(uint256[3] memory _amounts, uint256 _min_mint_amount) external;

  function add_liquidity(uint256[4] memory _amounts, uint256 _min_mint_amount) external;

  function token() external view returns (address);

  function curve() external view returns (address);

  function coins(uint256 index) external view returns (address);

  function underlying_coins(uint256 index) external view returns (address);

  function coins(int128 index) external view returns (address);

  function underlying_coins(int128 index) external view returns (address);
}

// solhint-disable var-name-mixedcase, func-name-mixedcase
/// @dev This is the interface of Curve yearn-style Pool with 2 tokens, examples:
/// + compound: https://curve.fi/compound
interface ICurveY2PoolDeposit is ICurveYPoolDeposit {

}

interface ICurveY2PoolSwap is ICurveYPoolSwap {}

/// @dev This is the interface of Curve yearn-style Pool with 3 tokens, examples:
/// usdt: https://curve.fi/usdt
interface ICurveY3PoolDeposit is ICurveYPoolDeposit {

}

interface ICurveY3PoolSwap is ICurveYPoolSwap {}

/// @dev This is the interface of Curve yearn-style Pool with 4 tokens, examples:
/// + pax: https://curve.fi/pax
/// + y: https://curve.fi/iearn
/// + busd: https://curve.fi/busd
/// + susd v2: https://curve.fi/susdv2
interface ICurveY4PoolDeposit is ICurveYPoolDeposit {

}

interface ICurveY4PoolSwap is ICurveYPoolSwap {}

// File: contracts/interfaces/IERC20Metadata.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

interface IERC20Metadata {
  function decimals() external view returns (uint8);

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

  function name() external view returns (string memory);
}

// File: contracts/interfaces/IUniswapV2Pair.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

interface IUniswapV2Pair {
  function token0() external view returns (address);

  function token1() external view returns (address);

  function getReserves()
    external
    view
    returns (
      uint112 _reserve0,
      uint112 _reserve1,
      uint32 _blockTimestampLast
    );

  function swap(
    uint256 amount0Out,
    uint256 amount1Out,
    address to,
    bytes calldata data
  ) external;

  // fraxswap
  function executeVirtualOrders(uint256 blockTimestamp) external;

  // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
  function getAmountOut(uint256 amountIn, address tokenIn) external view returns (uint256);
}

// File: contracts/interfaces/IUniswapV3Pool.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

interface IUniswapV3Pool {
  /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
  /// @return The contract address
  function factory() external view returns (address);

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

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

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

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

// File: contracts/interfaces/IUniswapV3Quoter.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

/// @title Quoter Interface
/// @notice Supports quoting the calculated amounts from exact input or exact output swaps
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IUniswapV3Quoter {
  /// @notice Returns the amount out received for a given exact input swap without executing the swap
  /// @param path The path of the swap, i.e. each token pair and the pool fee
  /// @param amountIn The amount of the first token to swap
  /// @return amountOut The amount of the last token that would be received
  function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut);

  /// @notice Returns the amount out received for a given exact input but for a swap of a single pool
  /// @param tokenIn The token being swapped in
  /// @param tokenOut The token being swapped out
  /// @param fee The fee of the token pool to consider for the pair
  /// @param amountIn The desired input amount
  /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
  /// @return amountOut The amount of `tokenOut` that would be received
  function quoteExactInputSingle(
    address tokenIn,
    address tokenOut,
    uint24 fee,
    uint256 amountIn,
    uint160 sqrtPriceLimitX96
  ) external returns (uint256 amountOut);

  /// @notice Returns the amount in required for a given exact output swap without executing the swap
  /// @param path The path of the swap, i.e. each token pair and the pool fee
  /// @param amountOut The amount of the last token to receive
  /// @return amountIn The amount of first token required to be paid
  function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn);

  /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
  /// @param tokenIn The token being swapped in
  /// @param tokenOut The token being swapped out
  /// @param fee The fee of the token pool to consider for the pair
  /// @param amountOut The desired output amount
  /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
  /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
  function quoteExactOutputSingle(
    address tokenIn,
    address tokenOut,
    uint24 fee,
    uint256 amountOut,
    uint160 sqrtPriceLimitX96
  ) external returns (uint256 amountIn);
}

// File: contracts/interfaces/IUniswapV3Router.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;
pragma abicoder v2;

interface IUniswapV3Router {
  struct ExactInputSingleParams {
    address tokenIn;
    address tokenOut;
    uint24 fee;
    address recipient;
    uint256 deadline;
    uint256 amountIn;
    uint256 amountOutMinimum;
    uint160 sqrtPriceLimitX96;
  }

  function exactInputSingle(ExactInputSingleParams calldata params) external returns (uint256 amountOut);
}

// File: contracts/interfaces/IWETH.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.6;

interface IWETH {
  function deposit() external payable;

  function withdraw(uint256 wad) external;
}