Contract 0xa701d16ee79ab65c929c2918343f28d6450b5056 8

 
Txn Hash Method
Block
From
To
Value [Txn Fee]
0x1f8a73cc81638a5361afb3ca53c51936eaf98bf4663a50bd22ce9d3456f23fe20x60c06040631918502023-02-21 19:17:24463 days 7 hrs ago0xf09c27934a92c56c7c0dd6cbac858c35fbd5170f IN  Create: IMXLendStrategy0 ETH0.000952620.1
[ Download CSV Export 
Latest 25 internal transaction
Parent Txn Hash Block From To Value
0xa7aa8a5e8419913fe59607e739b2c8434da55395677ba023f8542999d59bb73a720567082023-03-21 8:15:52435 days 18 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xa7aa8a5e8419913fe59607e739b2c8434da55395677ba023f8542999d59bb73a720567082023-03-21 8:15:52435 days 18 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xa7aa8a5e8419913fe59607e739b2c8434da55395677ba023f8542999d59bb73a720567082023-03-21 8:15:52435 days 18 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0xb632e22dba36e70ce4cb1924c8796b40ee86cb5fcd7639f4a1b8c680b5020386719838402023-03-21 3:15:15435 days 23 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xb632e22dba36e70ce4cb1924c8796b40ee86cb5fcd7639f4a1b8c680b5020386719838402023-03-21 3:15:15435 days 23 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xb632e22dba36e70ce4cb1924c8796b40ee86cb5fcd7639f4a1b8c680b5020386719838402023-03-21 3:15:15435 days 23 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0x5200f97a442ddc030b5689e736db2d6ed06295e1b4097ada953bba361f0bfbb4719269092023-03-20 23:14:53436 days 3 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x5200f97a442ddc030b5689e736db2d6ed06295e1b4097ada953bba361f0bfbb4719269092023-03-20 23:14:53436 days 3 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x5200f97a442ddc030b5689e736db2d6ed06295e1b4097ada953bba361f0bfbb4719269092023-03-20 23:14:53436 days 3 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0x1ca2901425405f5229592991872770326b45678dc59e97e87bb99ff52105f061718748732023-03-20 19:32:22436 days 7 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x1ca2901425405f5229592991872770326b45678dc59e97e87bb99ff52105f061718748732023-03-20 19:32:22436 days 7 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x1ca2901425405f5229592991872770326b45678dc59e97e87bb99ff52105f061718748732023-03-20 19:32:22436 days 7 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0x9af8a5072052bc832c3d7c28e3d75491caeb31f56bfda5f5c0ad30c262aae03e718250252023-03-20 16:05:59436 days 10 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x9af8a5072052bc832c3d7c28e3d75491caeb31f56bfda5f5c0ad30c262aae03e718250252023-03-20 16:05:59436 days 10 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x9af8a5072052bc832c3d7c28e3d75491caeb31f56bfda5f5c0ad30c262aae03e718250252023-03-20 16:05:59436 days 10 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0x9af8a5072052bc832c3d7c28e3d75491caeb31f56bfda5f5c0ad30c262aae03e718250252023-03-20 16:05:59436 days 10 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x9af8a5072052bc832c3d7c28e3d75491caeb31f56bfda5f5c0ad30c262aae03e718250252023-03-20 16:05:59436 days 10 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0x9af8a5072052bc832c3d7c28e3d75491caeb31f56bfda5f5c0ad30c262aae03e718250252023-03-20 16:05:59436 days 10 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0xa01109512595e27340b1c802372e125f77e016177d41a40ea6d12ba8f70dbf1a718127002023-03-20 15:15:13436 days 11 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xa01109512595e27340b1c802372e125f77e016177d41a40ea6d12ba8f70dbf1a718127002023-03-20 15:15:13436 days 11 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xa01109512595e27340b1c802372e125f77e016177d41a40ea6d12ba8f70dbf1a718127002023-03-20 15:15:13436 days 11 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0xe43c5cbb6addb08e4ff998363d826a922dd25228f488ad5f0889f737fdb967ad717835792023-03-20 13:15:33436 days 13 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xe43c5cbb6addb08e4ff998363d826a922dd25228f488ad5f0889f737fdb967ad717835792023-03-20 13:15:33436 days 13 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
0xe43c5cbb6addb08e4ff998363d826a922dd25228f488ad5f0889f737fdb967ad717835792023-03-20 13:15:33436 days 13 hrs ago 0xa6f224428a168a0f6ecfcb070d6a36e2291a6719 0xa701d16ee79ab65c929c2918343f28d6450b50560 ETH
0xb1f00227b126a69b5b8a6b2ca679853077878bc5403e1ebee6dcaf8193b858c2717102832023-03-20 8:14:46436 days 18 hrs ago 0xa701d16ee79ab65c929c2918343f28d6450b5056 0x074e82153303ec002cbd996febd148321e1302ce0 ETH
[ Download CSV Export 
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
IMXLendStrategy

Compiler Version
v0.8.16+commit.07a7930e

Optimization Enabled:
Yes with 1 runs

Other Settings:
default evmVersion, GNU GPLv3 license
File 1 of 52 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

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

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Internal function that returns the initialized version. Returns `_initialized`
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Internal function that returns the initialized version. Returns `_initializing`
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

File 2 of 52 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 3 of 52 : IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

File 4 of 52 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @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
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://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");

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

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

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

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

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

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

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

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

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

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

File 5 of 52 : AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

File 6 of 52 : IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

File 7 of 52 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 8 of 52 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

File 9 of 52 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

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

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

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

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

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

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

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

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

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

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

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

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

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

        return true;
    }

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

        _beforeTokenTransfer(from, to, amount);

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

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 10 of 52 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

File 12 of 52 : draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/extensions/draft-ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.sol";
import "../../../utils/Counters.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    /**
     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
     * However, to ensure consistency with the upgradeable transpiler, we will continue
     * to reserve a slot.
     * @custom:oz-renamed-from _PERMIT_TYPEHASH
     */
    // solhint-disable-next-line var-name-mixedcase
    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

File 13 of 52 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

File 14 of 52 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

    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'
        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) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

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

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

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

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

File 15 of 52 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://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");

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

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

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

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

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

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

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

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

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

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

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

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

File 16 of 52 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

File 17 of 52 : Counters.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

File 18 of 52 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";

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

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

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

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

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

File 19 of 52 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

File 20 of 52 : EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    address private immutable _CACHED_THIS;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _CACHED_THIS = address(this);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

File 21 of 52 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 22 of 52 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

File 23 of 52 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 24 of 52 : Auth.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.16;

import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";

struct AuthConfig {
	address owner;
	address guardian;
	address manager;
}

contract Auth is AccessControl {
	event OwnershipTransferInitiated(address owner, address pendingOwner);
	event OwnershipTransferred(address oldOwner, address newOwner);

	////////// CONSTANTS //////////

	/// Update vault params, perform time-sensitive operations, set manager
	bytes32 public constant GUARDIAN = keccak256("GUARDIAN");

	/// Hot-wallet bots that route funds between vaults, rebalance and harvest strategies
	bytes32 public constant MANAGER = keccak256("MANAGER");

	/// Add and remove vaults and strategies and other critical operations behind timelock
	/// Default admin role
	/// There should only be one owner, so it is not a role
	address public owner;
	address public pendingOwner;

	modifier onlyOwner() {
		require(msg.sender == owner, "ONLY_OWNER");
		_;
	}

	constructor(AuthConfig memory authConfig) {
		/// Set up the roles
		// owner can manage all roles
		owner = authConfig.owner;
		emit OwnershipTransferred(address(0), authConfig.owner);

		// TODO do we want cascading roles like this?
		_grantRole(DEFAULT_ADMIN_ROLE, authConfig.owner);
		_grantRole(GUARDIAN, authConfig.owner);
		_grantRole(GUARDIAN, authConfig.guardian);
		_grantRole(MANAGER, authConfig.owner);
		_grantRole(MANAGER, authConfig.guardian);
		_grantRole(MANAGER, authConfig.manager);

		/// Allow the guardian role to manage manager
		_setRoleAdmin(MANAGER, GUARDIAN);
	}

	// ----------- Ownership -----------

	/// @dev Init transfer of ownership of the contract to a new account (`_pendingOwner`).
	/// @param _pendingOwner pending owner of contract
	/// Can only be called by the current owner.
	function transferOwnership(address _pendingOwner) external onlyOwner {
		pendingOwner = _pendingOwner;
		emit OwnershipTransferInitiated(owner, _pendingOwner);
	}

	/// @dev Accept transfer of ownership of the contract.
	/// Can only be called by the pendingOwner.
	function acceptOwnership() external {
		address newOwner = pendingOwner;
		require(msg.sender == newOwner, "ONLY_PENDING_OWNER");
		address oldOwner = owner;
		owner = newOwner;

		// revoke the DEFAULT ADMIN ROLE from prev owner
		_revokeRole(DEFAULT_ADMIN_ROLE, oldOwner);
		_revokeRole(GUARDIAN, oldOwner);
		_revokeRole(MANAGER, oldOwner);

		_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
		_grantRole(GUARDIAN, newOwner);
		_grantRole(MANAGER, newOwner);

		emit OwnershipTransferred(oldOwner, newOwner);
	}
}

File 25 of 52 : Fees.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

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

// import "hardhat/console.sol";

struct FeeConfig {
	address treasury;
	uint256 performanceFee;
	uint256 managementFee;
}

abstract contract Fees is Auth {
	uint256 public constant MAX_MANAGEMENT_FEE = .05e18; // 5%
	uint256 public constant MAX_PERFORMANCE_FEE = .25e18; // 25%

	/// @notice The percentage of profit recognized each harvest to reserve as fees.
	/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
	uint256 public performanceFee;

	/// @notice Annual management fee.
	/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
	uint256 public managementFee;

	/// @notice address where all fees are sent to
	address public treasury;

	constructor(FeeConfig memory feeConfig) {
		treasury = feeConfig.treasury;
		performanceFee = feeConfig.performanceFee;
		managementFee = feeConfig.managementFee;
		emit SetTreasury(feeConfig.treasury);
		emit SetPerformanceFee(feeConfig.performanceFee);
		emit SetManagementFee(feeConfig.managementFee);
	}

	/// @notice Sets a new performanceFee.
	/// @param _performanceFee The new performance fee.
	function setPerformanceFee(uint256 _performanceFee) public onlyOwner {
		if (_performanceFee > MAX_PERFORMANCE_FEE) revert OverMaxFee();

		performanceFee = _performanceFee;
		emit SetPerformanceFee(performanceFee);
	}

	/// @notice Sets a new performanceFee.
	/// @param _managementFee The new performance fee.
	function setManagementFee(uint256 _managementFee) public onlyOwner {
		if (_managementFee > MAX_MANAGEMENT_FEE) revert OverMaxFee();

		managementFee = _managementFee;
		emit SetManagementFee(_managementFee);
	}

	/// @notice Updates treasury.
	/// @param _treasury New treasury address.
	function setTreasury(address _treasury) public onlyOwner {
		treasury = _treasury;
		emit SetTreasury(_treasury);
	}

	/// @notice Emitted when performance fee is updated.
	/// @param performanceFee The new perforamance fee.
	event SetPerformanceFee(uint256 performanceFee);

	/// @notice Emitted when management fee is updated.
	/// @param managementFee The new management fee.
	event SetManagementFee(uint256 managementFee);

	event SetTreasury(address indexed treasury);

	error OverMaxFee();
}

File 26 of 52 : StratAuth.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import { Auth } from "./Auth.sol";
import { EAction } from "../interfaces/Structs.sol";
import { SectorErrors } from "../interfaces/SectorErrors.sol";

// import "hardhat/console.sol";

abstract contract StratAuth is Auth, SectorErrors {
	address public vault;

	modifier onlyVault() {
		if (msg.sender != vault) revert OnlyVault();
		_;
	}

	event EmergencyAction(address indexed target, bytes data);

	/// @notice calls arbitrary function on target contract in case of emergency
	function emergencyAction(EAction[] calldata actions) public payable onlyOwner {
		uint256 l = actions.length;
		for (uint256 i; i < l; ++i) {
			address target = actions[i].target;
			bytes memory data = actions[i].data;
			(bool success, ) = target.call{ value: actions[i].value }(data);
			require(success, "emergencyAction failed");
			emit EmergencyAction(target, data);
		}
	}
}

File 27 of 52 : StratAuthLight.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import { Auth } from "./Auth.sol";
import { EAction } from "../interfaces/Structs.sol";
import { SectorErrors } from "../interfaces/SectorErrors.sol";

// import "hardhat/console.sol";

abstract contract StratAuthLight is SectorErrors {
	address public vault;

	modifier onlyVault() {
		if (msg.sender != vault) revert OnlyVault();
		_;
	}

	event EmergencyAction(address indexed target, bytes data);

	/// @notice calls arbitrary function on target contract in case of emergency
	function emergencyAction(EAction[] calldata actions) public payable onlyVault {
		uint256 l = actions.length;
		for (uint256 i; i < l; ++i) {
			address target = actions[i].target;
			bytes memory data = actions[i].data;
			(bool success, ) = target.call{ value: actions[i].value }(data);
			require(success, "emergencyAction failed");
			emit EmergencyAction(target, data);
		}
	}
}

File 28 of 52 : ISCYStrategy.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.16;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { HarvestSwapParams } from "../../interfaces/Structs.sol";
import { SectorErrors } from "../../interfaces/SectorErrors.sol";

interface ISCYStrategy {
	function underlying() external view returns (IERC20);

	function deposit(uint256 amount) external returns (uint256);

	function redeem(address to, uint256 amount) external returns (uint256 amntOut);

	function closePosition(uint256 slippageParam) external returns (uint256);

	function getAndUpdateTvl() external returns (uint256);

	function getTvl() external view returns (uint256);

	function getMaxTvl() external view returns (uint256);

	function collateralToUnderlying() external view returns (uint256);

	function harvest(
		HarvestSwapParams[] calldata farm1Params,
		HarvestSwapParams[] calldata farm2Parms
	) external returns (uint256[] memory harvest1, uint256[] memory harvest2);

	function getWithdrawAmnt(uint256 lpTokens) external view returns (uint256);

	function getDepositAmnt(uint256 uAmnt) external view returns (uint256);

	function getLpBalance() external view returns (uint256);

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

File 29 of 52 : ISCYVault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.16;

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

struct SCYVaultConfig {
	string symbol;
	string name;
	address addr;
	uint16 strategyId; // this is strategy specific token if 1155
	bool acceptsNativeToken;
	address yieldToken;
	IERC20 underlying;
	uint128 maxTvl; // pack all params and balances
	uint128 balance; // strategy balance in underlying
	uint128 uBalance; // underlying balance
	uint128 yBalance; // yield token balance
}

interface ISCYVault {
	// scy deposit
	function deposit(
		address receiver,
		address tokenIn,
		uint256 amountTokenToPull,
		uint256 minSharesOut
	) external payable returns (uint256 amountSharesOut);

	function redeem(
		address receiver,
		uint256 amountSharesToPull,
		address tokenOut,
		uint256 minTokenOut
	) external returns (uint256 amountTokenOut);

	function pause() external;

	function unpause() external;

	function getAndUpdateTvl() external returns (uint256 tvl);

	function getTvl() external view returns (uint256 tvl);

	function MIN_LIQUIDITY() external view returns (uint256);

	function underlying() external view returns (IERC20);

	function yieldToken() external view returns (address);

	function sendERC20ToStrategy() external view returns (bool);

	function strategy() external view returns (ISCYStrategy);

	function underlyingBalance(address) external view returns (uint256);

	function underlyingToShares(uint256 amnt) external view returns (uint256);

	function exchangeRateUnderlying() external view returns (uint256);

	function sharesToUnderlying(uint256 shares) external view returns (uint256);

	function getUpdatedUnderlyingBalance(address) external returns (uint256);

	function getFloatingAmount(address) external view returns (uint256);

	function getStrategyTvl() external view returns (uint256);

	function acceptsNativeToken() external view returns (bool);

	function underlyingDecimals() external view returns (uint8);

	function getMaxTvl() external view returns (uint256);

	function closePosition(uint256 minAmountOut, uint256 slippageParam) external;

	function initStrategy(address) external;

	function harvest(
		uint256 expectedTvl,
		uint256 maxDelta,
		HarvestSwapParams[] calldata swap1,
		HarvestSwapParams[] calldata swap2
	) external returns (uint256[] memory harvest1, uint256[] memory harvest2);

	function withdrawFromStrategy(uint256 shares, uint256 minAmountOut) external;

	function depositIntoStrategy(uint256 amount, uint256 minSharesOut) external;

	function uBalance() external view returns (uint256);

	function setMaxTvl(uint256) external;

	function getDepositAmnt(uint256 amount) external view returns (uint256);

	function getWithdrawAmnt(uint256 amount) external view returns (uint256);

	// function totalAssets() external view returns (uint256);
}

File 30 of 52 : ISuperComposableYield.sol
// SPDX-License-Identifier: GPL-3.0
/*
 * MIT License
 * ===========
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 */

pragma solidity 0.8.16;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ISCYVault } from "./ISCYVault.sol";

interface ISuperComposableYield is ISCYVault {
	/// @dev Emitted whenever the exchangeRate is updated
	event ExchangeRateUpdated(uint256 oldExchangeRate, uint256 newExchangeRate);

	/// @dev Emitted when any base tokens is deposited to mint shares
	event Deposit(
		address indexed caller,
		address indexed receiver,
		address indexed tokenIn,
		uint256 amountDeposited,
		uint256 amountScyOut
	);

	/// @dev Emitted when any shares are redeemed for base tokens
	event Redeem(
		address indexed caller,
		address indexed receiver,
		address indexed tokenOut,
		uint256 amountScyToRedeem,
		uint256 amountTokenOut
	);

	/// @dev check assetInfo for more information
	enum AssetType {
		TOKEN,
		LIQUIDITY
	}

	/**
	 * @notice mints an amount of shares by depositing a base token.
	 * @param receiver shares recipient address
	 * @param tokenIn address of the base tokens to mint shares
	 * @param amountTokenToPull amount of base tokens to be transferred from (`msg.sender`)
	 * @param minSharesOut reverts if amount of shares minted is lower than this
	 * @return amountSharesOut amount of shares minted
	 * @dev
	 *
	 * This contract receives base tokens using these two (possibly both) methods:
	 * - The tokens have been transferred directly to this contract prior to calling deposit().
	 * - Exactly `amountTokenToPull` are transferred to this contract using `transferFrom()` upon calling deposit().
	 *
	 * The amount of shares minted will be based on the combined amount of base tokens deposited
	 * using the given two methods.
	 *
	 * Emits a {Deposit} event
	 *
	 * Requirements:
	 * - (`baseTokenIn`) must be a valid base token.
	 * - There must be an ongoing approval from (`msg.sender`) for this contract with
	 * at least `amountTokenToPull` base tokens.
	 */
	function deposit(
		address receiver,
		address tokenIn,
		uint256 amountTokenToPull,
		uint256 minSharesOut
	) external payable returns (uint256 amountSharesOut);

	/**
	 * @notice redeems an amount of base tokens by burning some shares
	 * @param receiver recipient address
	 * @param amountSharesToPull amount of shares to be transferred from (`msg.sender`)
	 * @param tokenOut address of the base token to be redeemed
	 * @param minTokenOut reverts if amount of base token redeemed is lower than this
	 * @return amountTokenOut amount of base tokens redeemed
	 * @dev
	 *
	 * This contract receives shares using these two (possibly both) methods:
	 * - The shares have been transferred directly to this contract prior to calling redeem().
	 * - Exactly `amountSharesToPull` are transferred to this contract using `transferFrom()` upon calling redeem().
	 *
	 * The amount of base tokens redeemed based on the combined amount of shares deposited
	 * using the given two methods
	 *
	 * Emits a {Redeem} event
	 *
	 * Requirements:
	 * - (`tokenOut`) must be a valid base token.
	 * - There must be an ongoing approval from (`msg.sender`) for this contract with
	 * at least `amountSharesToPull` shares.
	 */
	function redeem(
		address receiver,
		uint256 amountSharesToPull,
		address tokenOut,
		uint256 minTokenOut
	) external returns (uint256 amountTokenOut);

	/**
	 * @notice returns the address of the underlying yield token
	 */
	function yieldToken() external view returns (address);

	/**
	 * @notice returns a list of all the base tokens that can be deposited to mint shares
	 */
	function getBaseTokens() external view returns (address[] memory res);

	/**
	 * @notice checks whether a token is a valid base token
	 * @notice returns a boolean indicating whether this is a valid token
	 */
	function isValidBaseToken(address token) external view returns (bool);

	/**
    * @notice This function contains information to interpret what the asset is
    * @notice decimals is the decimals to format asset balances
    * @notice if asset is an ERC20 token, assetType = 0, assetAddress is the address of the token
    * @notice if asset is liquidity of an AMM (like sqrt(k) in UniswapV2 forks), assetType = 1,
    assetAddress is the address of the LP token
    * @notice assetDecimals is the decimals of the asset
    */
	function assetInfo()
		external
		view
		returns (
			AssetType assetType,
			address assetAddress,
			uint8 assetDecimals
		);
}

File 31 of 52 : SectorErrors.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.16;

interface SectorErrors {
	error NotImplemented();
	error MaxTvlReached();
	error StrategyHasBalance();
	error MinLiquidity();
	error OnlyVault();
	error ZeroAmount();
}

File 32 of 52 : Structs.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

enum CallType {
	ADD_LIQUIDITY_AND_MINT,
	BORROWB,
	REMOVE_LIQ_AND_REPAY
}

enum VaultType {
	Strategy,
	Aggregator
}

enum EpochType {
	None,
	Withdraw,
	Full
}

enum NativeToken {
	None,
	Underlying,
	Short
}

struct CalleeData {
	CallType callType;
	bytes data;
}
struct AddLiquidityAndMintCalldata {
	uint256 uAmnt;
	uint256 sAmnt;
}
struct BorrowBCalldata {
	uint256 borrowAmount;
	bytes data;
}
struct RemoveLiqAndRepayCalldata {
	uint256 removeLpAmnt;
	uint256 repayUnderlying;
	uint256 repayShort;
	uint256 borrowUnderlying;
	// uint256 amountAMin;
	// uint256 amountBMin;
}

struct HarvestSwapParams {
	address[] path; //path that the token takes
	uint256 min; // min price of in token * 1e18 (computed externally based on spot * slippage + fees)
	uint256 deadline;
	bytes pathData; // uniswap3 path data
}

struct IMXConfig {
	address vault;
	address underlying;
	address short;
	address uniPair;
	address poolToken;
	address farmToken;
	address farmRouter;
}

struct HLPConfig {
	string symbol;
	string name;
	address underlying;
	address short;
	address cTokenLend;
	address cTokenBorrow;
	address uniPair;
	address uniFarm;
	address farmToken;
	uint256 farmId;
	address farmRouter;
	address comptroller;
	address lendRewardRouter;
	address lendRewardToken;
	address vault;
	NativeToken nativeToken;
}

struct EAction {
	address target;
	uint256 value;
	bytes data;
}

File 33 of 52 : IImpermax.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.16;

interface IMXRouter2 {
	function mint(
		address collateralToken,
		uint256 amount,
		address to,
		uint256 deadline
	) external returns (uint256 tokens);

	function borrow(
		address borrowable,
		uint256 amount,
		address to,
		uint256 deadline,
		bytes memory permitData
	) external;

	function borrowETH(
		address borrowable,
		uint256 amountETH,
		address to,
		uint256 deadline,
		bytes memory permitData
	) external;
}

interface IPoolToken {
	function totalBalance() external view returns (uint256);

	function mint(address minter) external returns (uint256 mintTokens);

	function underlying() external view returns (address);

	function exchangeRate() external view returns (uint256);

	function redeem(address redeemer) external returns (uint256 redeemAmount);
}

interface IBorrowable {
	function borrow(
		address borrower,
		address receiver,
		uint256 borrowAmount,
		bytes calldata data
	) external;

	function borrowApprove(address spender, uint256 value) external returns (bool);

	function accrueInterest() external;

	function borrowBalance(address borrower) external view returns (uint256);

	function underlying() external view returns (address);

	function exchangeRate() external returns (uint256);

	function exchangeRateLast() external view returns (uint256);

	function totalSupply() external view returns (uint256);

	function totalBorrows() external view returns (uint256);

	function totalBalance() external view returns (uint256);

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

interface ICollateral {
	function safetyMarginSqrt() external view returns (uint256);

	function liquidationIncentive() external view returns (uint256);

	function underlying() external view returns (address);

	function borrowable0() external view returns (address);

	function borrowable1() external view returns (address);

	function accountLiquidity(address account)
		external
		view
		returns (uint256 liquidity, uint256 shortfall);

	function flashRedeem(
		address redeemer,
		uint256 redeemAmount,
		bytes calldata data
	) external;

	function mint(address minter) external returns (uint256 mintTokens);

	function exchangeRate() external view returns (uint256);

	function getPrices() external view returns (uint256 price0, uint256 price1);

	function balanceOf(address) external view returns (uint256);

	function getTwapPrice112x112() external view returns (uint224 twapPrice112x112);

	function simpleUniswapOracle() external view returns (address);

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

interface ImpermaxChef {
	function pendingReward(address borrowable, address _user) external view returns (uint256);

	function harvest(address borrowable, address to) external;

	function massHarvest(address[] calldata borrowables, address to) external;
}

File 34 of 52 : ISimpleUniswapOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

interface ISimpleUniswapOracle {
	event PriceUpdate(
		address indexed pair,
		uint256 priceCumulative,
		uint32 blockTimestamp,
		bool lastIsA
	);

	function MIN_T() external pure returns (uint32);

	function getBlockTimestamp() external view returns (uint32);

	function getPair(address uniswapV2Pair)
		external
		view
		returns (
			uint256 priceCumulativeA,
			uint256 priceCumulativeB,
			uint32 updateA,
			uint32 updateB,
			bool lastIsA,
			bool initialized
		);

	function initialize(address uniswapV2Pair) external;

	function getResult(address uniswapV2Pair) external returns (uint224 price, uint32 T);
}

File 35 of 52 : IUniswapV2Factory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

interface IUniswapV2Factory {
	event PairCreated(address indexed token0, address indexed token1, address pair, uint256);

	function feeTo() external view returns (address);

	function feeToSetter() external view returns (address);

	function getPair(address tokenA, address tokenB) external view returns (address pair);

	function allPairs(uint256) external view returns (address pair);

	function allPairsLength() external view returns (uint256);

	function createPair(address tokenA, address tokenB) external returns (address pair);

	function setFeeTo(address) external;

	function setFeeToSetter(address) external;
}

File 36 of 52 : IUniswapV2Pair.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

interface IUniswapV2Pair {
	event Approval(address indexed owner, address indexed spender, uint256 value);
	event Transfer(address indexed from, address indexed to, uint256 value);

	function name() external pure returns (string memory);

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

	function decimals() external pure returns (uint8);

	function totalSupply() external view returns (uint256);

	function balanceOf(address owner) external view returns (uint256);

	function allowance(address owner, address spender) external view returns (uint256);

	function approve(address spender, uint256 value) external returns (bool);

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

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

	function DOMAIN_SEPARATOR() external view returns (bytes32);

	function PERMIT_TYPEHASH() external pure returns (bytes32);

	function nonces(address owner) external view returns (uint256);

	function permit(
		address owner,
		address spender,
		uint256 value,
		uint256 deadline,
		uint8 v,
		bytes32 r,
		bytes32 s
	) external;

	event Mint(address indexed sender, uint256 amount0, uint256 amount1);
	event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
	event Swap(
		address indexed sender,
		uint256 amount0In,
		uint256 amount1In,
		uint256 amount0Out,
		uint256 amount1Out,
		address indexed to
	);
	event Sync(uint112 reserve0, uint112 reserve1);

	function MINIMUM_LIQUIDITY() external pure returns (uint256);

	function factory() external view returns (address);

	function token0() external view returns (address);

	function token1() external view returns (address);

	function getReserves()
		external
		view
		returns (
			uint112 reserve0,
			uint112 reserve1,
			uint32 blockTimestampLast
		);

	function price0CumulativeLast() external view returns (uint256);

	function price1CumulativeLast() external view returns (uint256);

	function kLast() external view returns (uint256);

	function mint(address to) external returns (uint256 liquidity);

	function burn(address to) external returns (uint256 amount0, uint256 amount1);

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

	function skim(address to) external;

	function sync() external;

	function initialize(address, address) external;
}

File 37 of 52 : IUniswapV2Router01.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

interface IUniswapV2Router01 {
	function factory() external pure returns (address);

	function WETH() external pure returns (address);

	function addLiquidity(
		address tokenA,
		address tokenB,
		uint256 amountADesired,
		uint256 amountBDesired,
		uint256 amountAMin,
		uint256 amountBMin,
		address to,
		uint256 deadline
	)
		external
		returns (
			uint256 amountA,
			uint256 amountB,
			uint256 liquidity
		);

	function addLiquidityETH(
		address token,
		uint256 amountTokenDesired,
		uint256 amountTokenMin,
		uint256 amountETHMin,
		address to,
		uint256 deadline
	)
		external
		payable
		returns (
			uint256 amountToken,
			uint256 amountETH,
			uint256 liquidity
		);

	function removeLiquidity(
		address tokenA,
		address tokenB,
		uint256 liquidity,
		uint256 amountAMin,
		uint256 amountBMin,
		address to,
		uint256 deadline
	) external returns (uint256 amountA, uint256 amountB);

	function removeLiquidityETH(
		address token,
		uint256 liquidity,
		uint256 amountTokenMin,
		uint256 amountETHMin,
		address to,
		uint256 deadline
	) external returns (uint256 amountToken, uint256 amountETH);

	function removeLiquidityWithPermit(
		address tokenA,
		address tokenB,
		uint256 liquidity,
		uint256 amountAMin,
		uint256 amountBMin,
		address to,
		uint256 deadline,
		bool approveMax,
		uint8 v,
		bytes32 r,
		bytes32 s
	) external returns (uint256 amountA, uint256 amountB);

	function removeLiquidityETHWithPermit(
		address token,
		uint256 liquidity,
		uint256 amountTokenMin,
		uint256 amountETHMin,
		address to,
		uint256 deadline,
		bool approveMax,
		uint8 v,
		bytes32 r,
		bytes32 s
	) external returns (uint256 amountToken, uint256 amountETH);

	function swapExactTokensForTokens(
		uint256 amountIn,
		uint256 amountOutMin,
		address[] calldata path,
		address to,
		uint256 deadline
	) external returns (uint256[] memory amounts);

	function swapTokensForExactTokens(
		uint256 amountOut,
		uint256 amountInMax,
		address[] calldata path,
		address to,
		uint256 deadline
	) external returns (uint256[] memory amounts);

	function swapExactETHForTokens(
		uint256 amountOutMin,
		address[] calldata path,
		address to,
		uint256 deadline
	) external payable returns (uint256[] memory amounts);

	function swapTokensForExactETH(
		uint256 amountOut,
		uint256 amountInMax,
		address[] calldata path,
		address to,
		uint256 deadline
	) external returns (uint256[] memory amounts);

	function swapExactTokensForETH(
		uint256 amountIn,
		uint256 amountOutMin,
		address[] calldata path,
		address to,
		uint256 deadline
	) external returns (uint256[] memory amounts);

	function swapETHForExactTokens(
		uint256 amountOut,
		address[] calldata path,
		address to,
		uint256 deadline
	) external payable returns (uint256[] memory amounts);

	function quote(
		uint256 amountA,
		uint256 reserveA,
		uint256 reserveB
	) external pure returns (uint256 amountB);

	function getAmountOut(
		uint256 amountIn,
		uint256 reserveIn,
		uint256 reserveOut
	) external pure returns (uint256 amountOut);

	function getAmountIn(
		uint256 amountOut,
		uint256 reserveIn,
		uint256 reserveOut
	) external pure returns (uint256 amountIn);

	function getAmountsOut(uint256 amountIn, address[] calldata path)
		external
		view
		returns (uint256[] memory amounts);

	function getAmountsIn(uint256 amountOut, address[] calldata path)
		external
		view
		returns (uint256[] memory amounts);
}

File 38 of 52 : IWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

interface IWETH {
	function deposit() external payable;

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

	function withdraw(uint256) external;

	function balanceOf(address) external returns (uint256);
}

File 39 of 52 : FixedPointMathLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.16;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
	/*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

	uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

	function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
		return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
	}

	function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
		return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
	}

	function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
		return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
	}

	function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
		return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
	}

	/*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

	function mulDivDown(
		uint256 x,
		uint256 y,
		uint256 denominator
	) internal pure returns (uint256 z) {
		assembly {
			// Store x * y in z for now.
			z := mul(x, y)

			// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
			if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
				revert(0, 0)
			}

			// Divide z by the denominator.
			z := div(z, denominator)
		}
	}

	function mulDivUp(
		uint256 x,
		uint256 y,
		uint256 denominator
	) internal pure returns (uint256 z) {
		assembly {
			// Store x * y in z for now.
			z := mul(x, y)

			// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
			if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
				revert(0, 0)
			}

			// First, divide z - 1 by the denominator and add 1.
			// We allow z - 1 to underflow if z is 0, because we multiply the
			// end result by 0 if z is zero, ensuring we return 0 if z is zero.
			z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
		}
	}

	function rpow(
		uint256 x,
		uint256 n,
		uint256 scalar
	) internal pure returns (uint256 z) {
		assembly {
			switch x
			case 0 {
				switch n
				case 0 {
					// 0 ** 0 = 1
					z := scalar
				}
				default {
					// 0 ** n = 0
					z := 0
				}
			}
			default {
				switch mod(n, 2)
				case 0 {
					// If n is even, store scalar in z for now.
					z := scalar
				}
				default {
					// If n is odd, store x in z for now.
					z := x
				}

				// Shifting right by 1 is like dividing by 2.
				let half := shr(1, scalar)

				for {
					// Shift n right by 1 before looping to halve it.
					n := shr(1, n)
				} n {
					// Shift n right by 1 each iteration to halve it.
					n := shr(1, n)
				} {
					// Revert immediately if x ** 2 would overflow.
					// Equivalent to iszero(eq(div(xx, x), x)) here.
					if shr(128, x) {
						revert(0, 0)
					}

					// Store x squared.
					let xx := mul(x, x)

					// Round to the nearest number.
					let xxRound := add(xx, half)

					// Revert if xx + half overflowed.
					if lt(xxRound, xx) {
						revert(0, 0)
					}

					// Set x to scaled xxRound.
					x := div(xxRound, scalar)

					// If n is even:
					if mod(n, 2) {
						// Compute z * x.
						let zx := mul(z, x)

						// If z * x overflowed:
						if iszero(eq(div(zx, x), z)) {
							// Revert if x is non-zero.
							if iszero(iszero(x)) {
								revert(0, 0)
							}
						}

						// Round to the nearest number.
						let zxRound := add(zx, half)

						// Revert if zx + half overflowed.
						if lt(zxRound, zx) {
							revert(0, 0)
						}

						// Return properly scaled zxRound.
						z := div(zxRound, scalar)
					}
				}
			}
		}
	}

	/*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

	function sqrt(uint256 x) internal pure returns (uint256 z) {
		assembly {
			// Start off with z at 1.
			z := 1

			// Used below to help find a nearby power of 2.
			let y := x

			// Find the lowest power of 2 that is at least sqrt(x).
			if iszero(lt(y, 0x100000000000000000000000000000000)) {
				y := shr(128, y) // Like dividing by 2 ** 128.
				z := shl(64, z) // Like multiplying by 2 ** 64.
			}
			if iszero(lt(y, 0x10000000000000000)) {
				y := shr(64, y) // Like dividing by 2 ** 64.
				z := shl(32, z) // Like multiplying by 2 ** 32.
			}
			if iszero(lt(y, 0x100000000)) {
				y := shr(32, y) // Like dividing by 2 ** 32.
				z := shl(16, z) // Like multiplying by 2 ** 16.
			}
			if iszero(lt(y, 0x10000)) {
				y := shr(16, y) // Like dividing by 2 ** 16.
				z := shl(8, z) // Like multiplying by 2 ** 8.
			}
			if iszero(lt(y, 0x100)) {
				y := shr(8, y) // Like dividing by 2 ** 8.
				z := shl(4, z) // Like multiplying by 2 ** 4.
			}
			if iszero(lt(y, 0x10)) {
				y := shr(4, y) // Like dividing by 2 ** 4.
				z := shl(2, z) // Like multiplying by 2 ** 2.
			}
			if iszero(lt(y, 0x8)) {
				// Equivalent to 2 ** z.
				z := shl(1, z)
			}

			// Shifting right by 1 is like dividing by 2.
			z := shr(1, add(z, div(x, z)))
			z := shr(1, add(z, div(x, z)))
			z := shr(1, add(z, div(x, z)))
			z := shr(1, add(z, div(x, z)))
			z := shr(1, add(z, div(x, z)))
			z := shr(1, add(z, div(x, z)))
			z := shr(1, add(z, div(x, z)))

			// Compute a rounded down version of z.
			let zRoundDown := div(x, z)

			// If zRoundDown is smaller, use it.
			if lt(zRoundDown, z) {
				z := zRoundDown
			}
		}
	}
}

File 40 of 52 : SafeETH.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.16;

library SafeETH {
	function safeTransferETH(address to, uint256 amount) internal {
		bool callStatus;

		assembly {
			// Transfer the ETH and store if it succeeded or not.
			callStatus := call(gas(), to, amount, 0, 0, 0, 0)
		}

		require(callStatus, "ETH_TRANSFER_FAILED");
	}
}

File 41 of 52 : UniUtils.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
import "../interfaces/uniswap/IUniswapV2Pair.sol";
import "../interfaces/uniswap/IUniswapV2Router01.sol";
import "../interfaces/uniswap/IUniswapV2Factory.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

library UniUtils {
	using SafeERC20 for IERC20;

	function _getPairTokens(IUniswapV2Pair pair) internal view returns (address, address) {
		return (pair.token0(), pair.token1());
	}

	function _getPairReserves(
		IUniswapV2Pair pair,
		address tokenA,
		address tokenB
	) internal view returns (uint256 reserveA, uint256 reserveB) {
		(address token0, ) = _sortTokens(tokenA, tokenB);
		(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
		(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
	}

	// given some amount of an asset and lp reserves, returns an equivalent amount of the other asset
	function _quote(
		uint256 amountA,
		uint256 reserveA,
		uint256 reserveB
	) internal pure returns (uint256 amountB) {
		require(amountA > 0, "UniUtils: INSUFFICIENT_AMOUNT");
		require(reserveA > 0 && reserveB > 0, "UniUtils: INSUFFICIENT_LIQUIDITY");
		amountB = (amountA * reserveB) / reserveA;
	}

	function _sortTokens(address tokenA, address tokenB)
		internal
		pure
		returns (address token0, address token1)
	{
		require(tokenA != tokenB, "UniUtils: IDENTICAL_ADDRESSES");
		(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
		require(token0 != address(0), "UniUtils: ZERO_ADDRESS");
	}

	function _getAmountOut(
		IUniswapV2Pair pair,
		uint256 amountIn,
		address inToken,
		address outToken
	) internal view returns (uint256 amountOut) {
		require(amountIn > 0, "UniUtils: INSUFFICIENT_INPUT_AMOUNT");
		(uint256 reserveIn, uint256 reserveOut) = _getPairReserves(pair, inToken, outToken);
		uint256 amountInWithFee = amountIn * 997;
		uint256 numerator = amountInWithFee * reserveOut;
		uint256 denominator = reserveIn * 1000 + amountInWithFee;
		amountOut = numerator / denominator;
	}

	function _getAmountIn(
		IUniswapV2Pair pair,
		uint256 amountOut,
		address inToken,
		address outToken
	) internal view returns (uint256 amountIn) {
		require(amountOut > 0, "UniUtils: INSUFFICIENT_OUTPUT_AMOUNT");
		(uint256 reserveIn, uint256 reserveOut) = _getPairReserves(pair, inToken, outToken);
		uint256 numerator = reserveIn * amountOut * 1000;
		uint256 denominator = (reserveOut - amountOut) * 997;
		amountIn = (numerator / denominator) + 1;
	}

	function _swapExactTokensForTokens(
		IUniswapV2Pair pair,
		uint256 amountIn,
		address inToken,
		address outToken
	) internal returns (uint256) {
		uint256 amountOut = _getAmountOut(pair, amountIn, inToken, outToken);
		if (amountOut == 0) return 0;
		_swap(pair, amountIn, amountOut, inToken, outToken);
		return amountOut;
	}

	function _swapTokensForExactTokens(
		IUniswapV2Pair pair,
		uint256 amountOut,
		address inToken,
		address outToken
	) internal returns (uint256) {
		uint256 amountIn = _getAmountIn(pair, amountOut, inToken, outToken);
		_swap(pair, amountIn, amountOut, inToken, outToken);
		return amountIn;
	}

	function _swap(
		IUniswapV2Pair pair,
		uint256 amountIn,
		uint256 amountOut,
		address inToken,
		address outToken
	) internal {
		(address token0, ) = _sortTokens(outToken, inToken);
		(uint256 amount0Out, uint256 amount1Out) = inToken == token0
			? (uint256(0), amountOut)
			: (amountOut, uint256(0));
		IERC20(inToken).safeTransfer(address(pair), amountIn);
		pair.swap(amount0Out, amount1Out, address(this), new bytes(0));
	}
}

File 42 of 52 : IMX.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import { IMXCore, IBase, IERC20 } from "./IMXCore.sol";
import { IMXFarm } from "./IMXFarm.sol";
import { IMXConfig } from "../../interfaces/Structs.sol";
import { Auth, AuthConfig } from "../../common/Auth.sol";

// import "hardhat/console.sol";

contract IMX is IMXCore, IMXFarm {
	constructor(AuthConfig memory authConfig, IMXConfig memory config)
		Auth(authConfig)
		IMXFarm(
			config.underlying,
			config.uniPair,
			config.poolToken,
			config.farmRouter,
			config.farmToken
		)
		IMXCore(config.vault, config.underlying, config.short)
	{}

	function tarotBorrow(
		address a,
		address b,
		uint256 c,
		bytes calldata data
	) external {
		impermaxBorrow(a, b, c, data);
	}

	function tarotRedeem(
		address a,
		uint256 redeemAmount,
		bytes calldata data
	) external {
		impermaxRedeem(a, redeemAmount, data);
	}

	function underlying() public view override(IBase, IMXCore) returns (IERC20) {
		return super.underlying();
	}
}

File 43 of 52 : IMXCore.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

import { IBase, HarvestSwapParams } from "../mixins/IBase.sol";
import { IIMXFarm } from "../mixins/IIMXFarm.sol";
import { UniUtils, IUniswapV2Pair } from "../../libraries/UniUtils.sol";
import { FixedPointMathLib } from "../../libraries/FixedPointMathLib.sol";
import { ISimpleUniswapOracle } from "../../interfaces/uniswap/ISimpleUniswapOracle.sol";

import { StratAuth } from "../../common/StratAuth.sol";
import { ISCYStrategy } from "../../interfaces/ERC5115/ISCYStrategy.sol";

// import "hardhat/console.sol";

abstract contract IMXCore is ReentrancyGuard, StratAuth, IBase, IIMXFarm, ISCYStrategy {
	using FixedPointMathLib for uint256;
	using UniUtils for IUniswapV2Pair;
	using SafeERC20 for IERC20;

	event Deposit(address sender, uint256 amount);
	event Redeem(address sender, uint256 amount);

	// event RebalanceLoan(address indexed sender, uint256 startLoanHealth, uint256 updatedLoanHealth);
	event SetRebalanceThreshold(uint256 rebalanceThreshold);
	// this determines our default leverage position
	event SetSafetyMarginSqrt(uint256 safetyMarginSqrt);

	event Harvest(uint256 harvested); // this is actual the tvl before harvest
	event Rebalance(uint256 shortPrice, uint256 tvlBeforeRebalance, uint256 positionOffset);
	event SetMaxPriceOffset(uint256 maxPriceOffset);

	uint256 constant MINIMUM_LIQUIDITY = 1000;
	uint256 constant BPS_ADJUST = 10000;

	IERC20 private _underlying;
	IERC20 private _short;

	uint16 public rebalanceThreshold = 400; // 4% of lp
	// price move before liquidation
	uint256 private _safetyMarginSqrt = 1.140175425e18; // sqrt of 130%
	uint256 public maxPriceOffset = .2e18;

	modifier checkPrice(uint256 expectedPrice, uint256 maxDelta) {
		// parameter validation
		// to prevent manipulation by manager
		if (!hasRole(GUARDIAN, msg.sender)) {
			uint256 oraclePrice = shortToUnderlyingOracleUpdate(1e18);
			uint256 oracleDelta = oraclePrice > expectedPrice
				? oraclePrice - expectedPrice
				: expectedPrice - oraclePrice;
			if ((1e18 * (oracleDelta + maxDelta)) / expectedPrice > maxPriceOffset)
				revert OverMaxPriceOffset();
		}

		uint256 currentPrice = _shortToUnderlying(1e18);
		uint256 delta = expectedPrice > currentPrice
			? expectedPrice - currentPrice
			: currentPrice - expectedPrice;
		if (delta > maxDelta) revert SlippageExceeded();
		_;
	}

	constructor(
		address vault_,
		address underlying_,
		address short_
	) {
		vault = vault_;
		_underlying = IERC20(underlying_);
		_short = IERC20(short_);

		// _underlying.safeApprove(vault, type(uint256).max);

		// init default params
		// deployer is not owner so we set these manually

		// TODO param?
		rebalanceThreshold = 400;
		emit SetRebalanceThreshold(400);

		maxPriceOffset = .2e18;
		emit SetMaxPriceOffset(maxPriceOffset);

		_safetyMarginSqrt = 1.140175425e18;
		emit SetSafetyMarginSqrt(_safetyMarginSqrt);
	}

	// guardian can adjust max price offset if needed
	function setMaxPriceOffset(uint256 _maxPriceOffset) public onlyRole(GUARDIAN) {
		maxPriceOffset = _maxPriceOffset;
		emit SetMaxPriceOffset(_maxPriceOffset);
	}

	function safetyMarginSqrt() public view override returns (uint256) {
		return _safetyMarginSqrt;
	}

	function decimals() public view returns (uint8) {
		return IERC20Metadata(address(_underlying)).decimals();
	}

	// OWNER CONFIG

	function setRebalanceThreshold(uint16 rebalanceThreshold_) public onlyOwner {
		require(rebalanceThreshold_ >= 100, "STRAT: BAD_INPUT");
		rebalanceThreshold = rebalanceThreshold_;
		emit SetRebalanceThreshold(rebalanceThreshold_);
	}

	function setSafetyMarginSqrt(uint256 safetyMarginSqrt_) public onlyOwner {
		_safetyMarginSqrt = safetyMarginSqrt_;
		emit SetSafetyMarginSqrt(_safetyMarginSqrt);
	}

	// PUBLIC METHODS

	function short() public view override returns (IERC20) {
		return _short;
	}

	function underlying() public view virtual override(IBase, ISCYStrategy) returns (IERC20) {
		return _underlying;
	}

	// deposit underlying and recieve lp tokens
	function deposit(uint256 underlyingAmnt) external onlyVault nonReentrant returns (uint256) {
		if (underlyingAmnt == 0) return 0; // cannot deposit 0
		uint256 startBalance = collateralToken().balanceOf(address(this));
		_increasePosition(underlyingAmnt);
		uint256 endBalance = collateralToken().balanceOf(address(this));
		return endBalance - startBalance;
	}

	// redeem lp for underlying
	function redeem(address recipient, uint256 removeCollateral)
		public
		onlyVault
		returns (uint256 amountTokenOut)
	{
		if (removeCollateral < MINIMUM_LIQUIDITY) return 0; // cannot redeem 0
		// this is the full amount of LP tokens totalSupply of shares is entitled to
		_decreasePosition(removeCollateral);

		// make sure we never have any extra underlying dust sitting around
		// all 'extra' underlying should allways be transferred back to the vault

		unchecked {
			amountTokenOut = _underlying.balanceOf(address(this));
		}
		_underlying.safeTransfer(recipient, amountTokenOut);
		emit Redeem(msg.sender, amountTokenOut);
	}

	/// @notice decreases position based to desired LP amount
	/// @dev ** does not rebalance remaining portfolio
	/// @param removeCollateral amount of callateral token to remove
	function _decreasePosition(uint256 removeCollateral) internal {
		(uint256 uBorrowBalance, uint256 sBorrowBalance) = _updateAndGetBorrowBalances();

		uint256 balance = collateralToken().balanceOf(address(this));
		uint256 lp = _getLiquidity(balance);

		// remove lp & repay underlying loan
		// round up to avoid under-repaying
		uint256 removeLp = lp.mulDivUp(removeCollateral, balance);
		uint256 uRepay = uBorrowBalance.mulDivUp(removeCollateral, balance);
		uint256 sRepay = sBorrowBalance.mulDivUp(removeCollateral, balance);

		_removeIMXLiquidity(removeLp, uRepay, sRepay, 0);
	}

	// increases the position based on current desired balance
	// ** does not rebalance remaining portfolio
	function _increasePosition(uint256 amntUnderlying) internal {
		if (amntUnderlying < MINIMUM_LIQUIDITY) return; // avoid imprecision
		(uint256 uLp, uint256 sLp) = _getLPBalances();
		(uint256 uBorrowBalance, uint256 sBorrowBalance) = _getBorrowBalances();

		uint256 tvl = getAndUpdateTvl() - amntUnderlying;

		uint256 uBorrow;
		uint256 sBorrow;
		uint256 uAddLp;
		uint256 sAddLp;

		// on initial deposit or if amount are below threshold for accurate accounting
		if (
			tvl < MINIMUM_LIQUIDITY ||
			uLp < MINIMUM_LIQUIDITY ||
			sLp < MINIMUM_LIQUIDITY ||
			uBorrowBalance < MINIMUM_LIQUIDITY ||
			sBorrowBalance < MINIMUM_LIQUIDITY
		) {
			uBorrow = (_optimalUBorrow() * amntUnderlying) / 1e18;
			uAddLp = amntUnderlying + uBorrow;
			sBorrow = _underlyingToShort(uAddLp);
			sAddLp = sBorrow;
		} else {
			// if tvl > 0 we need to keep the exact proportions of current position
			// to ensure we have correct accounting independent of price moves
			uBorrow = (uBorrowBalance * amntUnderlying) / tvl;
			uAddLp = (uLp * amntUnderlying) / tvl;
			sBorrow = (sBorrowBalance * amntUnderlying) / tvl;
			sAddLp = _underlyingToShort(uAddLp);
		}

		_addIMXLiquidity(uAddLp, sAddLp, uBorrow, sBorrow);
	}

	// use the return of the function to estimate pending harvest via staticCall
	function harvest(HarvestSwapParams[] calldata harvestParams, HarvestSwapParams[] calldata)
		external
		onlyVault
		nonReentrant
		returns (uint256[] memory farmHarvest, uint256[] memory)
	{
		(uint256 startTvl, , , , , ) = getTVL();

		farmHarvest = new uint256[](1);
		// return amount of underlying tokens harvested
		(, farmHarvest[0]) = _harvestFarm(harvestParams[0]);

		// compound our lp position
		_increasePosition(_underlying.balanceOf(address(this)));
		emit Harvest(startTvl);
		return (farmHarvest, new uint256[](0));
	}

	function rebalance(uint256 expectedPrice, uint256 maxDelta)
		external
		onlyRole(MANAGER)
		checkPrice(expectedPrice, maxDelta)
		nonReentrant
	{
		// call this first to ensure we use an updated borrowBalance when computing offset
		uint256 tvl = getAndUpdateTvl();
		uint256 positionOffset = getPositionOffset();

		// don't rebalance unless we exceeded the threshold
		// GUARDIAN can execute rebalance any time
		if (positionOffset <= rebalanceThreshold && !hasRole(GUARDIAN, msg.sender))
			revert RebalanceThreshold();

		if (tvl == 0) return;
		uint256 targetUBorrow = (tvl * _optimalUBorrow()) / 1e18;
		uint256 targetUnderlyingLP = tvl + targetUBorrow;

		(uint256 underlyingLp, ) = _getLPBalances();
		uint256 targetShortLp = _underlyingToShort(targetUnderlyingLP);
		(uint256 uBorrowBalance, uint256 sBorrowBalance) = _updateAndGetBorrowBalances();

		// TODO account for uBalance?
		// uint256 uBalance = underlying().balanceOf(address(this));

		if (underlyingLp > targetUnderlyingLP) {
			uint256 uRepay;
			uint256 uBorrow;
			if (uBorrowBalance > targetUBorrow) uRepay = uBorrowBalance - targetUBorrow;
			else uBorrow = targetUBorrow - uBorrowBalance;

			uint256 sRepay = sBorrowBalance > targetShortLp ? sBorrowBalance - targetShortLp : 0;

			uint256 lp = _getLiquidity();
			uint256 removeLp = lp - (lp * targetUnderlyingLP) / underlyingLp;
			_removeIMXLiquidity(removeLp, uRepay, sRepay, uBorrow);
		} else if (targetUnderlyingLP > underlyingLp) {
			uint256 uBorrow = targetUBorrow > uBorrowBalance ? targetUBorrow - uBorrowBalance : 0;
			uint256 sBorrow = targetShortLp > sBorrowBalance ? targetShortLp - sBorrowBalance : 0;

			uint256 uAdd = targetUnderlyingLP - underlyingLp;

			// extra underlying balance will get re-paid automatically
			_addIMXLiquidity(
				uAdd,
				_underlyingToShort(uAdd), // this is more precise than targetShortLp - shortLP because of rounding
				uBorrow,
				sBorrow
			);
		}
		emit Rebalance(_shortToUnderlying(1e18), positionOffset, tvl);
	}

	// vault handles slippage
	function closePosition(uint256) public onlyVault returns (uint256 balance) {
		(uint256 uRepay, uint256 sRepay) = _updateAndGetBorrowBalances();
		uint256 removeLp = _getLiquidity();
		_removeIMXLiquidity(removeLp, uRepay, sRepay, 0);
		// transfer funds to vault
		balance = _underlying.balanceOf(address(this));
		_underlying.safeTransfer(vault, balance);
	}

	// TVL
	function getMaxTvl() public view returns (uint256) {
		(uint256 uBorrow, uint256 sBorrow) = _getBorrowBalances();
		uint256 sMax = sBorrowable().totalBalance();
		uint256 optimalBorrow = _optimalUBorrow();
		return
			// adjust the availableToBorrow to account for leverage
			min(
				((uBorrow + uBorrowable().totalBalance()) * 1e18) / optimalBorrow,
				_shortToUnderlying((sBorrow + sMax) * 1e18) / (optimalBorrow + 1e18)
			);
	}

	// TODO should we compute pending farm & lending rewards here?
	function getAndUpdateTvl() public returns (uint256 tvl) {
		(uint256 uBorrow, uint256 shortPosition) = _updateAndGetBorrowBalances();
		uint256 borrowBalance = _shortToUnderlying(shortPosition) + uBorrow;
		uint256 shortP = _short.balanceOf(address(this));
		uint256 shortBalance = shortP == 0
			? 0
			: _shortToUnderlying(_short.balanceOf(address(this)));
		(uint256 underlyingLp, ) = _getLPBalances();
		uint256 underlyingBalance = _underlying.balanceOf(address(this));
		uint256 assets = underlyingLp * 2 + underlyingBalance + shortBalance;
		tvl = assets > borrowBalance ? assets - borrowBalance : 0;
	}

	function getTotalTVL() public view returns (uint256 tvl) {
		(tvl, , , , , ) = getTVL();
	}

	function getTvl() public view returns (uint256 tvl) {
		(tvl, , , , , ) = getTVL();
	}

	function getTVL()
		public
		view
		returns (
			uint256 tvl,
			uint256,
			uint256 borrowPosition,
			uint256 borrowBalance,
			uint256 lpBalance,
			uint256 underlyingBalance
		)
	{
		uint256 underlyingBorrow;
		(underlyingBorrow, borrowPosition) = _getBorrowBalances();
		borrowBalance = _shortToUnderlying(borrowPosition) + underlyingBorrow;

		uint256 shortPosition = _short.balanceOf(address(this));
		uint256 shortBalance = shortPosition == 0 ? 0 : _shortToUnderlying(shortPosition);

		(uint256 underlyingLp, uint256 shortLp) = _getLPBalances();
		lpBalance = underlyingLp + _shortToUnderlying(shortLp);
		underlyingBalance = _underlying.balanceOf(address(this));
		uint256 assets = lpBalance + underlyingBalance + shortBalance;
		tvl = assets > borrowBalance ? assets - borrowBalance : 0;
	}

	function getPositionOffset() public view returns (uint256 positionOffset) {
		(, uint256 shortLp) = _getLPBalances();
		(, uint256 borrowBalance) = _getBorrowBalances();
		uint256 shortBalance = shortLp + _short.balanceOf(address(this));
		if (shortBalance == borrowBalance) return 0;
		// if short lp > 0 and borrowBalance is 0 we are off by inf, returning 100% should be enough
		if (borrowBalance == 0) return 10000;
		// this is the % by which our position has moved from beeing balanced

		positionOffset = shortBalance > borrowBalance
			? ((shortBalance - borrowBalance) * BPS_ADJUST) / borrowBalance
			: ((borrowBalance - shortBalance) * BPS_ADJUST) / borrowBalance;
	}

	// UTILS
	function getExpectedPrice() external view returns (uint256) {
		return _shortToUnderlying(1e18);
	}

	function getLPBalances() public view returns (uint256 underlyingLp, uint256 shortLp) {
		return _getLPBalances();
	}

	function getLiquidity() external view returns (uint256) {
		return _getLiquidity();
	}

	// used to estimate price of collateral token in underlying
	function collateralToUnderlying() public view returns (uint256) {
		(uint256 uR, uint256 sR, ) = pair().getReserves();
		(uR, sR) = address(_underlying) == pair().token0() ? (uR, sR) : (sR, uR);
		uint256 lp = pair().totalSupply();
		// for deposit of 1 underlying we get 1+_optimalUBorrow worth of lp -> collateral token
		return (1e18 * (uR * _getLiquidity(1e18))) / lp / (1e18 + _optimalUBorrow());
	}

	// in some cases the oracle needs to be updated externally
	// to be accessible by read methods like loanHealth();
	function updateOracle() public {
		try collateralToken().tarotPriceOracle() returns (address _oracle) {
			ISimpleUniswapOracle oracle = ISimpleUniswapOracle(_oracle);
			oracle.getResult(collateralToken().underlying());
		} catch {
			ISimpleUniswapOracle oracle = ISimpleUniswapOracle(
				collateralToken().simpleUniswapOracle()
			);
			oracle.getResult(collateralToken().underlying());
		}
	}

	function getLpToken() public view returns (address) {
		return address(collateralToken());
	}

	function getLpBalance() external view returns (uint256) {
		return collateralToken().balanceOf(address(this));
	}

	function getWithdrawAmnt(uint256 lpTokens) public view returns (uint256) {
		return (lpTokens * collateralToUnderlying()) / 1e18;
	}

	function getDepositAmnt(uint256 uAmnt) public view returns (uint256) {
		return (uAmnt * 1e18) / collateralToUnderlying();
	}

	/// @dev we can call this method via staticall to get the loan health
	/// even when oracle has not been updated
	function callLoanHealth() external returns (uint256) {
		updateOracle();
		return loanHealth();
	}

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

	error RebalanceThreshold();
	error LowLoanHealth();
	error SlippageExceeded();
	error OverMaxPriceOffset();
}

File 44 of 52 : IMXFarm.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import { ICollateral, IPoolToken, IBorrowable, ImpermaxChef } from "../../interfaces/imx/IImpermax.sol";
import { HarvestSwapParams, IIMXFarm, IERC20, SafeERC20, IUniswapV2Pair, IUniswapV2Router01 } from "../mixins/IIMXFarm.sol";
import { UniUtils } from "../../libraries/UniUtils.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

import { CallType, CalleeData, AddLiquidityAndMintCalldata, BorrowBCalldata, RemoveLiqAndRepayCalldata } from "../../interfaces/Structs.sol";

// import "hardhat/console.sol";

abstract contract IMXFarm is IIMXFarm {
	using SafeERC20 for IERC20;
	using UniUtils for IUniswapV2Pair;
	// using FixedPointMathLib for uint256;

	IUniswapV2Pair public _pair;
	ICollateral private _collateralToken;
	IBorrowable private _uBorrowable;
	IBorrowable private _sBorrowable;
	IPoolToken private stakedToken;
	ImpermaxChef private _impermaxChef;

	IERC20 private _farmToken;
	IUniswapV2Router01 private _farmRouter;

	bool public flip;

	constructor(
		address underlying_,
		address pair_,
		address collateralToken_,
		address farmRouter_,
		address farmToken_
	) {
		_pair = IUniswapV2Pair(pair_);
		_collateralToken = ICollateral(collateralToken_);
		_uBorrowable = IBorrowable(_collateralToken.borrowable0());
		_sBorrowable = IBorrowable(_collateralToken.borrowable1());

		if (underlying_ != _uBorrowable.underlying()) {
			flip = true;
			(_uBorrowable, _sBorrowable) = (_sBorrowable, _uBorrowable);
		}
		stakedToken = IPoolToken(_collateralToken.underlying());
		_impermaxChef = ImpermaxChef(_uBorrowable.borrowTracker());
		_farmToken = IERC20(farmToken_);
		_farmRouter = IUniswapV2Router01(farmRouter_);

		// necessary farm approvals
		_farmToken.safeApprove(address(farmRouter_), type(uint256).max);
	}

	function impermaxChef() public view override returns (ImpermaxChef) {
		return _impermaxChef;
	}

	function collateralToken() public view override returns (ICollateral) {
		return _collateralToken;
	}

	function sBorrowable() public view override returns (IBorrowable) {
		return _sBorrowable;
	}

	function uBorrowable() public view override returns (IBorrowable) {
		return _uBorrowable;
	}

	function farmRouter() public view override returns (IUniswapV2Router01) {
		return _farmRouter;
	}

	function pair() public view override returns (IUniswapV2Pair) {
		return _pair;
	}

	function _addIMXLiquidity(
		uint256 underlyingAmnt,
		uint256 shortAmnt,
		uint256 uBorrow,
		uint256 sBorrow
	) internal virtual override {
		_sBorrowable.borrowApprove(address(_sBorrowable), sBorrow);

		// mint collateral
		bytes memory addLPData = abi.encode(
			CalleeData({
				callType: CallType.ADD_LIQUIDITY_AND_MINT,
				data: abi.encode(
					AddLiquidityAndMintCalldata({ uAmnt: underlyingAmnt, sAmnt: shortAmnt })
				)
			})
		);

		// borrow short data
		bytes memory borrowSData = abi.encode(
			CalleeData({
				callType: CallType.BORROWB,
				data: abi.encode(BorrowBCalldata({ borrowAmount: uBorrow, data: addLPData }))
			})
		);

		// flashloan borrow then add lp
		_sBorrowable.borrow(address(this), address(this), sBorrow, borrowSData);
	}

	function impermaxBorrow(
		address,
		address,
		uint256,
		bytes calldata data
	) public {
		// ensure that msg.sender is correct
		require(
			msg.sender == address(_sBorrowable) || msg.sender == address(_uBorrowable),
			"IMXFarm: NOT_BORROWABLE"
		);
		CalleeData memory calleeData = abi.decode(data, (CalleeData));

		if (calleeData.callType == CallType.ADD_LIQUIDITY_AND_MINT) {
			AddLiquidityAndMintCalldata memory d = abi.decode(
				calleeData.data,
				(AddLiquidityAndMintCalldata)
			);
			_addLp(d.uAmnt, d.sAmnt);
		} else if (calleeData.callType == CallType.BORROWB) {
			BorrowBCalldata memory d = abi.decode(calleeData.data, (BorrowBCalldata));
			_uBorrowable.borrow(address(this), address(this), d.borrowAmount, d.data);
		}
	}

	function _addLp(uint256 uAmnt, uint256 sAmnt) internal {
		{
			uint256 sBalance = short().balanceOf(address(this));
			uint256 uBalance = underlying().balanceOf(address(this));

			// TODO use swap fee to get exact amount out
			// if we have extra short tokens, trade them for underlying
			if (sBalance > sAmnt) {
				uBalance += pair()._swapExactTokensForTokens(
					sBalance - sAmnt,
					address(short()),
					address(underlying())
				);
				// sBalance = sAmnt now
			} else if (sAmnt > sBalance) {
				// when rebalancing we will never have more sAmnt than sBalance
				uBalance -= pair()._swapTokensForExactTokens(
					sAmnt - sBalance,
					address(underlying()),
					address(short())
				);
			}

			// we know that now our short balance is now exact sBalance = sAmnt
			// if we don't have enough underlying, we need to decrase sAmnt slighlty
			if (uBalance < uAmnt) {
				uAmnt = uBalance;
				uint256 sAmntNew = _underlyingToShort(uAmnt);
				// make sure we're not increaseing the amount
				if (sAmnt > sAmntNew) sAmnt = sAmntNew;
				else uAmnt = _shortToUnderlying(sAmnt);
			}
			if (uBalance > uAmnt) {
				// if we have extra underlying return to borrowable
				// TODO check that this gets accounted for
				underlying().safeTransfer(address(_uBorrowable), uBalance - uAmnt);
			}
		}

		underlying().safeTransfer(address(_pair), uAmnt);
		short().safeTransfer(address(_pair), sAmnt);

		uint256 liquidity = _pair.mint(address(this));

		// first we create staked token, then collateral token
		IERC20(address(_pair)).safeTransfer(address(stakedToken), liquidity);
		stakedToken.mint(address(_collateralToken));
		_collateralToken.mint(address(this));
	}

	function _removeIMXLiquidity(
		uint256 removeLpAmnt,
		uint256 repayUnderlying,
		uint256 repayShort,
		uint256 borrowUnderlying
	) internal override {
		uint256 redeemAmount = (removeLpAmnt * 1e18) / stakedToken.exchangeRate() + 1;

		bytes memory data = abi.encode(
			RemoveLiqAndRepayCalldata({
				removeLpAmnt: removeLpAmnt,
				repayUnderlying: repayUnderlying,
				repayShort: repayShort,
				borrowUnderlying: borrowUnderlying
			})
		);

		_collateralToken.flashRedeem(address(this), redeemAmount, data);
	}

	function impermaxRedeem(
		address,
		uint256 redeemAmount,
		bytes calldata data
	) public {
		require(msg.sender == address(_collateralToken), "IMXFarm: NOT_COLLATERAL");

		RemoveLiqAndRepayCalldata memory d = abi.decode(data, (RemoveLiqAndRepayCalldata));

		// redeem withdrawn staked coins
		IERC20(address(stakedToken)).safeTransfer(address(stakedToken), redeemAmount);
		stakedToken.redeem(address(this));

		// remove collateral
		(, uint256 shortAmnt) = _removeLiquidity(d.removeLpAmnt);

		// in some cases we need to borrow extra underlying
		if (d.borrowUnderlying > 0)
			_uBorrowable.borrow(address(this), address(this), d.borrowUnderlying, "");

		// trade extra tokens

		// if we have extra short tokens, trade them for underlying
		if (shortAmnt > d.repayShort) {
			// TODO edge case - not enough underlying?
			pair()._swapExactTokensForTokens(
				shortAmnt - d.repayShort,
				address(short()),
				address(underlying())
			);
			shortAmnt = d.repayShort;
		}
		// if we know the exact amount of short we must repay, then ensure we have that amount
		else if (shortAmnt < d.repayShort && d.repayShort != type(uint256).max) {
			uint256 amountOut = d.repayShort - shortAmnt;
			uint256 amountIn = pair()._getAmountIn(
				amountOut,
				address(underlying()),
				address(short())
			);
			uint256 inTokenBalance = underlying().balanceOf(address(this));
			if (amountIn > inTokenBalance) {
				shortAmnt += pair()._swapExactTokensForTokens(
					inTokenBalance,
					address(underlying()),
					address(short())
				);
			} else {
				pair()._swap(amountIn, amountOut, address(underlying()), address(short()));
				shortAmnt = d.repayShort;
			}
		}

		uint256 uBalance = underlying().balanceOf(address(this));

		// repay short loan
		short().safeTransfer(address(_sBorrowable), shortAmnt);
		_sBorrowable.borrow(address(this), address(0), 0, new bytes(0));

		// repay underlying loan
		if (uBalance > 0) {
			underlying().safeTransfer(
				address(_uBorrowable),
				d.repayUnderlying > uBalance ? uBalance : d.repayUnderlying
			);
			_uBorrowable.borrow(address(this), address(0), 0, new bytes(0));
		}

		uint256 cAmount = (redeemAmount * 1e18) / _collateralToken.exchangeRate() + 1;

		// uint256 colBal = _collateralToken.balanceOf(address(this));
		// TODO add tests to make ensure cAmount < colBal

		// return collateral token
		IERC20(address(_collateralToken)).safeTransfer(
			address(_collateralToken),
			// colBal < cAmount ? colBal : cAmount
			cAmount
		);
	}

	function pendingHarvest() external view override returns (uint256 harvested) {
		if (address(_impermaxChef) == address(0)) return 0;
		harvested =
			_impermaxChef.pendingReward(address(_sBorrowable), address(this)) +
			_impermaxChef.pendingReward(address(_uBorrowable), address(this));
	}

	function harvestIsEnabled() public view returns (bool) {
		return address(_impermaxChef) != address(0);
	}

	function _harvestFarm(HarvestSwapParams calldata harvestParams)
		internal
		override
		returns (uint256 harvested, uint256 amountOut)
	{
		// rewards are not enabled
		if (address(_impermaxChef) == address(0)) return (harvested, amountOut);
		address[] memory borrowables = new address[](2);
		borrowables[0] = address(_sBorrowable);
		borrowables[1] = address(_uBorrowable);

		_impermaxChef.massHarvest(borrowables, address(this));

		harvested = _farmToken.balanceOf(address(this));
		if (harvested == 0) return (harvested, amountOut);

		uint256[] memory amounts = _swap(
			_farmRouter,
			harvestParams,
			address(_farmToken),
			harvested
		);
		amountOut = amounts[amounts.length - 1];
		emit HarvestedToken(address(_farmToken), harvested);
	}

	function _getLiquidity() internal view override returns (uint256) {
		return _getLiquidity(_collateralToken.balanceOf(address(this)));
	}

	function _getLiquidity(uint256 balance) internal view override returns (uint256) {
		if (balance == 0) return 0;
		return
			(stakedToken.exchangeRate() * (_collateralToken.exchangeRate() * (balance - 1))) /
			1e18 /
			1e18;
	}

	function _getBorrowBalances() internal view override returns (uint256, uint256) {
		return (
			_uBorrowable.borrowBalance(address(this)),
			_sBorrowable.borrowBalance(address(this))
		);
	}

	function accrueInterest() public override {
		_sBorrowable.accrueInterest();
		_uBorrowable.accrueInterest();
	}

	function _updateAndGetBorrowBalances() internal override returns (uint256, uint256) {
		accrueInterest();
		return _getBorrowBalances();
	}

	/// @notice borrow amount of underlying for every 1e18 of deposit
	/// @dev currently cannot go below ~2.02x lev
	function _optimalUBorrow() internal view override returns (uint256 uBorrow) {
		uint256 l = _collateralToken.liquidationIncentive();
		// this is the adjusted safety margin - how far we stay from liquidation
		uint256 s = (_collateralToken.safetyMarginSqrt() * safetyMarginSqrt()) / 1e18;
		uBorrow = (1e18 * (2e18 - (l * s) / 1e18)) / ((l * 1e18) / s + (l * s) / 1e18 - 2e18);
	}

	function loanHealth() public view override returns (uint256) {
		// this updates the oracle
		uint256 balance = IERC20(address(_collateralToken)).balanceOf(address(this));
		if (balance == 0) return 100e18;
		uint256 liq = (balance * _collateralToken.exchangeRate()) / 1e18;
		(uint256 available, uint256 shortfall) = _collateralToken.accountLiquidity(address(this));
		if (liq < shortfall) return 0; // we are way past liquidation
		return shortfall == 0 ? (1e18 * (liq + available)) / liq : (1e18 * (liq - shortfall)) / liq;
	}

	function shortToUnderlyingOracleUpdate(uint256 amount) public override returns (uint256) {
		(bool success, bytes memory data) = address(collateralToken()).call(
			abi.encodeWithSignature("getPrices()")
		);
		if (!success) revert OracleUpdate();
		(uint256 price0, uint256 price1) = abi.decode(data, (uint256, uint256));
		return flip ? (amount * price0) / price1 : (amount * price1) / price0;
	}

	function shortToUnderlyingOracle(uint256 amount) public view override returns (uint256) {
		try collateralToken().getPrices() returns (uint256 price0, uint256 price1) {
			return flip ? (amount * price0) / price1 : (amount * price1) / price0;
		} catch {
			revert OracleUpdate();
		}
	}

	error OracleUpdate();
}

File 45 of 52 : IMXLendStrategy.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.16;

import { IPoolToken, IBorrowable } from "../../interfaces/imx/IImpermax.sol";
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SCYVault } from "../../vaults/ERC5115/SCYVault.sol";
import { SafeETH } from "../../libraries/SafeETH.sol";
import { AuthConfig, Auth } from "../../common/Auth.sol";
import { FeeConfig, Fees } from "../../common/Fees.sol";
import { HarvestSwapParams } from "../../interfaces/Structs.sol";
import { StratAuthLight } from "../../common/StratAuthLight.sol";
import { ISCYStrategy } from "../../interfaces/ERC5115/ISCYStrategy.sol";

// import "hardhat/console.sol";

contract IMXLendStrategy is StratAuthLight, ISCYStrategy {
	using SafeERC20 for IERC20;

	IPoolToken public immutable poolToken;
	IERC20 public immutable underlying;

	constructor(address _vault, address _poolToken) {
		vault = _vault;
		poolToken = IPoolToken(_poolToken);
		underlying = IERC20(poolToken.underlying());
	}

	function deposit(uint256 amount) public onlyVault returns (uint256) {
		underlying.safeTransfer(address(poolToken), amount);
		return poolToken.mint(address(this));
	}

	function redeem(address to, uint256 amount) public onlyVault returns (uint256 amountOut) {
		if (amount == 0) return 0;
		IERC20(address(poolToken)).safeTransfer(address(poolToken), amount);
		amountOut = poolToken.redeem(to);
		return amountOut;
	}

	function getAndUpdateTvl() external returns (uint256) {
		// exchange rate does the accrual
		uint256 exchangeRate = IBorrowable(address(poolToken)).exchangeRate();
		uint256 balance = IERC20(address(poolToken)).balanceOf(address(this));
		uint256 underlyingBalance = (balance * exchangeRate) / 1e18;
		return underlyingBalance;
	}

	function getTvl() external view returns (uint256) {
		uint256 balance = IERC20(address(poolToken)).balanceOf(address(this));
		uint256 exchangeRate = IBorrowable(address(poolToken)).exchangeRateLast();
		uint256 underlyingBalance = (balance * exchangeRate) / 1e18;
		return underlyingBalance;
	}

	function closePosition(uint256) external onlyVault returns (uint256) {
		uint256 yeildTokenAmnt = IERC20(address(poolToken)).balanceOf(address(this));
		IERC20(address(poolToken)).safeTransfer(address(poolToken), yeildTokenAmnt);
		return IPoolToken(poolToken).redeem(address(vault));
	}

	// TOOD fraction of total deposits
	function getMaxTvl() external pure returns (uint256) {
		return type(uint256).max;
	}

	function collateralToUnderlying() external view returns (uint256) {
		return IBorrowable(address(poolToken)).exchangeRateLast();
	}

	function harvest(HarvestSwapParams[] calldata params, HarvestSwapParams[] calldata)
		external
		onlyVault
		returns (uint256[] memory harvest1, uint256[] memory harvest2)
	{}

	function getLpToken() public view returns (address) {
		return address(poolToken);
	}

	function getLpBalance() external view returns (uint256) {
		return IERC20(address(poolToken)).balanceOf(address(this));
	}

	function getWithdrawAmnt(uint256 lpTokens) public view returns (uint256) {
		return (lpTokens * IBorrowable(address(poolToken)).exchangeRateLast()) / 1e18;
	}

	function getDepositAmnt(uint256 uAmnt) public view returns (uint256) {
		return (uAmnt * 1e18) / IBorrowable(address(poolToken)).exchangeRateLast();
	}
}

File 46 of 52 : IBase.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

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

// all interfaces need to inherit from base
abstract contract IBase {
	function short() public view virtual returns (IERC20);

	function underlying() public view virtual returns (IERC20);
}

File 47 of 52 : IFarmable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

import { IUniswapV2Router01 } from "../../interfaces/uniswap/IUniswapV2Router01.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { HarvestSwapParams, IBase } from "./IBase.sol";

abstract contract IFarmable is IBase {
	using SafeERC20 for IERC20;

	event HarvestedToken(address indexed token, uint256 amount);

	function _swap(
		IUniswapV2Router01 router,
		HarvestSwapParams calldata swapParams,
		address from,
		uint256 amount
	) internal returns (uint256[] memory) {
		address out = swapParams.path[swapParams.path.length - 1];
		// ensure malicious harvester is not trading with wrong tokens
		// TODO should we add more validation to prevent malicious path?
		require(
			((swapParams.path[0] == address(from) && (out == address(short()))) ||
				out == address(underlying())),
			"IFarmable: WRONG_PATH"
		);
		return
			router.swapExactTokensForTokens(
				amount,
				swapParams.min,
				swapParams.path, // optimal route determined externally
				address(this),
				swapParams.deadline
			);
	}
}

File 48 of 52 : IIMXFarm.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;

import { IBorrowable, ICollateral, ImpermaxChef } from "../../interfaces/imx/IImpermax.sol";

import { IBase, HarvestSwapParams } from "./IBase.sol";
import { IUniLp, IUniswapV2Pair, SafeERC20, IERC20 } from "./IUniLp.sol";
import { IFarmable, IUniswapV2Router01 } from "./IFarmable.sol";

abstract contract IIMXFarm is IBase, IFarmable, IUniLp {
	function loanHealth() public view virtual returns (uint256);

	function sBorrowable() public view virtual returns (IBorrowable);

	function uBorrowable() public view virtual returns (IBorrowable);

	function collateralToken() public view virtual returns (ICollateral);

	function impermaxChef() public view virtual returns (ImpermaxChef);

	function pendingHarvest() external view virtual returns (uint256 harvested);

	function farmRouter() public view virtual returns (IUniswapV2Router01);

	function _getBorrowBalances()
		internal
		view
		virtual
		returns (uint256 underlyingAmnt, uint256 shortAmnt);

	function _updateAndGetBorrowBalances()
		internal
		virtual
		returns (uint256 underlyingAmnt, uint256 shortAmnt);

	function _optimalUBorrow() internal view virtual returns (uint256 uBorrow);

	function _harvestFarm(HarvestSwapParams calldata swapParams)
		internal
		virtual
		returns (uint256, uint256);

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

	function accrueInterest() public virtual;

	function _addIMXLiquidity(
		uint256 underlyingAmnt,
		uint256 shortAmnt,
		uint256 uBorrow,
		uint256 sBorrow
	) internal virtual;

	function _removeIMXLiquidity(
		uint256 removeLp,
		uint256 repayUnderlying,
		uint256 repayShort,
		uint256 uBorrow
	) internal virtual;

	function shortToUnderlyingOracleUpdate(uint256 amount) public virtual returns (uint256);

	function shortToUnderlyingOracle(uint256 amount) public view virtual returns (uint256);
}

File 49 of 52 : ILp.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

abstract contract ILp {
	function _quote(
		uint256 amount,
		address token0,
		address token1
	) internal view virtual returns (uint256 price);

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

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

	function _addLiquidity(uint256 amountToken0, uint256 amountToken1)
		internal
		virtual
		returns (uint256 liquidity);

	function _removeLiquidity(uint256 liquidity) internal virtual returns (uint256, uint256);

	function _getLPBalances()
		internal
		view
		virtual
		returns (uint256 underlyingBalance, uint256 shortBalance);
}

File 50 of 52 : IUniLp.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

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

import { IUniswapV2Pair } from "../../interfaces/uniswap/IUniswapV2Pair.sol";
import { UniUtils } from "../../libraries/UniUtils.sol";

import { IBase } from "./IBase.sol";
import { ILp } from "./ILp.sol";

// import "hardhat/console.sol";

abstract contract IUniLp is IBase, ILp {
	using SafeERC20 for IERC20;
	using UniUtils for IUniswapV2Pair;

	function pair() public view virtual returns (IUniswapV2Pair);

	// should only be called after oracle or user-input swap price check
	function _addLiquidity(uint256 amountToken0, uint256 amountToken1)
		internal
		virtual
		override
		returns (uint256 liquidity)
	{
		underlying().safeTransfer(address(pair()), amountToken0);
		short().safeTransfer(address(pair()), amountToken1);
		liquidity = pair().mint(address(this));
	}

	function _removeLiquidity(uint256 liquidity)
		internal
		virtual
		override
		returns (uint256, uint256)
	{
		IERC20(address(pair())).safeTransfer(address(pair()), liquidity);
		(address tokenA, ) = UniUtils._sortTokens(address(underlying()), address(short()));
		(uint256 amountToken0, uint256 amountToken1) = pair().burn(address(this));
		return
			tokenA == address(underlying())
				? (amountToken0, amountToken1)
				: (amountToken1, amountToken0);
	}

	function _quote(
		uint256 amount,
		address token0,
		address token1
	) internal view virtual override returns (uint256 price) {
		if (amount == 0) return 0;
		(uint256 reserve0, uint256 reserve1) = pair()._getPairReserves(token0, token1);
		price = UniUtils._quote(amount, reserve0, reserve1);
	}

	// fetches and sorts the reserves for a uniswap pair
	function getUnderlyingShortReserves() public view returns (uint256 reserveA, uint256 reserveB) {
		(reserveA, reserveB) = pair()._getPairReserves(address(underlying()), address(short()));
	}

	function _getLPBalances()
		internal
		view
		override
		returns (uint256 underlyingBalance, uint256 shortBalance)
	{
		uint256 totalLp = _getLiquidity();
		(uint256 totalUnderlyingBalance, uint256 totalShortBalance) = getUnderlyingShortReserves();
		uint256 total = pair().totalSupply();
		underlyingBalance = (totalUnderlyingBalance * totalLp) / total;
		shortBalance = (totalShortBalance * totalLp) / total;
	}

	// this is the current uniswap price
	function _shortToUnderlying(uint256 amount) internal view virtual returns (uint256) {
		return amount == 0 ? 0 : _quote(amount, address(short()), address(underlying()));
	}

	// this is the current uniswap price
	function _underlyingToShort(uint256 amount) internal view virtual returns (uint256) {
		return amount == 0 ? 0 : _quote(amount, address(underlying()), address(short()));
	}
}

File 51 of 52 : SCYBase.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.16;

import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { ISuperComposableYield } from "../../interfaces/ERC5115/ISuperComposableYield.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20MetadataUpgradeable as IERC20Metadata } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import { SectorErrors } from "../../interfaces/SectorErrors.sol";
import { Fees } from "../../common/Fees.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";
import { FixedPointMathLib } from "../../libraries/FixedPointMathLib.sol";

// import "hardhat/console.sol";

abstract contract SCYBase is
	ISuperComposableYield,
	ReentrancyGuard,
	ERC20,
	Fees,
	ERC20Permit,
	Pausable,
	SectorErrors
{
	using SafeERC20 for IERC20;
	using FixedPointMathLib for uint256;

	address internal constant NATIVE = address(0);
	uint256 internal constant ONE = 1e18;
	uint256 public constant MIN_LIQUIDITY = 1e3;

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

	constructor(string memory _name, string memory _symbol)
		ERC20(_name, _symbol)
		ERC20Permit(_name)
	{}

	/*///////////////////////////////////////////////////////////////
                    DEPOSIT/REDEEM USING BASE TOKENS
    //////////////////////////////////////////////////////////////*/

	/**
	 * @dev See {ISuperComposableYield-deposit}
	 */
	function deposit(
		address receiver,
		address tokenIn,
		uint256 amountTokenToPull,
		uint256 minSharesOut
	) external payable nonReentrant returns (uint256 amountSharesOut) {
		require(isValidBaseToken(tokenIn), "SCY: Invalid tokenIn");

		if (tokenIn == NATIVE && amountTokenToPull != 0) revert CantPullEth();
		else if (amountTokenToPull != 0) _transferIn(tokenIn, msg.sender, amountTokenToPull);

		// this depends on strategy
		// this supports depositing directly into strategy to save gas
		uint256 amountIn = getFloatingAmount(tokenIn);
		if (amountIn == 0) revert ZeroAmount();

		amountSharesOut = _deposit(receiver, tokenIn, amountIn);
		if (amountSharesOut < minSharesOut) revert InsufficientOut(amountSharesOut, minSharesOut);

		// lock minimum liquidity if totalSupply is 0
		if (totalSupply() == 0) {
			if (MIN_LIQUIDITY > amountSharesOut) revert MinLiquidity();
			amountSharesOut -= MIN_LIQUIDITY;
			_mint(address(1), MIN_LIQUIDITY);
		}

		_mint(receiver, amountSharesOut);
		emit Deposit(msg.sender, receiver, tokenIn, amountIn, amountSharesOut);
	}

	/**
	 * @dev See {ISuperComposableYield-redeem}
	 */
	function redeem(
		address receiver,
		uint256 amountSharesToRedeem,
		address tokenOut,
		uint256 minTokenOut
	) external nonReentrant returns (uint256 amountTokenOut) {
		require(isValidBaseToken(tokenOut), "SCY: invalid tokenOut");

		// this is to handle a case where the strategy sends funds directly to user
		uint256 amountToTransfer;
		(amountTokenOut, amountToTransfer) = _redeem(receiver, tokenOut, amountSharesToRedeem);
		if (amountTokenOut < minTokenOut) revert InsufficientOut(amountTokenOut, minTokenOut);

		if (amountToTransfer > 0) _transferOut(tokenOut, receiver, amountToTransfer);

		emit Redeem(msg.sender, receiver, tokenOut, amountSharesToRedeem, amountTokenOut);
	}

	/**
	 * @notice mint shares based on the deposited base tokens
	 * @param tokenIn base token address used to mint shares
	 * @param amountDeposited amount of base tokens deposited
	 * @return amountSharesOut amount of shares minted
	 */
	function _deposit(
		address receiver,
		address tokenIn,
		uint256 amountDeposited
	) internal virtual returns (uint256 amountSharesOut);

	/**
	 * @notice redeems base tokens based on amount of shares to be burned
	 * @param tokenOut address of the base token to be redeemed
	 * @param amountSharesToRedeem amount of shares to be burned
	 * @return amountTokenOut amount of base tokens redeemed
	 */
	function _redeem(
		address receiver,
		address tokenOut,
		uint256 amountSharesToRedeem
	) internal virtual returns (uint256 amountTokenOut, uint256 tokensToTransfer);

	/*///////////////////////////////////////////////////////////////
										Accounting
		//////////////////////////////////////////////////////////////*/

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

	function toSharesAfterDeposit(uint256 assets) public view virtual returns (uint256) {
		uint256 supply = totalSupply(); // Saves an extra SLOAD if totalSupply is non-zero.
		uint256 _totalAssets = totalAssets() - assets;
		// when _totalAssets < MIN_LIQUIDITY, treat it as 0
		if (_totalAssets < MIN_LIQUIDITY || supply == 0) return assets;
		return assets.mulDivDown(supply, _totalAssets);
	}

	function convertToShares(uint256 assets) public view virtual returns (uint256) {
		uint256 supply = totalSupply();
		uint256 _totalAssets = totalAssets();
		// when _totalAssets < MIN_LIQUIDITY, treat it as 0
		if (_totalAssets < MIN_LIQUIDITY || supply == 0) return assets;
		return assets.mulDivDown(supply, _totalAssets);
	}

	function convertToAssets(uint256 shares) public view virtual returns (uint256) {
		uint256 supply = totalSupply(); // Saves an extra SLOAD if totalSupply is non-zero.
		return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
	}

	// VIRTUALS
	function getFloatingAmount(address token) public view virtual returns (uint256);

	/**
	 * @notice See {ISuperComposableYield-getBaseTokens}
	 */
	function getBaseTokens() external view virtual override returns (address[] memory res);

	/**
	 * @dev See {ISuperComposableYield-isValidBaseToken}
	 */
	function isValidBaseToken(address token) public view virtual override returns (bool);

	function _transferIn(
		address token,
		address to,
		uint256 amount
	) internal virtual;

	function _transferOut(
		address token,
		address to,
		uint256 amount
	) internal virtual;

	function _depositNative() internal virtual;

	function sendERC20ToStrategy() public view virtual returns (bool) {
		return true;
	}

	function pause() public onlyRole(GUARDIAN) {
		_pause();
	}

	function unpause() public onlyRole(GUARDIAN) {
		_unpause();
	}

	function _beforeTokenTransfer(
		address from,
		address to,
		uint256 amount
	) internal override whenNotPaused {
		super._beforeTokenTransfer(from, to, amount);
	}

	error CantPullEth();
	error InsufficientOut(uint256 amountOut, uint256 minOut);
}

File 52 of 52 : SCYVault.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.16;

import { SCYBase, IERC20, IERC20Metadata, SafeERC20 } from "./SCYBase.sol";
import { IMX } from "../../strategies/imx/IMX.sol";
import { SafeETH } from "../../libraries/SafeETH.sol";
import { FixedPointMathLib } from "../../libraries/FixedPointMathLib.sol";
import { IWETH } from "../../interfaces/uniswap/IWETH.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { EAction, HarvestSwapParams } from "../../interfaces/Structs.sol";
import { VaultType, EpochType } from "../../interfaces/Structs.sol";
import { SectorErrors } from "../../interfaces/SectorErrors.sol";
import { ISCYStrategy } from "../../interfaces/ERC5115/ISCYStrategy.sol";
import { SCYVaultConfig } from "../../interfaces/ERC5115/ISCYVault.sol";
import { Auth, AuthConfig } from "../../common/Auth.sol";
import { Fees, FeeConfig } from "../../common/Fees.sol";

// import "hardhat/console.sol";

contract SCYVault is SCYBase {
	using SafeERC20 for IERC20;
	using FixedPointMathLib for uint256;

	VaultType public constant vaultType = VaultType.Strategy;
	EpochType public constant epochType = EpochType.None;

	event Harvest(
		address indexed treasury,
		uint256 underlyingProfit,
		uint256 performanceFee,
		uint256 managementFee,
		uint256 sharesFees,
		uint256 tvl
	);

	uint256 public lastHarvestTimestamp;
	uint256 public lastHarvestInterval; // time interval of last harvest
	uint256 public maxLockedProfit;

	ISCYStrategy public strategy;

	// immutables
	address public immutable override yieldToken;
	uint16 public immutable strategyId; // strategy-specific id ex: for MasterChef or 1155
	bool public immutable acceptsNativeToken;
	IERC20 public immutable underlying;

	uint256 public maxTvl; // pack all params and balances
	uint256 public vaultTvl; // strategy balance in underlying
	uint256 public uBalance; // underlying balance held by vault

	event MaxTvlUpdated(uint256 maxTvl);
	event StrategyUpdated(address strategy);

	modifier isInitialized() {
		if (address(strategy) == address(0)) revert NotInitialized();
		_;
	}

	constructor(
		AuthConfig memory authConfig,
		FeeConfig memory feeConfig,
		SCYVaultConfig memory vaultConfig
	) SCYBase(vaultConfig.name, vaultConfig.symbol) Auth(authConfig) Fees(feeConfig) {
		// strategy init
		yieldToken = vaultConfig.yieldToken;
		strategy = ISCYStrategy(vaultConfig.addr);
		strategyId = vaultConfig.strategyId;
		underlying = vaultConfig.underlying;
		acceptsNativeToken = vaultConfig.acceptsNativeToken;
		maxTvl = vaultConfig.maxTvl;

		lastHarvestTimestamp = block.timestamp;
	}

	/*///////////////////////////////////////////////////////////////
                    CONFIG
    //////////////////////////////////////////////////////////////*/

	function getMaxTvl() public view returns (uint256) {
		return min(maxTvl, strategy.getMaxTvl());
	}

	function setMaxTvl(uint256 _maxTvl) public onlyRole(GUARDIAN) {
		maxTvl = _maxTvl;
		emit MaxTvlUpdated(min(maxTvl, strategy.getMaxTvl()));
	}

	function initStrategy(address config) public onlyRole(GUARDIAN) {
		if (address(strategy) != address(0)) revert NoReInit();
		strategy = ISCYStrategy(config);
		_validateStrategy();
		emit StrategyUpdated(config);
	}

	function updateStrategy(address config) public onlyOwner {
		uint256 tvl = strategy.getAndUpdateTvl();
		if (tvl > 0) revert InvalidStrategyUpdate();
		strategy = ISCYStrategy(config);
		_validateStrategy();
		emit StrategyUpdated(config);
	}

	function _validateStrategy() internal view {
		if (strategy.underlying() != underlying) revert InvalidStrategy();
	}

	function _depositNative() internal override {
		IWETH(address(underlying)).deposit{ value: msg.value }();
		if (sendERC20ToStrategy()) IERC20(underlying).safeTransfer(address(strategy), msg.value);
	}

	function _deposit(
		address,
		address token,
		uint256 amount
	) internal override isInitialized returns (uint256 sharesOut) {
		if (vaultTvl + amount > getMaxTvl()) revert MaxTvlReached();
		// if we have any float in the contract we cannot do deposit accounting
		if (uBalance >= MIN_LIQUIDITY) revert DepositsPaused();
		if (token == NATIVE) _depositNative();
		uint256 yieldTokenAdded = strategy.deposit(amount);
		sharesOut = toSharesAfterDeposit(yieldTokenAdded);
		vaultTvl += amount;
	}

	function _redeem(
		address receiver,
		address token,
		uint256 sharesToRedeem
	) internal override returns (uint256 amountTokenOut, uint256 amountToTransfer) {
		uint256 _totalSupply = totalSupply();

		// adjust share amount for lockedProfit
		// we still burn the full sharesToRedeem, but fewer assets are returned
		// this is required in order to prevent harvest front-running
		uint256 adjustedShares = (sharesToRedeem * _totalSupply) / (_totalSupply + lockedProfit());
		uint256 yeildTokenRedeem = convertToAssets(adjustedShares);

		// vault may hold float of underlying, in this case, add a share of reserves to withdrawal
		// TODO why not use underlying.balanceOf?
		uint256 reserves = uBalance;
		uint256 shareOfReserves = (reserves * adjustedShares) / _totalSupply;

		// Update strategy underlying reserves balance
		if (shareOfReserves > 0) uBalance -= shareOfReserves;

		receiver = token == NATIVE ? address(this) : receiver;

		// if we also need to send the user share of reserves, we allways withdraw to vault first
		// if we don't we can have strategy withdraw directly to user if possible
		if (shareOfReserves > 0) {
			// don't try to redeem small amounts, it will fail
			if (yeildTokenRedeem >= MIN_LIQUIDITY)
				(amountTokenOut) = strategy.redeem(receiver, yeildTokenRedeem);
			amountTokenOut += shareOfReserves;
			amountToTransfer += shareOfReserves;
		} else (amountTokenOut) = strategy.redeem(receiver, yeildTokenRedeem);

		// its possible that cached vault tvl is lower than actual tvl
		uint256 _vaultTvl = vaultTvl;
		vaultTvl = _vaultTvl > amountTokenOut ? _vaultTvl - amountTokenOut : 0;

		// it requested token is native, convert to native
		if (token == NATIVE) {
			IWETH(address(underlying)).withdraw(amountTokenOut);
			// ensure that we are tranferring these tokens to the user
			amountToTransfer = amountTokenOut;
		}

		_burn(msg.sender, sharesToRedeem);
		// edge case if total supply is MIN_LIQUIDITY
		// re-enable deposits by setting uBalance to 0
		if (_totalSupply - sharesToRedeem <= MIN_LIQUIDITY) uBalance = 0;
	}

	/// @notice harvest strategy
	function harvest(
		uint256 expectedTvl,
		uint256 maxDelta,
		HarvestSwapParams[] calldata swap1,
		HarvestSwapParams[] calldata swap2
	) external onlyRole(MANAGER) returns (uint256[] memory harvest1, uint256[] memory harvest2) {
		/// TODO refactor this
		uint256 _uBalance = underlying.balanceOf(address(this));
		uint256 startTvl = strategy.getAndUpdateTvl() + _uBalance;

		_checkSlippage(expectedTvl, startTvl, maxDelta);

		// this allows us to skip strategy harvest if needeed
		if (swap1.length > 0 || swap2.length > 0)
			(harvest1, harvest2) = strategy.harvest(swap1, swap2);

		uint256 tvl = strategy.getTvl() + _uBalance;

		uint256 prevTvl = vaultTvl;
		uint256 timestamp = block.timestamp;
		uint256 profit = tvl > prevTvl ? tvl - prevTvl : 0;

		// PROCESS VAULT FEES
		uint256 _performanceFee = profit == 0 ? 0 : (profit * performanceFee) / 1e18;
		uint256 _managementFee = managementFee == 0
			? 0
			: (managementFee * tvl * (timestamp - lastHarvestTimestamp)) / 1e18 / 365 days;

		uint256 totalFees = _performanceFee + _managementFee;
		uint256 feeShares;
		if (totalFees > 0) {
			// we know that totalSupply != 0 and tvl > totalFees
			// this results in more accurate accounting considering dilution
			feeShares = totalFees.mulDivDown(totalSupply(), tvl - totalFees);
			_mint(treasury, feeShares);
		}

		emit Harvest(treasury, profit, _performanceFee, _managementFee, feeShares, tvl);

		vaultTvl = tvl;

		// only use harvest profits in lockedProfit?
		uint256 lProfit = tvl > startTvl ? tvl - startTvl : 0;

		// keep previous locked profits + add current profits
		// locked profit is denominated in shares
		uint256 newLockedProfit;
		if (lProfit > totalFees) {
			uint256 lockedValue = lProfit - totalFees;
			newLockedProfit = (lockedValue).mulDivDown(totalSupply(), tvl - lockedValue);
		}
		maxLockedProfit = lockedProfit() + newLockedProfit;

		// we use 3/4 of the interval for locked profits
		lastHarvestInterval = ((timestamp - lastHarvestTimestamp) * 3) / 4;
		lastHarvestTimestamp = timestamp;
	}

	/// @notice Calculates the current amount of locked profit.
	/// lockedProfit is denominated in shares and is used to inflate total supplly	on withdrawal
	/// @return The current amount of locked profit.
	function lockedProfit() public view returns (uint256) {
		// Get the last harvest and harvest delay.
		uint256 previousHarvest = lastHarvestTimestamp;
		uint256 harvestInterval = lastHarvestInterval;

		unchecked {
			// If the harvest delay has passed, there is no locked profit.
			// Cannot overflow on human timescales since harvestInterval is capped.
			if (block.timestamp >= previousHarvest + harvestInterval) return 0;

			// Get the maximum amount we could return.
			uint256 maximumLockedProfit = maxLockedProfit;

			// Compute how much profit remains locked based on the last harvest and harvest delay.
			// It's impossible for the previous harvest to be in the future, so this will never underflow.
			return
				maximumLockedProfit -
				(maximumLockedProfit * (block.timestamp - previousHarvest)) /
				harvestInterval;
		}
	}

	function _checkSlippage(
		uint256 expectedValue,
		uint256 actualValue,
		uint256 maxDelta
	) internal pure {
		uint256 delta = expectedValue > actualValue
			? expectedValue - actualValue
			: actualValue - expectedValue;
		if (delta > maxDelta) revert SlippageExceeded();
	}

	/// @notice slippage is computed in shares
	function depositIntoStrategy(uint256 underlyingAmount, uint256 minAmountOut)
		public
		onlyRole(GUARDIAN)
	{
		if (underlyingAmount > uBalance) revert NotEnoughUnderlying();
		uBalance -= underlyingAmount;
		underlying.safeTransfer(address(strategy), underlyingAmount);
		uint256 yAdded = strategy.deposit(underlyingAmount);
		uint256 virtualSharesOut = convertToShares(yAdded);
		if (virtualSharesOut < minAmountOut) revert SlippageExceeded();
		emit DepositIntoStrategy(msg.sender, underlyingAmount);
	}

	/// @notice slippage is computed in underlying
	function withdrawFromStrategy(uint256 shares, uint256 minAmountOut) public onlyRole(GUARDIAN) {
		uint256 yieldTokenAmnt = convertToAssets(shares);
		uint256 underlyingWithdrawn = strategy.redeem(address(this), yieldTokenAmnt);
		if (underlyingWithdrawn < minAmountOut) revert SlippageExceeded();
		uBalance = underlying.balanceOf(address(this));
		emit WithdrawFromStrategy(msg.sender, underlyingWithdrawn);
	}

	function closePosition(uint256 minAmountOut, uint256 slippageParam) public onlyRole(MANAGER) {
		uint256 underlyingWithdrawn = strategy.closePosition(slippageParam);
		if (underlyingWithdrawn < minAmountOut) revert SlippageExceeded();
		uBalance = underlying.balanceOf(address(this));
		emit ClosePosition(msg.sender, underlyingWithdrawn);
	}

	/// @notice this method allows an arbitrary method to be called by the owner in case of emergency
	/// owner must be a timelock contract in order to allow users to redeem funds in case they suspect
	/// this action to be malicious
	function emergencyAction(EAction[] calldata actions) public payable onlyOwner {
		uint256 l = actions.length;
		for (uint256 i; i < l; ++i) {
			address target = actions[i].target;
			bytes memory data = actions[i].data;
			(bool success, ) = target.call{ value: actions[i].value }(data);
			require(success, "emergencyAction failed");
			emit EmergencyAction(target, data);
		}
	}

	function getStrategyTvl() public view returns (uint256) {
		return strategy.getTvl();
	}

	/// no slippage check - slippage can be done on vault level
	/// against total expected balance of all strategies
	function getAndUpdateTvl() public returns (uint256 tvl) {
		uint256 stratTvl = strategy.getAndUpdateTvl();
		uint256 balance = underlying.balanceOf(address(this));
		tvl = balance + stratTvl;
	}

	function getTvl() public view returns (uint256 tvl) {
		uint256 stratTvl = strategy.getTvl();
		uint256 balance = underlying.balanceOf(address(this));
		tvl = balance + stratTvl;
	}

	function totalAssets() public view override returns (uint256) {
		return strategy.getLpBalance();
	}

	function isPaused() public view returns (bool) {
		return uBalance >= MIN_LIQUIDITY;
	}

	// used for estimates only
	function exchangeRateUnderlying() public view returns (uint256) {
		uint256 _totalSupply = totalSupply();
		if (_totalSupply == 0) return strategy.collateralToUnderlying();
		uint256 tvl = underlying.balanceOf(address(this)) + strategy.getTvl();
		return tvl.mulDivUp(ONE, _totalSupply);
	}

	function getUpdatedUnderlyingBalance(address user) external returns (uint256) {
		uint256 userBalance = balanceOf(user);
		uint256 _totalSupply = totalSupply();
		if (_totalSupply == 0 || userBalance == 0) return 0;
		uint256 tvl = underlying.balanceOf(address(this)) + strategy.getAndUpdateTvl();
		return (tvl * userBalance) / _totalSupply;
	}

	function underlyingBalance(address user) external view returns (uint256) {
		uint256 userBalance = balanceOf(user);
		uint256 _totalSupply = totalSupply();
		if (_totalSupply == 0 || userBalance == 0) return 0;
		uint256 tvl = underlying.balanceOf(address(this)) + strategy.getTvl();
		uint256 adjustedShares = (userBalance * _totalSupply) / (_totalSupply + lockedProfit());
		return (tvl * adjustedShares) / _totalSupply;
	}

	function underlyingToShares(uint256 uAmnt) public view returns (uint256) {
		uint256 _totalSupply = totalSupply();
		uint256 tvl = getTvl();
		if (_totalSupply == 0 || tvl == 0)
			return uAmnt.mulDivDown(ONE, strategy.collateralToUnderlying());
		return uAmnt.mulDivDown(_totalSupply, tvl);
	}

	function sharesToUnderlying(uint256 shares) public view returns (uint256) {
		uint256 _totalSupply = totalSupply();
		if (_totalSupply == 0) return (shares * strategy.collateralToUnderlying()) / ONE;
		uint256 adjustedShares = (shares * _totalSupply) / (_totalSupply + lockedProfit());
		return adjustedShares.mulDivDown(getTvl(), _totalSupply);
	}

	///
	///  Yield Token Overrides
	///

	function assetInfo()
		public
		view
		returns (
			AssetType assetType,
			address assetAddress,
			uint8 assetDecimals
		)
	{
		address yToken = yieldToken;
		return (AssetType.LIQUIDITY, yToken, IERC20Metadata(yToken).decimals());
	}

	function underlyingDecimals() public view returns (uint8) {
		return IERC20Metadata(address(underlying)).decimals();
	}

	/// make sure to override this - actual logic should use floating strategy balances
	function getFloatingAmount(address token)
		public
		view
		virtual
		override
		returns (uint256 fltAmnt)
	{
		if (token == address(underlying))
			return
				sendERC20ToStrategy()
					? underlying.balanceOf(address(strategy))
					: underlying.balanceOf(address(this)) - uBalance;
		if (token == NATIVE) return address(this).balance;
	}

	function decimals() public pure override returns (uint8) {
		return 18;
	}

	/// @dev used to compute slippage on withdraw
	function getWithdrawAmnt(uint256 shares) public view returns (uint256) {
		uint256 assets = convertToAssets(shares);
		return ISCYStrategy(strategy).getWithdrawAmnt(assets);
	}

	/// @dev used to compute slippage on deposit
	function getDepositAmnt(uint256 uAmnt) public view returns (uint256) {
		uint256 _totalAssets = totalAssets();
		uint256 _totalSupply = totalSupply();
		if (_totalAssets == 0 && _totalSupply > 0) return uAmnt.mulDivDown(_totalSupply, uBalance);
		uint256 assets = ISCYStrategy(strategy).getDepositAmnt(uAmnt);
		return _totalSupply == 0 ? assets : assets.mulDivDown(_totalSupply, _totalAssets);
	}

	function getBaseTokens() external view virtual override returns (address[] memory res) {
		if (acceptsNativeToken) {
			res = new address[](2);
			res[1] = NATIVE;
		} else res = new address[](1);
		res[0] = address(underlying);
	}

	function isValidBaseToken(address token) public view virtual override returns (bool) {
		return token == address(underlying) || (acceptsNativeToken && token == NATIVE);
	}

	// send funds to strategy
	function _transferIn(
		address token,
		address from,
		uint256 amount
	) internal virtual override {
		address to = sendERC20ToStrategy() ? address(strategy) : address(this);
		IERC20(token).safeTransferFrom(from, to, amount);
	}

	// send funds to user
	function _transferOut(
		address token,
		address to,
		uint256 amount
	) internal virtual override {
		if (token == NATIVE) {
			SafeETH.safeTransferETH(to, amount);
		} else {
			IERC20(token).safeTransfer(to, amount);
		}
	}

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

	event WithdrawFromStrategy(address indexed caller, uint256 amount);
	event DepositIntoStrategy(address indexed caller, uint256 amount);
	event ClosePosition(address indexed caller, uint256 amount);
	event EmergencyAction(address target, bytes callData);

	error InvalidStrategyUpdate();
	error NoReInit();
	error InvalidStrategy();
	error NotInitialized();
	error DepositsPaused();
	error StrategyExists();
	error StrategyDoesntExist();
	error NotEnoughUnderlying();
	error SlippageExceeded();
}

Settings
{
  "evmVersion": "london",
  "libraries": {},
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": true
  },
  "optimizer": {
    "enabled": true,
    "runs": 1
  },
  "remappings": [],
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract ABI

[{"inputs":[{"internalType":"address","name":"_vault","type":"address"},{"internalType":"address","name":"_poolToken","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"MaxTvlReached","type":"error"},{"inputs":[],"name":"MinLiquidity","type":"error"},{"inputs":[],"name":"NotImplemented","type":"error"},{"inputs":[],"name":"OnlyVault","type":"error"},{"inputs":[],"name":"StrategyHasBalance","type":"error"},{"inputs":[],"name":"ZeroAmount","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"EmergencyAction","type":"event"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"closePosition","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collateralToUnderlying","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"internalType":"struct EAction[]","name":"actions","type":"tuple[]"}],"name":"emergencyAction","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"getAndUpdateTvl","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"uAmnt","type":"uint256"}],"name":"getDepositAmnt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLpBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLpToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMaxTvl","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getTvl","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"lpTokens","type":"uint256"}],"name":"getWithdrawAmnt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"pathData","type":"bytes"}],"internalType":"struct HarvestSwapParams[]","name":"params","type":"tuple[]"},{"components":[{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"pathData","type":"bytes"}],"internalType":"struct HarvestSwapParams[]","name":"","type":"tuple[]"}],"name":"harvest","outputs":[{"internalType":"uint256[]","name":"harvest1","type":"uint256[]"},{"internalType":"uint256[]","name":"harvest2","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"poolToken","outputs":[{"internalType":"contract IPoolToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"underlying","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

60c06040523480156200001157600080fd5b5060405162001567380380620015678339810160408190526200003491620000ef565b600080546001600160a01b0319166001600160a01b03848116919091179091558116608081905260408051636f307dc360e01b81529051636f307dc3916004808201926020929091908290030181865afa15801562000097573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000bd919062000127565b6001600160a01b031660a052506200014c9050565b80516001600160a01b0381168114620000ea57600080fd5b919050565b600080604083850312156200010357600080fd5b6200010e83620000d2565b91506200011e60208401620000d2565b90509250929050565b6000602082840312156200013a57600080fd5b6200014582620000d2565b9392505050565b60805160a05161137e620001e9600039600081816101850152610a2c0152600081816101d8015281816102980152818161033001528181610377015281816103fc015281816104c701528181610779015281816107cf015281816108a7015281816109240152818161096e01528181610a4e01528181610a8a01528181610b0701528181610b8f01528181610c480152610cd9015261137e6000f3fe6080604052600436106100c35760003560e01c80631e9a6950146100c857806329ebc534146100fb5780632a1ebce114610110578063358d6a041461013e578063632765cf146101535780636f307dc3146101735780637df3927e146101b45780638214f5a4146101c95780638421403d146101fc5780639a79bf8e14610211578063a126d60114610231578063b6b55f2514610251578063c7fe2d6414610271578063cbdf382c14610286578063d075dd42146102ba578063fbfa77cf146102cf575b600080fd5b3480156100d457600080fd5b506100e86100e3366004610fd3565b6102ef565b6040519081526020015b60405180910390f35b34801561010757600080fd5b506100e86103f8565b34801561011c57600080fd5b5061013061012b366004611048565b610481565b6040516100f29291906110ee565b34801561014a57600080fd5b506000196100e8565b34801561015f57600080fd5b506100e861016e36600461111c565b6104ba565b34801561017f57600080fd5b506101a77f000000000000000000000000000000000000000000000000000000000000000081565b6040516100f29190611135565b6101c76101c2366004611149565b61055b565b005b3480156101d557600080fd5b507f00000000000000000000000000000000000000000000000000000000000000006101a7565b34801561020857600080fd5b506100e861075f565b34801561021d57600080fd5b506100e861022c36600461111c565b6107cb565b34801561023d57600080fd5b506100e861024c36600461111c565b610861565b34801561025d57600080fd5b506100e861026c36600461111c565b6109f3565b34801561027d57600080fd5b506100e8610b02565b34801561029257600080fd5b506101a77f000000000000000000000000000000000000000000000000000000000000000081565b3480156102c657600080fd5b506100e8610c43565b3480156102db57600080fd5b506000546101a7906001600160a01b031681565b600080546001600160a01b0316331461031b57604051638d1af8bd60e01b815260040160405180910390fd5b8160000361032b575060006103f2565b6103607f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0381169084610d70565b6040516395a2251f60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906395a2251f906103ac908690600401611135565b6020604051808303816000875af11580156103cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103ef919061118a565b90505b92915050565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa158015610458573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061047c919061118a565b905090565b60005460609081906001600160a01b031633146104b157604051638d1af8bd60e01b815260040160405180910390fd5b94509492505050565b6000670de0b6b3a76400007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa158015610523573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610547919061118a565b61055190846111b9565b6103f291906111d8565b6000546001600160a01b0316331461058657604051638d1af8bd60e01b815260040160405180910390fd5b8060005b818110156107595760008484838181106105a6576105a66111fa565b90506020028101906105b89190611210565b6105c6906020810190611230565b905060008585848181106105dc576105dc6111fa565b90506020028101906105ee9190611210565b6105fc90604081019061124b565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092018290525093945050506001600160a01b038416905087878681811061064f5761064f6111fa565b90506020028101906106619190611210565b602001358360405161067391906112b5565b60006040518083038185875af1925050503d80600081146106b0576040519150601f19603f3d011682016040523d82523d6000602084013e6106b5565b606091505b50509050806107045760405162461bcd60e51b8152602060048201526016602482015275195b595c99d95b98de5058dd1a5bdb8819985a5b195960521b60448201526064015b60405180910390fd5b826001600160a01b03167fa9f1cb7eee5fc621e043c1ef431febb0f901998a6c0cbdf70147b0fe4d9f5a6a8360405161073d91906112f3565b60405180910390a25050508061075290611306565b905061058a565b50505050565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a08231906107ae903090600401611135565b602060405180830381865afa158015610458573d6000803e3d6000fd5b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa15801561082b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061084f919061118a565b61055183670de0b6b3a76400006111b9565b600080546001600160a01b0316331461088d57604051638d1af8bd60e01b815260040160405180910390fd5b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a08231906108dc903090600401611135565b602060405180830381865afa1580156108f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061091d919061118a565b90506109547f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0381169083610d70565b6000546040516395a2251f60e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116926395a2251f926109a7929190911690600401611135565b6020604051808303816000875af11580156109c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109ea919061118a565b9150505b919050565b600080546001600160a01b03163314610a1f57604051638d1af8bd60e01b815260040160405180910390fd5b610a736001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f000000000000000000000000000000000000000000000000000000000000000084610d70565b6040516335313c2160e11b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636a62784290610abf903090600401611135565b6020604051808303816000875af1158015610ade573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103f2919061118a565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316633ba0b9a96040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610b65573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b89919061118a565b905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610bd99190611135565b602060405180830381865afa158015610bf6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c1a919061118a565b90506000670de0b6b3a7640000610c3184846111b9565b610c3b91906111d8565b949350505050565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610c929190611135565b602060405180830381865afa158015610caf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cd3919061118a565b905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d35573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d59919061118a565b90506000670de0b6b3a7640000610c3183856111b9565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610dc2908490610dc7565b505050565b6000610e1c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610e999092919063ffffffff16565b805190915015610dc25780806020019051810190610e3a919061131f565b610dc25760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016106fb565b6060610c3b848460008585600080866001600160a01b03168587604051610ec091906112b5565b60006040518083038185875af1925050503d8060008114610efd576040519150601f19603f3d011682016040523d82523d6000602084013e610f02565b606091505b5091509150610f1387838387610f1e565b979650505050505050565b60608315610f8d578251600003610f86576001600160a01b0385163b610f865760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016106fb565b5081610c3b565b610c3b8383815115610fa25781518083602001fd5b8060405162461bcd60e51b81526004016106fb91906112f3565b80356001600160a01b03811681146109ee57600080fd5b60008060408385031215610fe657600080fd5b610fef83610fbc565b946020939093013593505050565b60008083601f84011261100f57600080fd5b5081356001600160401b0381111561102657600080fd5b6020830191508360208260051b850101111561104157600080fd5b9250929050565b6000806000806040858703121561105e57600080fd5b84356001600160401b038082111561107557600080fd5b61108188838901610ffd565b9096509450602087013591508082111561109a57600080fd5b506110a787828801610ffd565b95989497509550505050565b600081518084526020808501945080840160005b838110156110e3578151875295820195908201906001016110c7565b509495945050505050565b60408152600061110160408301856110b3565b828103602084015261111381856110b3565b95945050505050565b60006020828403121561112e57600080fd5b5035919050565b6001600160a01b0391909116815260200190565b6000806020838503121561115c57600080fd5b82356001600160401b0381111561117257600080fd5b61117e85828601610ffd565b90969095509350505050565b60006020828403121561119c57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b60008160001904831182151516156111d3576111d36111a3565b500290565b6000826111f557634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052603260045260246000fd5b60008235605e1983360301811261122657600080fd5b9190910192915050565b60006020828403121561124257600080fd5b6103ef82610fbc565b6000808335601e1984360301811261126257600080fd5b8301803591506001600160401b0382111561127c57600080fd5b60200191503681900382131561104157600080fd5b60005b838110156112ac578181015183820152602001611294565b50506000910152565b60008251611226818460208701611291565b600081518084526112df816020860160208601611291565b601f01601f19169290920160200192915050565b6020815260006103ef60208301846112c7565b600060018201611318576113186111a3565b5060010190565b60006020828403121561133157600080fd5b8151801515811461134157600080fd5b939250505056fea26469706673582212202ba925c88dea4ae8d56ef07ef3067d6609b25396959666f677e51057079f048464736f6c63430008100033000000000000000000000000a6f224428a168a0f6ecfcb070d6a36e2291a6719000000000000000000000000074e82153303ec002cbd996febd148321e1302ce

Deployed Bytecode

0x6080604052600436106100c35760003560e01c80631e9a6950146100c857806329ebc534146100fb5780632a1ebce114610110578063358d6a041461013e578063632765cf146101535780636f307dc3146101735780637df3927e146101b45780638214f5a4146101c95780638421403d146101fc5780639a79bf8e14610211578063a126d60114610231578063b6b55f2514610251578063c7fe2d6414610271578063cbdf382c14610286578063d075dd42146102ba578063fbfa77cf146102cf575b600080fd5b3480156100d457600080fd5b506100e86100e3366004610fd3565b6102ef565b6040519081526020015b60405180910390f35b34801561010757600080fd5b506100e86103f8565b34801561011c57600080fd5b5061013061012b366004611048565b610481565b6040516100f29291906110ee565b34801561014a57600080fd5b506000196100e8565b34801561015f57600080fd5b506100e861016e36600461111c565b6104ba565b34801561017f57600080fd5b506101a77f000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc881565b6040516100f29190611135565b6101c76101c2366004611149565b61055b565b005b3480156101d557600080fd5b507f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6101a7565b34801561020857600080fd5b506100e861075f565b34801561021d57600080fd5b506100e861022c36600461111c565b6107cb565b34801561023d57600080fd5b506100e861024c36600461111c565b610861565b34801561025d57600080fd5b506100e861026c36600461111c565b6109f3565b34801561027d57600080fd5b506100e8610b02565b34801561029257600080fd5b506101a77f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce81565b3480156102c657600080fd5b506100e8610c43565b3480156102db57600080fd5b506000546101a7906001600160a01b031681565b600080546001600160a01b0316331461031b57604051638d1af8bd60e01b815260040160405180910390fd5b8160000361032b575060006103f2565b6103607f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b0381169084610d70565b6040516395a2251f60e01b81526001600160a01b037f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce16906395a2251f906103ac908690600401611135565b6020604051808303816000875af11580156103cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103ef919061118a565b90505b92915050565b60007f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa158015610458573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061047c919061118a565b905090565b60005460609081906001600160a01b031633146104b157604051638d1af8bd60e01b815260040160405180910390fd5b94509492505050565b6000670de0b6b3a76400007f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa158015610523573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610547919061118a565b61055190846111b9565b6103f291906111d8565b6000546001600160a01b0316331461058657604051638d1af8bd60e01b815260040160405180910390fd5b8060005b818110156107595760008484838181106105a6576105a66111fa565b90506020028101906105b89190611210565b6105c6906020810190611230565b905060008585848181106105dc576105dc6111fa565b90506020028101906105ee9190611210565b6105fc90604081019061124b565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092018290525093945050506001600160a01b038416905087878681811061064f5761064f6111fa565b90506020028101906106619190611210565b602001358360405161067391906112b5565b60006040518083038185875af1925050503d80600081146106b0576040519150601f19603f3d011682016040523d82523d6000602084013e6106b5565b606091505b50509050806107045760405162461bcd60e51b8152602060048201526016602482015275195b595c99d95b98de5058dd1a5bdb8819985a5b195960521b60448201526064015b60405180910390fd5b826001600160a01b03167fa9f1cb7eee5fc621e043c1ef431febb0f901998a6c0cbdf70147b0fe4d9f5a6a8360405161073d91906112f3565b60405180910390a25050508061075290611306565b905061058a565b50505050565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce16906370a08231906107ae903090600401611135565b602060405180830381865afa158015610458573d6000803e3d6000fd5b60007f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa15801561082b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061084f919061118a565b61055183670de0b6b3a76400006111b9565b600080546001600160a01b0316331461088d57604051638d1af8bd60e01b815260040160405180910390fd5b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce16906370a08231906108dc903090600401611135565b602060405180830381865afa1580156108f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061091d919061118a565b90506109547f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b0381169083610d70565b6000546040516395a2251f60e01b81526001600160a01b037f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce8116926395a2251f926109a7929190911690600401611135565b6020604051808303816000875af11580156109c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109ea919061118a565b9150505b919050565b600080546001600160a01b03163314610a1f57604051638d1af8bd60e01b815260040160405180910390fd5b610a736001600160a01b037f000000000000000000000000ff970a61a04b1ca14834a43f5de4533ebddb5cc8167f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce84610d70565b6040516335313c2160e11b81526001600160a01b037f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce1690636a62784290610abf903090600401611135565b6020604051808303816000875af1158015610ade573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103f2919061118a565b6000807f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b0316633ba0b9a96040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610b65573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b89919061118a565b905060007f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610bd99190611135565b602060405180830381865afa158015610bf6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c1a919061118a565b90506000670de0b6b3a7640000610c3184846111b9565b610c3b91906111d8565b949350505050565b6000807f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610c929190611135565b602060405180830381865afa158015610caf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cd3919061118a565b905060007f000000000000000000000000074e82153303ec002cbd996febd148321e1302ce6001600160a01b031663be340e326040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d35573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d59919061118a565b90506000670de0b6b3a7640000610c3183856111b9565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610dc2908490610dc7565b505050565b6000610e1c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610e999092919063ffffffff16565b805190915015610dc25780806020019051810190610e3a919061131f565b610dc25760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016106fb565b6060610c3b848460008585600080866001600160a01b03168587604051610ec091906112b5565b60006040518083038185875af1925050503d8060008114610efd576040519150601f19603f3d011682016040523d82523d6000602084013e610f02565b606091505b5091509150610f1387838387610f1e565b979650505050505050565b60608315610f8d578251600003610f86576001600160a01b0385163b610f865760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016106fb565b5081610c3b565b610c3b8383815115610fa25781518083602001fd5b8060405162461bcd60e51b81526004016106fb91906112f3565b80356001600160a01b03811681146109ee57600080fd5b60008060408385031215610fe657600080fd5b610fef83610fbc565b946020939093013593505050565b60008083601f84011261100f57600080fd5b5081356001600160401b0381111561102657600080fd5b6020830191508360208260051b850101111561104157600080fd5b9250929050565b6000806000806040858703121561105e57600080fd5b84356001600160401b038082111561107557600080fd5b61108188838901610ffd565b9096509450602087013591508082111561109a57600080fd5b506110a787828801610ffd565b95989497509550505050565b600081518084526020808501945080840160005b838110156110e3578151875295820195908201906001016110c7565b509495945050505050565b60408152600061110160408301856110b3565b828103602084015261111381856110b3565b95945050505050565b60006020828403121561112e57600080fd5b5035919050565b6001600160a01b0391909116815260200190565b6000806020838503121561115c57600080fd5b82356001600160401b0381111561117257600080fd5b61117e85828601610ffd565b90969095509350505050565b60006020828403121561119c57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b60008160001904831182151516156111d3576111d36111a3565b500290565b6000826111f557634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052603260045260246000fd5b60008235605e1983360301811261122657600080fd5b9190910192915050565b60006020828403121561124257600080fd5b6103ef82610fbc565b6000808335601e1984360301811261126257600080fd5b8301803591506001600160401b0382111561127c57600080fd5b60200191503681900382131561104157600080fd5b60005b838110156112ac578181015183820152602001611294565b50506000910152565b60008251611226818460208701611291565b600081518084526112df816020860160208601611291565b601f01601f19169290920160200192915050565b6020815260006103ef60208301846112c7565b600060018201611318576113186111a3565b5060010190565b60006020828403121561133157600080fd5b8151801515811461134157600080fd5b939250505056fea26469706673582212202ba925c88dea4ae8d56ef07ef3067d6609b25396959666f677e51057079f048464736f6c63430008100033

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

000000000000000000000000a6f224428a168a0f6ecfcb070d6a36e2291a6719000000000000000000000000074e82153303ec002cbd996febd148321e1302ce

-----Decoded View---------------
Arg [0] : _vault (address): 0xA6F224428a168a0F6eCFCB070D6a36e2291a6719
Arg [1] : _poolToken (address): 0x074e82153303ec002CBD996FebD148321E1302cE

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 000000000000000000000000a6f224428a168a0f6ecfcb070d6a36e2291a6719
Arg [1] : 000000000000000000000000074e82153303ec002cbd996febd148321e1302ce


Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.