creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorV3Interface {\n  function decimals() external view returns (uint8);\n\n  function description() external view returns (string memory);\n\n  function version() external view returns (uint256);\n\n  function getRoundData(uint80 _roundId)\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n\n  function latestRoundData()\n    external\n    view\n    returns (\n      uint80 roundId,\n      int256 answer,\n      uint256 startedAt,\n      uint256 updatedAt,\n      uint80 answeredInRound\n    );\n}\n"
      },
      "@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol": {
        "content": "pragma solidity >=0.5.0;\n\ninterface IUniswapV2Factory {\n    event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n    function feeTo() external view returns (address);\n    function feeToSetter() external view returns (address);\n\n    function getPair(address tokenA, address tokenB) external view returns (address pair);\n    function allPairs(uint) external view returns (address pair);\n    function allPairsLength() external view returns (uint);\n\n    function createPair(address tokenA, address tokenB) external returns (address pair);\n\n    function setFeeTo(address) external;\n    function setFeeToSetter(address) external;\n}\n"
      },
      "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol": {
        "content": "pragma solidity >=0.5.0;\n\ninterface IUniswapV2Pair {\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    function name() external pure returns (string memory);\n    function symbol() external pure returns (string memory);\n    function decimals() external pure returns (uint8);\n    function totalSupply() external view returns (uint);\n    function balanceOf(address owner) external view returns (uint);\n    function allowance(address owner, address spender) external view returns (uint);\n\n    function approve(address spender, uint value) external returns (bool);\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address from, address to, uint value) external returns (bool);\n\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n    function PERMIT_TYPEHASH() external pure returns (bytes32);\n    function nonces(address owner) external view returns (uint);\n\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n    event Mint(address indexed sender, uint amount0, uint amount1);\n    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n    event Swap(\n        address indexed sender,\n        uint amount0In,\n        uint amount1In,\n        uint amount0Out,\n        uint amount1Out,\n        address indexed to\n    );\n    event Sync(uint112 reserve0, uint112 reserve1);\n\n    function MINIMUM_LIQUIDITY() external pure returns (uint);\n    function factory() external view returns (address);\n    function token0() external view returns (address);\n    function token1() external view returns (address);\n    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n    function price0CumulativeLast() external view returns (uint);\n    function price1CumulativeLast() external view returns (uint);\n    function kLast() external view returns (uint);\n\n    function mint(address to) external returns (uint liquidity);\n    function burn(address to) external returns (uint amount0, uint amount1);\n    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n    function skim(address to) external;\n    function sync() external;\n\n    function initialize(address, address) external;\n}\n"
      },
      "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol": {
        "content": "pragma solidity >=0.6.2;\n\ninterface IUniswapV2Router01 {\n    function factory() external pure returns (address);\n    function WETH() external pure returns (address);\n\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB, uint liquidity);\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountToken, uint amountETH);\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountToken, uint amountETH);\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n\n    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}\n"
      },
      "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol": {
        "content": "pragma solidity >=0.6.2;\n\nimport './IUniswapV2Router01.sol';\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountETH);\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountETH);\n\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external payable;\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n}\n"
      },
      "contracts/Arbitrage.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol\";\nimport \"@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol\";\nimport \"@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol\";\nimport \"@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol\";\nimport \"contracts/interfaces/IWETH.sol\";\nimport \"contracts/interfaces/IPriceFeedAggregator.sol\";\nimport \"contracts/interfaces/IReserveHolder.sol\";\nimport \"contracts/interfaces/IArbitrageERC20.sol\";\nimport \"contracts/interfaces/IRewardController.sol\";\nimport \"contracts/library/ExternalContractAddresses.sol\";\nimport \"contracts/uniswap/libraries/UniswapV2Library.sol\";\nimport \"contracts/interfaces/IArbitrage.sol\";\n\n/// @title Contract for performing arbitrage\n/// @notice This contract is responsible for buying USC tokens and for keeping price of USC token pegged to target price\n/// @dev This contract does not hold any assets\ncontract Arbitrage is IArbitrage, ReentrancyGuard, Ownable {\n  using SafeERC20 for IERC20;\n  using SafeERC20 for IArbitrageERC20;\n\n  uint256 public constant BASE_PRICE = 1e8;\n  uint256 public constant USC_TARGET_PRICE = 1e8;\n  uint256 public constant EQ_PRICE_DELTA = 1000 wei;\n  uint256 public constant POOL_FEE = 30;\n  uint256 public constant MAX_FEE = 100_00;\n  // F = (1 - pool_fee) on 18 decimals\n  uint256 public constant F = ((MAX_FEE - POOL_FEE) * 1e18) / MAX_FEE;\n  uint16 public constant MAX_PRICE_TOLERANCE = 100_00;\n  address public constant WETH = ExternalContractAddresses.WETH;\n  address public constant STETH = ExternalContractAddresses.stETH;\n  IUniswapV2Router02 public constant swapRouter = IUniswapV2Router02(ExternalContractAddresses.UNI_V2_SWAP_ROUTER);\n  IUniswapV2Factory public constant poolFactory = IUniswapV2Factory(ExternalContractAddresses.UNI_V2_POOL_FACTORY);\n\n  IArbitrageERC20 public immutable USC;\n  IArbitrageERC20 public immutable CHI;\n  IRewardController public immutable rewardController;\n  IPriceFeedAggregator public immutable priceFeedAggregator;\n  IReserveHolder public immutable reserveHolder;\n\n  uint256 public maxMintPriceDiff;\n  uint16 public priceTolerance;\n\n  constructor(\n    IArbitrageERC20 _USC,\n    IArbitrageERC20 _CHI,\n    IRewardController _rewardController,\n    IPriceFeedAggregator _priceFeedAggregator,\n    IReserveHolder _reserveHolder\n  ) Ownable() {\n    USC = _USC;\n    CHI = _CHI;\n    rewardController = _rewardController;\n    priceFeedAggregator = _priceFeedAggregator;\n    reserveHolder = _reserveHolder;\n\n    IERC20(USC).approve(address(rewardController), type(uint256).max);\n    IERC20(STETH).approve(address(reserveHolder), type(uint256).max);\n  }\n\n  /// @inheritdoc IArbitrage\n  function setPriceTolerance(uint16 _priceTolerance) external onlyOwner {\n    if (_priceTolerance > MAX_PRICE_TOLERANCE) {\n      revert ToleranceTooBig(_priceTolerance);\n    }\n    priceTolerance = _priceTolerance;\n    emit SetPriceTolerance(_priceTolerance);\n  }\n\n  /// @inheritdoc IArbitrage\n  function setMaxMintPriceDiff(uint256 _maxMintPriceDiff) external onlyOwner {\n    maxMintPriceDiff = _maxMintPriceDiff;\n    emit SetMaxMintPriceDiff(_maxMintPriceDiff);\n  }\n\n  /// @inheritdoc IArbitrage\n  function mint() external payable nonReentrant returns (uint256) {\n    uint256 ethAmount = msg.value;\n    IWETH(WETH).deposit{value: ethAmount}();\n    IERC20(WETH).safeTransfer(address(reserveHolder), ethAmount);\n    return _mint(ethAmount, WETH);\n  }\n\n  /// @inheritdoc IArbitrage\n  function mintWithWETH(uint256 wethAmount) external nonReentrant returns (uint256) {\n    IERC20(WETH).safeTransferFrom(msg.sender, address(reserveHolder), wethAmount);\n    return _mint(wethAmount, WETH);\n  }\n\n  /// @inheritdoc IArbitrage\n  function mintWithStETH(uint256 stETHAmount) external nonReentrant returns (uint256) {\n    IERC20(STETH).safeTransferFrom(msg.sender, address(this), stETHAmount);\n    reserveHolder.deposit(IERC20(STETH).balanceOf(address(this)));\n    return _mint(stETHAmount, STETH);\n  }\n\n  /// @inheritdoc IArbitrage\n  function executeArbitrage() public override nonReentrant returns (uint256) {\n    return _executeArbitrage();\n  }\n\n  /// @inheritdoc IArbitrage\n  function getArbitrageData()\n    public\n    view\n    returns (bool isPriceAboveTarget, bool isExcessOfReserves, uint256 reserveDiff, uint256 discount)\n  {\n    uint256 ethPrice = priceFeedAggregator.peek(WETH);\n    uint256 uscPrice = _getAndValidateUscPrice(ethPrice);\n\n    uint256 reserveValue;\n    (isExcessOfReserves, reserveDiff, reserveValue) = _getReservesData();\n    isPriceAboveTarget = uscPrice >= USC_TARGET_PRICE;\n\n    //If prices are equal delta does not need to be calculated\n    if (_almostEqualAbs(uscPrice, USC_TARGET_PRICE, EQ_PRICE_DELTA)) {\n      discount = Math.mulDiv(reserveDiff, BASE_PRICE, reserveValue);\n    }\n  }\n\n  function _executeArbitrage() internal returns (uint256) {\n    (bool isPriceAboveTarget, bool isExcessOfReserves, uint256 reserveDiff, uint256 discount) = getArbitrageData();\n\n    uint256 ethPrice = priceFeedAggregator.peek(WETH);\n\n    if (discount != 0) {\n      if (isExcessOfReserves) {\n        return _arbitrageAtPegExcessOfReserves(reserveDiff, discount, ethPrice);\n      } else {\n        return _arbitrageAtPegDeficitOfReserves(reserveDiff, discount, ethPrice);\n      }\n    } else if (isPriceAboveTarget) {\n      if (isExcessOfReserves) {\n        return _arbitrageAbovePegExcessOfReserves(reserveDiff, ethPrice);\n      } else {\n        return _arbitrageAbovePegDeficitOfReserves(reserveDiff, ethPrice);\n      }\n    } else {\n      if (isExcessOfReserves) {\n        return _arbitrageBellowPegExcessOfReserves(reserveDiff, ethPrice);\n      } else {\n        return _arbitrageBellowPegDeficitOfReserves(reserveDiff, ethPrice);\n      }\n    }\n  }\n\n  function _mint(uint256 amount, address token) private returns (uint256) {\n    uint256 ethPrice = priceFeedAggregator.peek(WETH);\n\n    uint256 uscSpotPrice = _calculateUscSpotPrice(ethPrice);\n    if (!_almostEqualAbs(uscSpotPrice, USC_TARGET_PRICE, maxMintPriceDiff)) {\n      _executeArbitrage();\n    }\n\n    uint256 usdValue;\n    if (token == WETH) {\n      usdValue = _convertTokenAmountToUsdValue(amount, ethPrice);\n    } else {\n      uint256 tokenPrice = priceFeedAggregator.peek(token);\n      usdValue = _convertTokenAmountToUsdValue(amount, tokenPrice);\n    }\n\n    uint256 uscAmountToMint = _convertUsdValueToTokenAmount(usdValue, USC_TARGET_PRICE);\n    USC.mint(msg.sender, uscAmountToMint);\n    emit Mint(msg.sender, token, amount, uscAmountToMint);\n    return uscAmountToMint;\n  }\n\n  function _arbitrageAbovePegExcessOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {\n    uint256 deltaUSC = _calculateDeltaUSC(ethPrice);\n\n    USC.mint(address(this), deltaUSC);\n    uint256 ethAmountReceived = _swap(address(USC), WETH, deltaUSC);\n\n    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaUSC, USC_TARGET_PRICE);\n    uint256 deltaInETH = _convertUsdValueToTokenAmount(deltaUsd, ethPrice);\n\n    if (deltaInETH > ethAmountReceived) {\n      revert DeltaBiggerThanAmountReceivedETH(deltaInETH, ethAmountReceived);\n    }\n\n    uint256 ethAmountToSwap;\n    uint256 ethAmountForReserves;\n\n    if (deltaUsd > reserveDiff) {\n      ethAmountToSwap = _convertUsdValueToTokenAmount(reserveDiff, ethPrice);\n      ethAmountForReserves = _convertUsdValueToTokenAmount(deltaUsd, ethPrice) - ethAmountToSwap;\n      IERC20(WETH).safeTransfer(address(reserveHolder), ethAmountForReserves);\n    } else {\n      ethAmountToSwap = _convertUsdValueToTokenAmount(deltaUsd, ethPrice);\n    }\n\n    uint256 chiAmountReceived = _swap(WETH, address(CHI), ethAmountToSwap);\n    CHI.burn(chiAmountReceived);\n\n    uint256 rewardAmount = ethAmountReceived - ethAmountToSwap - ethAmountForReserves;\n\n    IERC20(WETH).safeTransfer(msg.sender, rewardAmount);\n    uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, ethPrice);\n    emit ExecuteArbitrage(msg.sender, 1, deltaUsd, reserveDiff, ethPrice, rewardValue);\n    return rewardValue;\n  }\n\n  function _arbitrageAbovePegDeficitOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {\n    uint256 deltaUSC = _calculateDeltaUSC(ethPrice);\n\n    USC.mint(address(this), deltaUSC);\n    uint256 ethAmountReceived = _swap(address(USC), WETH, deltaUSC);\n\n    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaUSC, USC_TARGET_PRICE);\n    uint256 deltaInETH = _convertUsdValueToTokenAmount(deltaUsd, ethPrice);\n\n    if (deltaInETH > ethAmountReceived) {\n      revert DeltaBiggerThanAmountReceivedETH(deltaInETH, ethAmountReceived);\n    }\n\n    IERC20(WETH).safeTransfer(address(reserveHolder), deltaInETH);\n\n    uint256 rewardAmount = ethAmountReceived - deltaInETH;\n\n    IERC20(WETH).safeTransfer(msg.sender, rewardAmount);\n    uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, ethPrice);\n    emit ExecuteArbitrage(msg.sender, 2, deltaUsd, reserveDiff, ethPrice, rewardValue);\n    return rewardValue;\n  }\n\n  function _arbitrageBellowPegExcessOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {\n    uint256 uscAmountToFreeze;\n    uint256 uscAmountToBurn;\n    uint256 ethAmountToRedeem;\n    uint256 ethAmountFromChi;\n\n    uint256 deltaETH = _calculateDeltaETH(ethPrice);\n    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaETH, ethPrice);\n\n    if (deltaUsd > reserveDiff) {\n      ethAmountToRedeem = _convertUsdValueToTokenAmount(reserveDiff, ethPrice);\n      uscAmountToFreeze = _convertUsdValueToTokenAmount(reserveDiff, USC_TARGET_PRICE);\n      uscAmountToBurn = _convertUsdValueToTokenAmount(deltaUsd - reserveDiff, USC_TARGET_PRICE);\n\n      uint256 chiAmountToMint = _getAmountInForAmountOut(address(CHI), WETH, deltaETH - ethAmountToRedeem);\n      CHI.mint(address(this), chiAmountToMint);\n      ethAmountFromChi = _swap(address(CHI), WETH, chiAmountToMint);\n    } else {\n      ethAmountToRedeem = deltaETH;\n      uscAmountToFreeze = _convertUsdValueToTokenAmount(deltaUsd, USC_TARGET_PRICE);\n    }\n\n    reserveHolder.redeem(ethAmountToRedeem);\n    uint256 uscAmountReceived = _swap(WETH, address(USC), ethAmountToRedeem + ethAmountFromChi);\n\n    if (uscAmountReceived < uscAmountToFreeze) {\n      uscAmountToFreeze = uscAmountReceived;\n    }\n\n    rewardController.rewardUSC(uscAmountToFreeze);\n\n    if (uscAmountToBurn > 0) {\n      USC.burn(uscAmountToBurn);\n    }\n\n    uint256 rewardAmount = uscAmountReceived - uscAmountToFreeze - uscAmountToBurn;\n    USC.safeTransfer(msg.sender, rewardAmount);\n    uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, USC_TARGET_PRICE);\n    emit ExecuteArbitrage(msg.sender, 3, deltaUsd, reserveDiff, ethPrice, rewardValue);\n    return rewardValue;\n  }\n\n  function _arbitrageBellowPegDeficitOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {\n    uint256 uscAmountToBurn;\n    uint256 uscAmountToFreeze;\n    uint256 ethAmountToRedeem;\n    uint256 ethAmountFromChi;\n\n    uint256 deltaETH = _calculateDeltaETH(ethPrice);\n    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaETH, ethPrice);\n\n    if (deltaUsd > reserveDiff) {\n      ethAmountFromChi = _convertUsdValueToTokenAmount(reserveDiff, ethPrice);\n      uscAmountToBurn = _convertUsdValueToTokenAmount(reserveDiff, USC_TARGET_PRICE);\n      uscAmountToFreeze = _convertUsdValueToTokenAmount(deltaUsd - reserveDiff, USC_TARGET_PRICE);\n      ethAmountToRedeem = deltaETH - ethAmountFromChi;\n      reserveHolder.redeem(ethAmountToRedeem);\n    } else {\n      ethAmountFromChi = deltaETH;\n      uscAmountToBurn = _convertUsdValueToTokenAmount(deltaUsd, USC_TARGET_PRICE);\n    }\n\n    uint256 uscAmountReceived;\n    {\n      if (ethAmountFromChi > 0) {\n        uint256 chiAmountToMint = _getAmountInForAmountOut(address(CHI), WETH, ethAmountFromChi);\n        CHI.mint(address(this), chiAmountToMint);\n        _swap(address(CHI), WETH, chiAmountToMint);\n      }\n\n      uscAmountReceived = _swap(WETH, address(USC), ethAmountFromChi + ethAmountToRedeem);\n    }\n\n    if (uscAmountToFreeze > 0) {\n      rewardController.rewardUSC(uscAmountToFreeze);\n    }\n\n    if (uscAmountToBurn > 0) {\n      USC.burn(uscAmountToBurn);\n    }\n\n    {\n      uint256 rewardAmount = uscAmountReceived - uscAmountToFreeze - uscAmountToBurn;\n      USC.safeTransfer(msg.sender, rewardAmount);\n      uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, USC_TARGET_PRICE);\n      emit ExecuteArbitrage(msg.sender, 4, deltaUsd, reserveDiff, ethPrice, rewardValue);\n      return rewardValue;\n    }\n  }\n\n  function _arbitrageAtPegExcessOfReserves(\n    uint256 reserveDiff,\n    uint256 discount,\n    uint256 ethPrice\n  ) private returns (uint256) {\n    uint256 ethToRedeem = _convertUsdValueToTokenAmount(reserveDiff, ethPrice);\n\n    reserveHolder.redeem(ethToRedeem);\n\n    uint256 chiReceived = _swap(WETH, address(CHI), ethToRedeem);\n    uint256 chiArbitrageReward = Math.mulDiv(chiReceived, discount, BASE_PRICE);\n\n    CHI.burn(chiReceived - chiArbitrageReward);\n\n    IERC20(CHI).safeTransfer(msg.sender, chiArbitrageReward);\n\n    uint256 chiPrice = priceFeedAggregator.peek(address(CHI));\n    uint256 rewardValue = _convertTokenAmountToUsdValue(chiArbitrageReward, chiPrice);\n    emit ExecuteArbitrage(msg.sender, 5, 0, reserveDiff, ethPrice, rewardValue);\n    return rewardValue;\n  }\n\n  function _arbitrageAtPegDeficitOfReserves(\n    uint256 reserveDiff,\n    uint256 discount,\n    uint256 ethPrice\n  ) private returns (uint256) {\n    uint256 ethToGet = _convertUsdValueToTokenAmount(reserveDiff, ethPrice);\n\n    uint256 chiToCoverEth = _getAmountInForAmountOut(address(CHI), WETH, ethToGet);\n    uint256 chiArbitrageReward = Math.mulDiv(chiToCoverEth, discount, BASE_PRICE);\n\n    CHI.mint(address(this), chiToCoverEth + chiArbitrageReward);\n\n    uint256 ethReceived = _swap(address(CHI), WETH, chiToCoverEth);\n    IERC20(WETH).safeTransfer(address(reserveHolder), ethReceived);\n\n    IERC20(CHI).safeTransfer(msg.sender, chiArbitrageReward);\n\n    uint256 chiPrice = priceFeedAggregator.peek(address(CHI));\n    uint256 rewardValue = _convertTokenAmountToUsdValue(chiArbitrageReward, chiPrice);\n    emit ExecuteArbitrage(msg.sender, 6, 0, reserveDiff, ethPrice, rewardValue);\n    return rewardValue;\n  }\n\n  function _getReservesData() public view returns (bool isExcessOfReserves, uint256 reserveDiff, uint256 reserveValue) {\n    reserveValue = reserveHolder.getReserveValue();\n    uint256 uscTotalSupplyValue = _convertTokenAmountToUsdValue(USC.totalSupply(), USC_TARGET_PRICE);\n\n    if (reserveValue > uscTotalSupplyValue) {\n      isExcessOfReserves = true;\n      reserveDiff = (reserveValue - uscTotalSupplyValue);\n    } else {\n      isExcessOfReserves = false;\n      reserveDiff = (uscTotalSupplyValue - reserveValue);\n    }\n  }\n\n  function _getAndValidateUscPrice(uint256 ethPrice) private view returns (uint256) {\n    uint256 uscPrice = priceFeedAggregator.peek(address(USC));\n    uint256 uscSpotPrice = _calculateUscSpotPrice(ethPrice);\n    uint256 priceDiff = _absDiff(uscSpotPrice, uscPrice);\n    uint256 maxPriceDiff = Math.mulDiv(uscPrice, priceTolerance, MAX_PRICE_TOLERANCE);\n\n    if (priceDiff > maxPriceDiff) {\n      revert PriceSlippageTooBig();\n    }\n\n    return uscSpotPrice;\n  }\n\n  // input ethPrice has 8 decimals\n  // returns result with 8 decimals\n  function _calculateUscSpotPrice(uint256 ethPrice) private view returns (uint256) {\n    (uint256 reserveUSC, uint256 reserveWETH) = UniswapV2Library.getReserves(\n      address(poolFactory),\n      address(USC),\n      address(WETH)\n    );\n    uint256 uscFor1ETH = UniswapV2Library.quote(1 ether, reserveWETH, reserveUSC);\n    return Math.mulDiv(ethPrice, 1 ether, uscFor1ETH);\n  }\n\n  // what amount of In tokens to put in pool to make price:   1 tokenOut = (priceOut / priceIn) tokenIn\n  // assuming reserves are on 18 decimals, prices are on 8 decimals\n  function _calculateDelta(\n    uint256 reserveIn,\n    uint256 priceIn,\n    uint256 reserveOut,\n    uint256 priceOut\n  ) public pure returns (uint256) {\n    // F = (1 - pool_fee) = 0.997 on 18 decimals,   in square root formula  a = F\n\n    // parameter `b` in square root formula,  b = rIn * (1+f) ,  on 18 decimals\n    uint256 b = Math.mulDiv(reserveIn, 1e18 + F, 1e18);\n    uint256 b_sqr = Math.mulDiv(b, b, 1e18);\n\n    // parameter `c` in square root formula,  c = rIn^2 - (rIn * rOut * priceOut) / priceIn\n    uint256 c_1 = Math.mulDiv(reserveIn, reserveIn, 1e18);\n    uint256 c_2 = Math.mulDiv(Math.mulDiv(reserveIn, reserveOut, 1e18), priceOut, priceIn);\n\n    uint256 c;\n    uint256 root;\n    if (c_1 > c_2) {\n      c = c_1 - c_2;\n      // d = 4ac\n      uint256 d = Math.mulDiv(4 * F, c, 1e18);\n\n      // root = sqrt(b^2 - 4ac)\n      // multiplying by 10^9 to get back to 18 decimals\n      root = Math.sqrt(b_sqr - d) * 1e9;\n    } else {\n      c = c_2 - c_1;\n      // d = 4ac\n      uint256 d = Math.mulDiv(4 * F, c, 1e18);\n\n      // root = sqrt(b^2 - 4ac)    -> in this case `c` is negative, so we add `d` to `b^2`\n      // multiplying by 10^9 to get back to 18 decimals\n      root = Math.sqrt(b_sqr + d) * 1e9;\n    }\n    // delta = (-b + root) / 2*f\n    uint256 delta = Math.mulDiv(1e18, root - b, 2 * F);\n\n    return delta;\n  }\n\n  // given ethPrice is on 8 decimals\n  // how many USC to put in pool to make price:   1 ETH = ethPrice * USC\n  function _calculateDeltaUSC(uint256 ethPrice) public view returns (uint256) {\n    (uint256 reserveUSC, uint256 reserveWETH) = UniswapV2Library.getReserves(\n      address(poolFactory),\n      address(USC),\n      address(WETH)\n    );\n    return _calculateDelta(reserveUSC, USC_TARGET_PRICE, reserveWETH, ethPrice);\n  }\n\n  // how many ETH to put in pool to make price:   1 ETH = ethPrice * USC\n  function _calculateDeltaETH(uint256 ethPrice) public view returns (uint256) {\n    (uint256 reserveUSC, uint256 reserveWETH) = UniswapV2Library.getReserves(\n      address(poolFactory),\n      address(USC),\n      address(WETH)\n    );\n    return _calculateDelta(reserveWETH, ethPrice, reserveUSC, USC_TARGET_PRICE);\n  }\n\n  function _makePath(address t1, address t2) internal pure returns (address[] memory path) {\n    path = new address[](2);\n    path[0] = t1;\n    path[1] = t2;\n  }\n\n  function _makePath(address t1, address t2, address t3) internal pure returns (address[] memory path) {\n    path = new address[](3);\n    path[0] = t1;\n    path[1] = t2;\n    path[2] = t3;\n  }\n\n  function _swap(address tokenIn, address tokenOut, uint256 amount) private returns (uint256) {\n    address[] memory path;\n\n    if (tokenIn != WETH && tokenOut != WETH) {\n      path = _makePath(tokenIn, WETH, tokenOut);\n    } else {\n      path = _makePath(tokenIn, tokenOut);\n    }\n\n    IERC20(tokenIn).approve(address(swapRouter), amount);\n    uint256[] memory amounts = swapRouter.swapExactTokensForTokens(amount, 0, path, address(this), block.timestamp);\n\n    uint256 amountReceived = amounts[path.length - 1];\n\n    return amountReceived;\n  }\n\n  function _getAmountInForAmountOut(address tIn, address tOut, uint256 amountOut) internal view returns (uint256) {\n    (uint256 rIn, uint256 rOut) = UniswapV2Library.getReserves(address(poolFactory), tIn, tOut);\n    return UniswapV2Library.getAmountIn(amountOut, rIn, rOut);\n  }\n\n  function _convertUsdValueToTokenAmount(uint256 usdValue, uint256 price) internal pure returns (uint256) {\n    return Math.mulDiv(usdValue, 1e18, price);\n  }\n\n  function _convertTokenAmountToUsdValue(uint256 amount, uint256 price) internal pure returns (uint256) {\n    return Math.mulDiv(amount, price, 1e18);\n  }\n\n  function _absDiff(uint256 a, uint256 b) internal pure returns (uint256) {\n    return (a > b) ? a - b : b - a;\n  }\n\n  function _almostEqualAbs(uint256 price1, uint256 price2, uint256 delta) internal pure returns (bool) {\n    return _absDiff(price1, price2) <= delta;\n  }\n\n  receive() external payable {}\n}\n"
      },
      "contracts/interfaces/IArbitrage.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IArbitrage {\n  event SetPriceTolerance(uint16 priceTolerance);\n  event SetMaxMintPriceDiff(uint256 maxMintPriceDiff);\n  event Mint(address indexed account, address token, uint256 amount, uint256 uscAmount);\n  event ExecuteArbitrage(\n    address indexed account,\n    uint256 indexed arbNum,\n    uint256 deltaUsd,\n    uint256 reserveDiff,\n    uint256 ethPrice,\n    uint256 rewardValue\n  );\n\n  error DeltaBiggerThanAmountReceivedETH(uint256 deltaETH, uint256 receivedETH);\n  error ToleranceTooBig(uint16 _tolerance);\n  error PriceSlippageTooBig();\n\n  /// @notice Sets spot price tolerance from TWAP price\n  /// @dev 100% = 10000\n  /// @param _priceTolerance Price tolerance in percents\n  /// @custom:usage This function should be called from owner in purpose of setting price tolerance\n  function setPriceTolerance(uint16 _priceTolerance) external;\n\n  /// @notice Sets max mint price diff\n  /// @param _maxMintPriceDiff Max mint price diff\n  /// @custom:usage This function should be called from owner in purpose of setting max mint price diff\n  function setMaxMintPriceDiff(uint256 _maxMintPriceDiff) external;\n\n  /// @notice Mint USC tokens for ETH\n  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage\n  /// @return uscAmount Amount of USC tokens minted\n  function mint() external payable returns (uint256 uscAmount);\n\n  /// @notice Mint USC tokens for WETH\n  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage\n  /// @param wethAmount Amount of WETH to mint with\n  /// @return uscAmount Amount of USC tokens minted\n  function mintWithWETH(uint256 wethAmount) external returns (uint256 uscAmount);\n\n  /// @notice Mint USC tokens for stETH\n  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage\n  /// @param stETHAmount Amount of stETH to mint with\n  /// @return uscAmount Amount of USC tokens minted\n  function mintWithStETH(uint256 stETHAmount) external returns (uint256 uscAmount);\n\n  /// @notice Executes arbitrage, profit sent to caller\n  /// @notice Returns reward value in USD\n  /// @return rewardValue Reward value in USD\n  /// @custom:usage This function should be called from external keeper in purpose of pegging USC price and getting reward\n  /// @custom:usage This function has no restrictions, anyone can be arbitrager\n  function executeArbitrage() external returns (uint256 rewardValue);\n\n  /// @notice Gets information for perfoming arbitrage such as price diff, reserve diff, discount\n  /// @return isPriceAboveTarget True if USC price is above target price\n  /// @return isExcessOfReserves True if there is excess of reserves\n  /// @return reserveDiff Reserve diff, excess or deficit of reserves\n  /// @return discount Discount in percents, only if price is equal to target price\n  function getArbitrageData()\n    external\n    view\n    returns (bool isPriceAboveTarget, bool isExcessOfReserves, uint256 reserveDiff, uint256 discount);\n}\n"
      },
      "contracts/interfaces/IArbitrageERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IArbitrageERC20 is IERC20 {\n  function mint(address to, uint256 amount) external;\n\n  function burn(uint256 amount) external;\n}\n"
      },
      "contracts/interfaces/IPriceFeedAggregator.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IPriceFeedAggregator {\n  event SetPriceFeed(address indexed base, address indexed feed);\n\n  error ZeroAddress();\n\n  /// @notice Sets price feed adapter for given token\n  /// @param base Token address\n  /// @param feed Price feed adapter address\n  function setPriceFeed(address base, address feed) external;\n\n  /// @notice Gets price for given token\n  /// @param base Token address\n  /// @return price Price for given token\n  function peek(address base) external view returns (uint256 price);\n}\n"
      },
      "contracts/interfaces/IReserveHolder.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IReserveHolder {\n  event SetArbitrager(address indexed arbitrager, bool enabled);\n  event SetClaimer(address indexed claimer);\n  event SetEthThreshold(uint256 threshold);\n  event SetSwapEthTolerance(uint256 tolerance);\n  event SetCurveStEthSafeGuardPercentage(uint256 percentage);\n  event Deposit(address indexed account, uint256 amount);\n  event Rebalance(uint256 ethAmount, uint256 stEthAmount);\n  event Redeem(address indexed account, uint256 amount);\n  event RedeemSwap(uint256 ethAmount, uint256 stEthAmount);\n  event ClaimRewards(address indexed account, uint256 amount);\n  event Receive(address indexed account, uint256 amount);\n\n  error NotArbitrager(address _account);\n  error NotClaimer(address _account);\n  error ThresholdTooHigh(uint256 _threshold);\n  error SafeGuardTooHigh(uint256 _safeGuard);\n  error EtherSendFailed(address _account, uint256 _amount);\n\n  /// @notice Updates arbitrager status\n  /// @param arbitrager Arbitrager address\n  /// @param status Arbitrager status\n  function setArbitrager(address arbitrager, bool status) external;\n\n  /// @notice Sets claimer address\n  /// @param claimer Claimer address\n  /// @custom:usage Claimer should be rewardController contract\n  function setClaimer(address claimer) external;\n\n  /// @notice Sets eth threshold\n  /// @param ethThreshold Eth threshold\n  /// @custom:usage Eth threshold should be set in percentage\n  /// @custom:usage Part of reserves is in WETH so arbitrage contract can use them without swapping stETH for ETH\n  function setEthThreshold(uint256 ethThreshold) external;\n\n  /// @notice Sets swap eth tolerance\n  /// @param swapEthTolerance Swap eth tolerance\n  /// @custom:usage Swap eth tolerance should be set in wei\n  /// @custom:usage Absolute tolerance for swapping stETH for ETH\n  function setSwapEthTolerance(uint256 swapEthTolerance) external;\n\n  /// @notice Sets curve stETH safe guard percentage\n  /// @param curveStEthSafeGuardPercentage Curve stETH safe guard percentage\n  function setCurveStEthSafeGuardPercentage(uint256 curveStEthSafeGuardPercentage) external;\n\n  /// @notice Gets reserve value in USD\n  /// @return reserveValue Reserve value in USD\n  function getReserveValue() external view returns (uint256 reserveValue);\n\n  /// @notice Gets current rewards generated by stETH\n  /// @return currentRewards Current rewards generated by stETH\n  function getCurrentRewards() external view returns (uint256 currentRewards);\n\n  /// @notice Gets cumulative rewards generated by stETH\n  /// @return cumulativeRewards Cumulative rewards generated by stETH\n  function getCumulativeRewards() external view returns (uint256 cumulativeRewards);\n\n  /// @notice Deposits stETH to reseves\n  /// @param amount Amount of stETH to deposit\n  function deposit(uint256 amount) external;\n\n  /// @notice Rebalance reserve in order to achieve balace/ethThreshold ratio\n  /// @dev If there is more WETH than ethThreshold then unwrap WETH and get stETH from Lido\n  /// @dev If there is less WETH than ethThreshold then swap stETH for WETH on UniV2\n  /// @custom:usage This function should be called by external keeper\n  function rebalance() external;\n\n  /// @notice Redeems stETH from reserves\n  /// @param amount Amount of stETH to redeem\n  /// @return wethAmount Amount of WETH received\n  /// @custom:usage This function should be called by arbitrage contract\n  function redeem(uint256 amount) external returns (uint256 wethAmount);\n\n  /// @notice Claims stETH rewards in given amount for given account\n  /// @notice Contract does not perform any check and is relying on rewardController contract to perform them\n  /// @param account Account to claim stETH rewards for\n  /// @param amount Amount of stETH to claim\n  /// @custom:usage This function should be called by rewardController contract\n  function claimRewards(address account, uint256 amount) external;\n\n  /// @notice Wrapps ETH to WETH\n  /// @dev Users can buy USC with ETH which is transfered to this contract. This function should be called to wrapp than ETH to WETH\n  /// @custom:usage This function should be called by external keeper\n  function wrapETH() external;\n}\n"
      },
      "contracts/interfaces/IRewardController.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IArbitrage} from \"./IArbitrage.sol\";\n\ninterface IRewardController {\n  struct EpochData {\n    uint256 totalUscReward;\n    uint256 reserveHolderTotalRewards;\n  }\n\n  struct StETHRewards {\n    uint256 uscStakingStEthReward;\n    uint256 chiStakingStEthReward;\n    uint256 chiLockingStEthReward;\n    uint256 chiVestingStEthReward;\n    uint256 uscEthLPStakingStEthReward;\n    uint256 chiEthLPStakingStEthReward;\n  }\n\n  struct ChiIncentives {\n    uint256 uscStakingChiIncentives;\n    uint256 chiLockingChiIncentives;\n    uint256 chiVestingChiIncentives;\n  }\n\n  event RewardUSC(address indexed account, uint256 amount);\n  event UpdateEpoch(uint256 indexed epoch, uint256 totalStEthReward, uint256 totalChiIncentives);\n  event ClaimStEth(address indexed account, uint256 amount);\n  event SetChiIncentivesPerEpoch(uint256 indexed chiIncentivesPerEpoch);\n  event SetArbitrager(address indexed arbitrager);\n\n  error ZeroAmount();\n  error NotArbitrager();\n  error EpochNotFinished();\n\n  /// @notice Set amount of chi incentives per epoch for chi lockers\n  /// @param _chiIncentivesForChiLocking Amount of chi incentives per epoch\n  function setChiIncentivesForChiLocking(uint256 _chiIncentivesForChiLocking) external;\n\n  /// @notice Set amount of chi incentives per epoch for USC staking\n  /// @param _chiIncentivesForUscStaking Amount of chi incentives per epoch\n  function setChiIncentivesForUscStaking(uint256 _chiIncentivesForUscStaking) external;\n\n  /// @notice Set amount of chi incentives per epoch for USC-ETH LP staking contracts\n  /// @param _chiIncentivesForUscEthLPStaking Amount of chi incentives per epoch\n  function setChiIncentivesForUscEthLPStaking(uint256 _chiIncentivesForUscEthLPStaking) external;\n\n  /// @notice Set amount of chi incentives per epoch for CHI-ETH LP staking contracts\n  /// @param _chiIncentivesForChiEthLPStaking Amount of chi incentives per epoch\n  function setChiIncentivesForChiEthLPStaking(uint256 _chiIncentivesForChiEthLPStaking) external;\n\n  /// @notice Sets arbitrager contract\n  /// @param _arbitrager Arbitrager contract\n  function setArbitrager(IArbitrage _arbitrager) external;\n\n  /// @notice Freezes given amount of USC token\n  /// @dev Frozen tokens are not transfered they are burned and later minted again when conditions are met\n  /// @param amount Amount of USC tokens to freeze\n  /// @custom:usage This function should be called from Arbitrager contract in purpose of freezing USC tokens\n  function rewardUSC(uint256 amount) external;\n\n  /// @notice Updates epoch data\n  /// @dev This functio will update epochs in all subcontracts and will distribute chi incentives and stETH rewards\n  /// @custom:usage This function should be called once a week in order to end current epoch and start new one\n  /// @custom:usage Thsi function ends current epoch and distributes chi incentives and stETH rewards to all contracts in this epoch\n  function updateEpoch() external;\n\n  /// @notice Claims stETH rewards for caller\n  /// @dev This function will claim stETH rewards from all subcontracts and will send them to caller\n  /// @dev Thsi contract does not hold stETH, instead it sends it through reserveHolder contract\n  function claimStEth() external;\n\n  /// @notice Calculates and returns unclaimed stETH amount for given account in all subcontracts\n  /// @param account Account to calculate unclaimed stETH amount for\n  /// @return totalAmount Total amount of unclaimed stETH for given account\n  function unclaimedStETHAmount(address account) external view returns (uint256 totalAmount);\n}\n"
      },
      "contracts/interfaces/IWETH.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IWETH is IERC20 {\n  function deposit() external payable;\n\n  function withdraw(uint256 amount) external;\n}\n"
      },
      "contracts/library/ExternalContractAddresses.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice external contract addresses on Ethereum Mainnet\nlibrary ExternalContractAddresses {\n  address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n  address public constant stETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;\n  address public constant UNI_V2_SWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n  address public constant UNI_V2_POOL_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;\n  address public constant ETH_USD_CHAINLINK_FEED = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;\n  address public constant STETH_USD_CHAINLINK_FEED = 0xCfE54B5cD566aB89272946F602D76Ea879CAb4a8;\n  address public constant CURVE_ETH_STETH_POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022;\n}\n"
      },
      "contracts/uniswap/libraries/SafeMath.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\n// library copied from uniswap/v2-core/contracts/libraries/SafeMath.sol\n// the only change is in pragma solidity version.\n// this contract was the reason of incompatible solidity version error\n\n// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)\n\nlibrary SafeMath {\n  function add(uint x, uint y) internal pure returns (uint z) {\n    require((z = x + y) >= x, \"ds-math-add-overflow\");\n  }\n\n  function sub(uint x, uint y) internal pure returns (uint z) {\n    require((z = x - y) <= x, \"ds-math-sub-underflow\");\n  }\n\n  function mul(uint x, uint y) internal pure returns (uint z) {\n    require(y == 0 || (z = x * y) / y == x, \"ds-math-mul-overflow\");\n  }\n}\n"
      },
      "contracts/uniswap/libraries/UniswapV2Library.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\n// library copied from uniswap/v2-core/contracts/libraries/UniswapV2Library.sol\n// the only change is in pragma solidity version.\n\nimport \"@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol\";\n\nimport \"./SafeMath.sol\";\n\nlibrary UniswapV2Library {\n  using SafeMath for uint;\n\n  // returns sorted token addresses, used to handle return values from pairs sorted in this order\n  function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\n    require(tokenA != tokenB, \"UniswapV2Library: IDENTICAL_ADDRESSES\");\n    (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n    require(token0 != address(0), \"UniswapV2Library: ZERO_ADDRESS\");\n  }\n\n  // calculates the CREATE2 address for a pair without making any external calls\n  function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n    (address token0, address token1) = sortTokens(tokenA, tokenB);\n    pair = address(\n      uint160(\n        uint(\n          keccak256(\n            abi.encodePacked(\n              hex\"ff\",\n              factory,\n              keccak256(abi.encodePacked(token0, token1)),\n              hex\"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f\" // init code hash\n            )\n          )\n        )\n      )\n    );\n  }\n\n  // fetches and sorts the reserves for a pair\n  function getReserves(\n    address factory,\n    address tokenA,\n    address tokenB\n  ) internal view returns (uint reserveA, uint reserveB) {\n    (address token0, ) = sortTokens(tokenA, tokenB);\n    (uint reserve0, uint reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();\n    (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n  }\n\n  // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n  function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {\n    require(amountA > 0, \"UniswapV2Library: INSUFFICIENT_AMOUNT\");\n    require(reserveA > 0 && reserveB > 0, \"UniswapV2Library: INSUFFICIENT_LIQUIDITY\");\n    amountB = amountA.mul(reserveB) / reserveA;\n  }\n\n  // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n  function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {\n    require(amountIn > 0, \"UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT\");\n    require(reserveIn > 0 && reserveOut > 0, \"UniswapV2Library: INSUFFICIENT_LIQUIDITY\");\n    uint amountInWithFee = amountIn.mul(997);\n    uint numerator = amountInWithFee.mul(reserveOut);\n    uint denominator = reserveIn.mul(1000).add(amountInWithFee);\n    amountOut = numerator / denominator;\n  }\n\n  // given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n  function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {\n    require(amountOut > 0, \"UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT\");\n    require(reserveIn > 0 && reserveOut > 0, \"UniswapV2Library: INSUFFICIENT_LIQUIDITY\");\n    uint numerator = reserveIn.mul(amountOut).mul(1000);\n    uint denominator = reserveOut.sub(amountOut).mul(997);\n    amountIn = (numerator / denominator).add(1);\n  }\n\n  // performs chained getAmountOut calculations on any number of pairs\n  function getAmountsOut(\n    address factory,\n    uint amountIn,\n    address[] memory path\n  ) internal view returns (uint[] memory amounts) {\n    require(path.length >= 2, \"UniswapV2Library: INVALID_PATH\");\n    amounts = new uint[](path.length);\n    amounts[0] = amountIn;\n    for (uint i; i < path.length - 1; i++) {\n      (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);\n      amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);\n    }\n  }\n\n  // performs chained getAmountIn calculations on any number of pairs\n  function getAmountsIn(\n    address factory,\n    uint amountOut,\n    address[] memory path\n  ) internal view returns (uint[] memory amounts) {\n    require(path.length >= 2, \"UniswapV2Library: INVALID_PATH\");\n    amounts = new uint[](path.length);\n    amounts[amounts.length - 1] = amountOut;\n    for (uint i = path.length - 1; i > 0; i--) {\n      (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);\n      amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);\n    }\n  }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 1000
      },
      "viaIR": true,
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}