creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable-v4/token/ERC20/extensions/IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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-upgradeable-v4/token/ERC20/IERC20Upgradeable.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 IERC20Upgradeable {\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-upgradeable-v4/token/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {\n    using AddressUpgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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        IERC20PermitUpgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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))) && AddressUpgradeable.isContract(address(token));\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable-v4/utils/AddressUpgradeable.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 AddressUpgradeable {\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-upgradeable-v4/utils/structs/EnumerableSetUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSetUpgradeable {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "@openzeppelin/contracts-v4/access/AccessControl.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n    struct RoleData {\n        mapping(address => bool) members;\n        bytes32 adminRole;\n    }\n\n    mapping(bytes32 => RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with a standardized message including the required role.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     *\n     * _Available since v4.1._\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n        return _roles[role].members[account];\n    }\n\n    /**\n     * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n     * Overriding this function changes the behavior of the {onlyRole} modifier.\n     *\n     * Format of the revert message is described in {_checkRole}.\n     *\n     * _Available since v4.6._\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Revert with a standard message if `account` is missing `role`.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert(\n                string(\n                    abi.encodePacked(\n                        \"AccessControl: account \",\n                        Strings.toHexString(account),\n                        \" is missing role \",\n                        Strings.toHexString(uint256(role), 32)\n                    )\n                )\n            );\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n        return _roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address account) public virtual override {\n        require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event. Note that unlike {grantRole}, this function doesn't perform any\n     * checks on the calling account.\n     *\n     * May emit a {RoleGranted} event.\n     *\n     * [WARNING]\n     * ====\n     * This function should only be called from the constructor when setting\n     * up the initial roles for the system.\n     *\n     * Using this function in any other way is effectively circumventing the admin\n     * system imposed by {AccessControl}.\n     * ====\n     *\n     * NOTE: This function is deprecated in favor of {_grantRole}.\n     */\n    function _setupRole(bytes32 role, address account) internal virtual {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        _roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual {\n        if (!hasRole(role, account)) {\n            _roles[role].members[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n        }\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual {\n        if (hasRole(role, account)) {\n            _roles[role].members[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-v4/access/IAccessControl.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     *\n     * _Available since v3.1._\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {AccessControl-_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(bytes32 role, address account) external;\n}\n"
      },
      "@openzeppelin/contracts-v4/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-v4/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-v4/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-v4/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-v4/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-v4/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "@openzeppelin/contracts-v4/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-v4/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"
      },
      "@openzeppelin/contracts-v4/utils/math/SignedMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-v4/utils/Strings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\nimport \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toString(int256 value) internal pure returns (string memory) {\n        return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value))));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"
      },
      "contracts/f(x)/v2/FxInitialFund.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.20;\n\nimport { AccessControl } from \"@openzeppelin/contracts-v4/access/AccessControl.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts-v4/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol\";\n\nimport { IFxMarketV2 } from \"../../interfaces/f(x)/IFxMarketV2.sol\";\nimport { IFxTreasuryV2 } from \"../../interfaces/f(x)/IFxTreasuryV2.sol\";\nimport { IFxUSD } from \"../../interfaces/f(x)/IFxUSD.sol\";\n\ncontract FxInitialFund is AccessControl {\n  using SafeERC20 for IERC20;\n\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the status of `fxWithdrawalEnabled` is updated.\n  event ToggleFxWithdrawalStatus();\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when try to withdraw both fxUSD and xToken.\n  error ErrorFxWithdrawalNotEnabled();\n\n  /// @dev Thrown when the amount of base token is not enough.\n  error ErrorInsufficientBaseToken();\n\n  /// @dev Thrown when deposit after initialization.\n  error ErrorInitialized();\n\n  /// @dev Thrown when withdraw before initialization.\n  error ErrorNotInitialized();\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @notice The role for minter.\n  bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n\n  /// @notice The address of market contract.\n  address public immutable market;\n\n  /// @notice The address of treasury contract.\n  address public immutable treasury;\n\n  /// @notice The address of base token.\n  address public immutable baseToken;\n\n  /// @notice The address of fToken token.\n  address public immutable fToken;\n\n  /// @notice The address of xToken token.\n  address public immutable xToken;\n\n  /// @notice The address of fxUSD token.\n  address public immutable fxUSD;\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @notice Mapping from user address to pool shares.\n  mapping(address => uint256) public shares;\n\n  /// @notice The total amount of pool shares.\n  uint256 public totalShares;\n\n  /// @notice The total amount of fxUSD/fToken minted.\n  uint256 public totalFToken;\n\n  /// @notice The total amount of xToken minted.\n  uint256 public totalXToken;\n\n  /// @notice Whether the pool is initialized.\n  bool public initialized;\n\n  /// @notice Whether withdraw both fxUSD and xToken is enabled.\n  bool public fxWithdrawalEnabled;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(address _market, address _fxUSD) {\n    address _treasury = IFxMarketV2(_market).treasury();\n\n    market = _market;\n    treasury = _treasury;\n    baseToken = IFxTreasuryV2(_treasury).baseToken();\n    fToken = IFxTreasuryV2(_treasury).fToken();\n    xToken = IFxTreasuryV2(_treasury).xToken();\n    fxUSD = _fxUSD;\n\n    _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Deposit base token to this contract.\n  /// @param amount The amount of token to deposit.\n  /// @param receiver The address of pool share recipient.\n  function deposit(uint256 amount, address receiver) external {\n    if (initialized) revert ErrorInitialized();\n\n    IERC20(baseToken).safeTransferFrom(_msgSender(), address(this), amount);\n    shares[receiver] += amount;\n    totalShares += amount;\n  }\n\n  /// @notice Withdraw base token from this contract.\n  /// @param receiver The address of base token recipient.\n  /// @param minBaseOut The minimum amount of base token should receive.\n  /// @return baseOut The amount of base token received.\n  function withdrawBaseToken(address receiver, uint256 minBaseOut) external returns (uint256 baseOut) {\n    if (!initialized) revert ErrorNotInitialized();\n\n    uint256 _share = shares[_msgSender()];\n    shares[_msgSender()] = 0;\n    uint256 _totalShares = totalShares;\n    uint256 _fAmount = (_share * totalFToken) / _totalShares;\n    uint256 _xAmount = (_share * totalXToken) / _totalShares;\n\n    uint256 _fBaseOut;\n    if (fxUSD != address(0)) {\n      (_fBaseOut, ) = IFxUSD(fxUSD).redeem(baseToken, _fAmount, receiver, 0);\n    } else {\n      (_fBaseOut, ) = IFxMarketV2(market).redeemFToken(_fAmount, receiver, 0);\n    }\n    // No need to approve xToken to market\n    uint256 _xBaseOut = IFxMarketV2(market).redeemXToken(_xAmount, receiver, 0);\n\n    baseOut = _xBaseOut + _fBaseOut;\n    if (baseOut < minBaseOut) revert ErrorInsufficientBaseToken();\n  }\n\n  /// @notice Withdraw fxUSD/fToken and xToken from this contract.\n  /// @param receiver The address of token recipient.\n  function withdraw(address receiver) external {\n    if (!initialized) revert ErrorNotInitialized();\n    if (!fxWithdrawalEnabled) revert ErrorFxWithdrawalNotEnabled();\n\n    uint256 _share = shares[_msgSender()];\n    shares[_msgSender()] = 0;\n    uint256 _totalShares = totalShares;\n    uint256 _fAmount = (_share * totalFToken) / _totalShares;\n    uint256 _xAmount = (_share * totalXToken) / _totalShares;\n\n    if (fxUSD != address(0)) {\n      IERC20(fxUSD).safeTransfer(receiver, _fAmount);\n    } else {\n      IERC20(fToken).safeTransfer(receiver, _fAmount);\n    }\n    IERC20(xToken).safeTransfer(receiver, _xAmount);\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Initialize treasury with base token in this contract.\n  function mint() external onlyRole(MINTER_ROLE) {\n    if (initialized) revert ErrorInitialized();\n\n    uint256 _balance = IERC20(baseToken).balanceOf(address(this));\n    IERC20(baseToken).safeTransfer(treasury, _balance);\n    (uint256 _totalFToken, uint256 _totalXToken) = IFxTreasuryV2(treasury).initializeProtocol(\n      IFxTreasuryV2(treasury).getUnderlyingValue(_balance)\n    );\n\n    if (fxUSD != address(0)) {\n      IERC20(fToken).safeApprove(fxUSD, _totalFToken);\n      IFxUSD(fxUSD).wrap(baseToken, _totalFToken, address(this));\n    }\n\n    totalFToken = _totalFToken;\n    totalXToken = _totalXToken;\n    initialized = true;\n  }\n\n  /// @notice Change the status of `fxWithdrawalEnabled`.\n  function toggleFxWithdrawalStatus() external onlyRole(DEFAULT_ADMIN_ROLE) {\n    fxWithdrawalEnabled = !fxWithdrawalEnabled;\n\n    emit ToggleFxWithdrawalStatus();\n  }\n}\n"
      },
      "contracts/gateways/facets/FxUSDFacet.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.20;\n\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/IERC20Upgradeable.sol\";\n\nimport { IFxMarketV2 } from \"../../interfaces/f(x)/IFxMarketV2.sol\";\nimport { IFxShareableRebalancePool } from \"../../interfaces/f(x)/IFxShareableRebalancePool.sol\";\nimport { IFxUSD } from \"../../interfaces/f(x)/IFxUSD.sol\";\n\nimport { FxInitialFund } from \"../../f(x)/v2/FxInitialFund.sol\";\n\nimport { LibGatewayRouter } from \"../libraries/LibGatewayRouter.sol\";\n\ncontract FxUSDFacet {\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when the length of two arrays is mismatch.\n  error ErrorLengthMismatch();\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Deposit to initial fund with given token and convert parameters.\n  /// @param _params The token converting parameters.\n  /// @param _vault The address of vault to use.\n  /// @return _baseOut The amount of base token received.\n  function fxInitialFundDeposit(LibGatewayRouter.ConvertInParams memory _params, address _vault)\n    external\n    payable\n    returns (uint256 _baseOut)\n  {\n    LibGatewayRouter.ensureWhitelised(_vault, LibGatewayRouter.WhitelistKind.FxInitialFundVault);\n\n    address _baseToken = FxInitialFund(_vault).baseToken();\n    _baseOut = LibGatewayRouter.transferInAndConvert(_params, _baseToken);\n    LibGatewayRouter.approve(_baseToken, _vault, _baseOut);\n    FxInitialFund(_vault).deposit(_baseOut, msg.sender);\n  }\n\n  /// @notice Mint some fToken with given token and convert parameters.\n  /// @param _params The token converting parameters.\n  /// @param _market The address of market to use.\n  /// @param _minFTokenMinted The minimum amount of fToken should be received.\n  /// @return _fTokenMinted The amount of fToken received.\n  function fxMintFTokenV2(\n    LibGatewayRouter.ConvertInParams memory _params,\n    address _market,\n    uint256 _minFTokenMinted\n  ) external payable returns (uint256 _fTokenMinted) {\n    LibGatewayRouter.ensureWhitelised(_market, LibGatewayRouter.WhitelistKind.FxMarket);\n\n    address _baseToken = IFxMarketV2(_market).baseToken();\n    uint256 _amount = LibGatewayRouter.transferInAndConvert(_params, _baseToken);\n    LibGatewayRouter.approve(_baseToken, _market, _amount);\n    _fTokenMinted = IFxMarketV2(_market).mintFToken(_amount, msg.sender, _minFTokenMinted);\n    LibGatewayRouter.refundERC20(_baseToken, msg.sender);\n  }\n\n  /// @notice Mint some xToken with given token and convert parameters.\n  /// @param _params The token converting parameters.\n  /// @param _market The address of market to use.\n  /// @param _minXTokenMinted The minimum amount of xToken should be received.\n  /// @return _xTokenMinted The amount of xToken received.\n  /// @return _bonusOut The amount of bonus base token received.\n  function fxMintXTokenV2(\n    LibGatewayRouter.ConvertInParams memory _params,\n    address _market,\n    uint256 _minXTokenMinted\n  ) external payable returns (uint256 _xTokenMinted, uint256 _bonusOut) {\n    LibGatewayRouter.ensureWhitelised(_market, LibGatewayRouter.WhitelistKind.FxMarket);\n\n    address _baseToken = IFxMarketV2(_market).baseToken();\n    uint256 _amount = LibGatewayRouter.transferInAndConvert(_params, _baseToken);\n    LibGatewayRouter.approve(_baseToken, _market, _amount);\n    (_xTokenMinted, _bonusOut) = IFxMarketV2(_market).mintXToken(_amount, msg.sender, _minXTokenMinted);\n    LibGatewayRouter.refundERC20(_baseToken, msg.sender);\n  }\n\n  /// @notice Redeem fToken and convert to some other token.\n  /// @param _params The token converting parameters.\n  /// @param _market The address of market to use.\n  /// @param _fTokenIn the amount of fToken to redeem, use `uint256(-1)` to redeem all fToken.\n  /// @param _minBaseToken The minimum amount of base token should be received.\n  /// @return _baseOut The amount of base token received.\n  /// @return _dstOut The amount of dst token received.\n  /// @return _bonusOut The amount of bonus base token received.\n  function fxRedeemFTokenV2(\n    LibGatewayRouter.ConvertOutParams memory _params,\n    address _market,\n    uint256 _fTokenIn,\n    uint256 _minBaseToken\n  )\n    external\n    returns (\n      uint256 _baseOut,\n      uint256 _dstOut,\n      uint256 _bonusOut\n    )\n  {\n    LibGatewayRouter.ensureWhitelised(_market, LibGatewayRouter.WhitelistKind.FxMarket);\n\n    address _fToken = IFxMarketV2(_market).fToken();\n    address _baseToken = IFxMarketV2(_market).baseToken();\n    _fTokenIn = LibGatewayRouter.transferTokenIn(_fToken, address(this), _fTokenIn);\n\n    (_baseOut, _bonusOut) = IFxMarketV2(_market).redeemFToken(_fTokenIn, address(this), _minBaseToken);\n    _dstOut = LibGatewayRouter.convertAndTransferOut(_params, _baseToken, _baseOut + _bonusOut, msg.sender);\n    LibGatewayRouter.refundERC20(_fToken, msg.sender);\n  }\n\n  /// @notice Redeem xToken and convert to some other token.\n  /// @param _params The token converting parameters.\n  /// @param _market The address of market to use.\n  /// @param _xTokenIn the amount of xToken to redeem, use `uint256(-1)` to redeem all xToken.\n  /// @param _minBaseToken The minimum amount of base token should be received.\n  /// @return _baseOut The amount of base token received.\n  /// @return _dstOut The amount of dst token received.\n  function fxRedeemXTokenV2(\n    LibGatewayRouter.ConvertOutParams memory _params,\n    address _market,\n    uint256 _xTokenIn,\n    uint256 _minBaseToken\n  ) external returns (uint256 _baseOut, uint256 _dstOut) {\n    LibGatewayRouter.ensureWhitelised(_market, LibGatewayRouter.WhitelistKind.FxMarket);\n\n    address _xToken = IFxMarketV2(_market).xToken();\n    address _baseToken = IFxMarketV2(_market).baseToken();\n    _xTokenIn = LibGatewayRouter.transferTokenIn(_xToken, address(this), _xTokenIn);\n\n    _baseOut = IFxMarketV2(_market).redeemXToken(_xTokenIn, address(this), _minBaseToken);\n    _dstOut = LibGatewayRouter.convertAndTransferOut(_params, _baseToken, _baseOut, msg.sender);\n    LibGatewayRouter.refundERC20(_xToken, msg.sender);\n  }\n\n  /// @notice Swap between fToken and xToken\n  /// @param _market The address of market to use.\n  /// @param _amountIn The amount of input token.\n  /// @param _fTokenForXToken Whether swap fToken for xToken.\n  /// @param _minOut The minimum amount of token should be received.\n  /// @return _amountOut The amount of token received.\n  /// @return _bonusOut The amount of bonus token received.\n  function fxSwapV2(\n    address _market,\n    uint256 _amountIn,\n    bool _fTokenForXToken,\n    uint256 _minOut\n  ) external returns (uint256 _amountOut, uint256 _bonusOut) {\n    LibGatewayRouter.ensureWhitelised(_market, LibGatewayRouter.WhitelistKind.FxMarket);\n\n    address _fToken = IFxMarketV2(_market).fToken();\n    address _xToken = IFxMarketV2(_market).xToken();\n    address _baseToken = IFxMarketV2(_market).baseToken();\n\n    if (_fTokenForXToken) {\n      _amountIn = LibGatewayRouter.transferTokenIn(_fToken, address(this), _amountIn);\n      (uint256 _baseOut, uint256 _redeemBonus) = IFxMarketV2(_market).redeemFToken(_amountIn, address(this), 0);\n      _bonusOut = _redeemBonus;\n      LibGatewayRouter.approve(_baseToken, _market, _baseOut);\n      (_amountOut, _redeemBonus) = IFxMarketV2(_market).mintXToken(_baseOut, msg.sender, 0);\n      _bonusOut += _redeemBonus;\n      LibGatewayRouter.refundERC20(_fToken, msg.sender);\n    } else {\n      _amountIn = LibGatewayRouter.transferTokenIn(_xToken, address(this), _amountIn);\n      uint256 _baseOut = IFxMarketV2(_market).redeemXToken(_amountIn, address(this), 0);\n      LibGatewayRouter.approve(_baseToken, _market, _baseOut);\n      _amountOut = IFxMarketV2(_market).mintFToken(_baseOut, msg.sender, _minOut);\n      LibGatewayRouter.refundERC20(_xToken, msg.sender);\n    }\n\n    LibGatewayRouter.refundERC20(_baseToken, msg.sender);\n  }\n\n  /// @notice Swap between fxUSD and xToken\n  /// @param _market The address of market to use.\n  /// @param _amountIn The amount of input token.\n  /// @param _fxUSDForXToken Whether swap fxUSD for xToken.\n  /// @param _minOut The minimum amount of token should be received.\n  /// @return _amountOut The amount of token received.\n  /// @return _bonusOut The amount of bonus token received.\n  function fxSwapFxUSD(\n    address _market,\n    uint256 _amountIn,\n    bool _fxUSDForXToken,\n    uint256 _minOut\n  ) external returns (uint256 _amountOut, uint256 _bonusOut) {\n    LibGatewayRouter.ensureWhitelised(_market, LibGatewayRouter.WhitelistKind.FxMarket);\n\n    address fxUSD = IFxMarketV2(_market).fxUSD();\n    address _xToken = IFxMarketV2(_market).xToken();\n    address _baseToken = IFxMarketV2(_market).baseToken();\n    if (_fxUSDForXToken) {\n      _amountIn = LibGatewayRouter.transferTokenIn(fxUSD, address(this), _amountIn);\n      (uint256 _baseOut, uint256 _redeemBonus) = IFxUSD(fxUSD).redeem(_baseToken, _amountIn, address(this), 0);\n      _bonusOut = _redeemBonus;\n      LibGatewayRouter.approve(_baseToken, _market, _baseOut);\n      (_amountOut, _redeemBonus) = IFxMarketV2(_market).mintXToken(_baseOut, msg.sender, 0);\n      _bonusOut += _redeemBonus;\n      LibGatewayRouter.refundERC20(fxUSD, msg.sender);\n    } else {\n      _amountIn = LibGatewayRouter.transferTokenIn(_xToken, address(this), _amountIn);\n      uint256 _baseOut = IFxMarketV2(_market).redeemXToken(_amountIn, address(this), 0);\n      LibGatewayRouter.approve(_baseToken, fxUSD, _baseOut);\n      _amountOut = IFxUSD(fxUSD).mint(_baseToken, _baseOut, msg.sender, _minOut);\n      LibGatewayRouter.refundERC20(_xToken, msg.sender);\n    }\n    LibGatewayRouter.refundERC20(_baseToken, msg.sender);\n  }\n\n  /// @notice Mint some fxUSD with given token and convert parameters.\n  /// @param _params The token converting parameters.\n  /// @param _fxUSD The address of fxUSD token.\n  /// @param _baseToken The address of base token used to mint.\n  /// @param _minFxUSDMinted The minimum amount of fxUSD should be received.\n  /// @return _fxUSDMinted The amount of fxUSD received.\n  function fxMintFxUSD(\n    LibGatewayRouter.ConvertInParams memory _params,\n    address _fxUSD,\n    address _baseToken,\n    uint256 _minFxUSDMinted\n  ) external payable returns (uint256 _fxUSDMinted) {\n    LibGatewayRouter.ensureWhitelised(_fxUSD, LibGatewayRouter.WhitelistKind.FxUSD);\n\n    uint256 _amount = LibGatewayRouter.transferInAndConvert(_params, _baseToken);\n    LibGatewayRouter.approve(_baseToken, _fxUSD, _amount);\n    _fxUSDMinted = IFxUSD(_fxUSD).mint(_baseToken, _amount, msg.sender, _minFxUSDMinted);\n    LibGatewayRouter.refundERC20(_baseToken, msg.sender);\n  }\n\n  /// @notice Mint some fxUSD and earn in rebalance pool with given token and convert parameters.\n  /// @param _params The token converting parameters.\n  /// @param _fxUSD The address of fxUSD token.\n  /// @param _pool The address of rebalance pool used to earn.\n  /// @param _minFxUSDMinted The minimum amount of fxUSD should be received.\n  /// @return _fxUSDMinted The amount of fxUSD received.\n  function fxMintFxUSDAndEarn(\n    LibGatewayRouter.ConvertInParams memory _params,\n    address _fxUSD,\n    address _pool,\n    uint256 _minFxUSDMinted\n  ) external payable returns (uint256 _fxUSDMinted) {\n    LibGatewayRouter.ensureWhitelised(_fxUSD, LibGatewayRouter.WhitelistKind.FxUSD);\n\n    address _baseToken = IFxShareableRebalancePool(_pool).baseToken();\n    uint256 _amount = LibGatewayRouter.transferInAndConvert(_params, _baseToken);\n    LibGatewayRouter.approve(_baseToken, _fxUSD, _amount);\n    _fxUSDMinted = IFxUSD(_fxUSD).mintAndEarn(_pool, _amount, msg.sender, _minFxUSDMinted);\n    LibGatewayRouter.refundERC20(_baseToken, msg.sender);\n  }\n\n  /// @notice Withdraw fToken from rebalance pool as fxUSD\n  /// @param _fxUSD The address of fxUSD token.\n  /// @param _pool The address of rebalance pool used.\n  /// @param _amountIn the amount of fToken to withdraw, use `uint256(-1)` to withdraw all fToken.\n  /// @return _amountOut The amount of fxUSD received.\n  function fxRebalancePoolWithdraw(\n    address _fxUSD,\n    address _pool,\n    uint256 _amountIn\n  ) external payable returns (uint256 _amountOut) {\n    LibGatewayRouter.ensureWhitelised(_fxUSD, LibGatewayRouter.WhitelistKind.FxUSD);\n\n    address _baseToken = IFxShareableRebalancePool(_pool).baseToken();\n    address _fToken = IFxShareableRebalancePool(_pool).asset();\n    _amountOut = IERC20Upgradeable(_fToken).balanceOf(address(this));\n    IFxShareableRebalancePool(_pool).withdrawFrom(msg.sender, _amountIn, address(this));\n    _amountOut = IERC20Upgradeable(_fToken).balanceOf(address(this)) - _amountOut;\n    LibGatewayRouter.approve(_fToken, _fxUSD, _amountOut);\n    IFxUSD(_fxUSD).wrap(_baseToken, _amountOut, msg.sender);\n  }\n\n  /// @notice Withdraw fToken from rebalance pool as target token.\n  /// @return _amountOut The amount of target token received.\n  function fxRebalancePoolWithdrawAs(\n    LibGatewayRouter.ConvertOutParams memory _params,\n    address _pool,\n    uint256 _amountIn\n  ) external payable returns (uint256 _amountOut) {\n    LibGatewayRouter.ensureWhitelised(_pool, LibGatewayRouter.WhitelistKind.FxRebalancePool);\n\n    address _baseToken = IFxShareableRebalancePool(_pool).baseToken();\n    address _fToken = IFxShareableRebalancePool(_pool).asset();\n    address _market = IFxShareableRebalancePool(_pool).market();\n    _amountOut = IERC20Upgradeable(_fToken).balanceOf(address(this));\n    IFxShareableRebalancePool(_pool).withdrawFrom(msg.sender, _amountIn, address(this));\n    _amountOut = IERC20Upgradeable(_fToken).balanceOf(address(this)) - _amountOut;\n    // assume all fToken will be redeem for simplicity\n    (uint256 _baseOut, uint256 _bonusOut) = IFxMarketV2(_market).redeemFToken(_amountOut, address(this), 0);\n    _amountOut = LibGatewayRouter.convertAndTransferOut(_params, _baseToken, _baseOut + _bonusOut, msg.sender);\n  }\n\n  /// @notice Redeem fxUSD and convert to some other token.\n  /// @param _params The token converting parameters.\n  /// @param _fxUSD The address of fxUSD token.\n  /// @param _baseToken The address of base token to use.\n  /// @param _fxUSDIn the amount of fxUSD to redeem, use `uint256(-1)` to redeem all fToken.\n  /// @param _minBaseToken The minimum amount of base token should be received.\n  /// @return _baseOut The amount of base token received.\n  /// @return _dstOut The amount of dst token received.\n  /// @return _bonusOut The amount of bonus base token received.\n  function fxRedeemFxUSD(\n    LibGatewayRouter.ConvertOutParams memory _params,\n    address _fxUSD,\n    address _baseToken,\n    uint256 _fxUSDIn,\n    uint256 _minBaseToken\n  )\n    external\n    payable\n    returns (\n      uint256 _baseOut,\n      uint256 _dstOut,\n      uint256 _bonusOut\n    )\n  {\n    LibGatewayRouter.ensureWhitelised(_fxUSD, LibGatewayRouter.WhitelistKind.FxUSD);\n\n    _fxUSDIn = LibGatewayRouter.transferTokenIn(_fxUSD, address(this), _fxUSDIn);\n    (_baseOut, _bonusOut) = IFxUSD(_fxUSD).redeem(_baseToken, _fxUSDIn, address(this), _minBaseToken);\n    _dstOut = LibGatewayRouter.convertAndTransferOut(_params, _baseToken, _baseOut + _bonusOut, msg.sender);\n    LibGatewayRouter.refundERC20(_fxUSD, msg.sender);\n  }\n\n  /// @notice Redeem fxUSD and convert to some other token.\n  /// @param _params The list of token converting parameters.\n  /// @param _fxUSD The address of fxUSD token.\n  /// @param _fxUSDIn the amount of fxUSD to redeem, use `uint256(-1)` to redeem all fToken.\n  /// @param _minBaseTokens The list of minimum amount of base token should be received.\n  /// @param _minDstOut The minimum amount of dst token should be received.\n  /// @return _baseOuts The list of amounts of base token received.\n  /// @return _bonusOuts The list of amount of bonus base token received.\n  /// @return _dstOut The amount of dst token received.\n  function fxAutoRedeemFxUSD(\n    LibGatewayRouter.ConvertOutParams[] memory _params,\n    address _fxUSD,\n    uint256 _fxUSDIn,\n    uint256[] memory _minBaseTokens,\n    uint256 _minDstOut\n  )\n    external\n    payable\n    returns (\n      uint256[] memory _baseOuts,\n      uint256[] memory _bonusOuts,\n      uint256 _dstOut\n    )\n  {\n    LibGatewayRouter.ensureWhitelised(_fxUSD, LibGatewayRouter.WhitelistKind.FxUSD);\n\n    _fxUSDIn = LibGatewayRouter.transferTokenIn(_fxUSD, address(this), _fxUSDIn);\n    address[] memory _baseTokens;\n    (_baseTokens, _baseOuts, _bonusOuts) = IFxUSD(_fxUSD).autoRedeem(_fxUSDIn, address(this), _minBaseTokens);\n    if (_params.length != _baseOuts.length) revert ErrorLengthMismatch();\n    for (uint256 i = 0; i < _params.length; i++) {\n      _dstOut += LibGatewayRouter.convertAndTransferOut(\n        _params[i],\n        _baseTokens[i],\n        _baseOuts[i] + _bonusOuts[i],\n        msg.sender\n      );\n    }\n    if (_dstOut < _minDstOut) {\n      revert LibGatewayRouter.ErrorInsufficientOutput();\n    }\n  }\n\n  /// @notice Swap base through fxUSD.\n  /// @param _fxUSD The address of fxUSD token.\n  /// @param _baseTokenIn The address of source base token to use.\n  /// @param _amountIn the amount of source base token to swap, use `uint256(-1)` to swapp all.\n  /// @param _baseTokenOut The address of target base token to use.\n  /// @param _minOut The minimum amount of target base token should be received.\n  /// @return _amountOut The amount of target base token received.\n  /// @return _bonusOut The amount of bonus base token received.\n  function fxBaseTokenSwap(\n    address _fxUSD,\n    address _baseTokenIn,\n    uint256 _amountIn,\n    address _baseTokenOut,\n    uint256 _minOut\n  ) external returns (uint256 _amountOut, uint256 _bonusOut) {\n    LibGatewayRouter.ensureWhitelised(_fxUSD, LibGatewayRouter.WhitelistKind.FxUSD);\n\n    _amountIn = LibGatewayRouter.transferTokenIn(_baseTokenIn, address(this), _amountIn);\n    LibGatewayRouter.approve(_baseTokenIn, _fxUSD, _amountIn);\n    uint256 _fxUSDMinted = IFxUSD(_fxUSD).mint(_baseTokenIn, _amountIn, address(this), 0);\n    (_amountOut, _bonusOut) = IFxUSD(_fxUSD).redeem(_baseTokenOut, _fxUSDMinted, msg.sender, _minOut);\n  }\n}\n"
      },
      "contracts/gateways/libraries/LibGatewayRouter.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { EnumerableSetUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/utils/structs/EnumerableSetUpgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/IERC20Upgradeable.sol\";\n\nimport { ITokenConverter } from \"../../helpers/converter/ITokenConverter.sol\";\n\nlibrary LibGatewayRouter {\n  using SafeERC20Upgradeable for IERC20Upgradeable;\n  using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when use unapproved target contract.\n  error ErrorTargetNotApproved();\n\n  /// @dev Thrown when msg.value is different from amount.\n  error ErrorMsgValueMismatch();\n\n  /// @dev Thrown when the output token is not enough.\n  error ErrorInsufficientOutput();\n\n  /// @dev Thrown when the whitelisted account type is incorrect.\n  error ErrorNotWhitelisted(WhitelistKind expected, WhitelistKind found);\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The storage slot for gateway storage.\n  bytes32 private constant GATEWAY_STORAGE_POSITION = keccak256(\"diamond.gateway.storage\");\n\n  /*********\n   * Enums *\n   *********/\n\n  enum WhitelistKind {\n    None,\n    DexAggregator,\n    FxMarket,\n    FxInitialFundVault,\n    FxRebalancePool,\n    FxUSD\n  }\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @param spenders Mapping from target address to token spender address.\n  /// @param approvedTargets The list of approved target contracts.\n  struct GatewayStorage {\n    mapping(address => address) spenders;\n    EnumerableSetUpgradeable.AddressSet approvedTargets;\n    mapping(address => WhitelistKind) whitelisted;\n  }\n\n  /// @notice The struct for input token convert parameters.\n  ///\n  /// @param src The address of source token.\n  /// @param amount The amount of source token.\n  /// @param target The address of converter contract.\n  /// @param data The calldata passing to the target contract.\n  /// @param minOut The minimum amount of output token should receive.\n  struct ConvertInParams {\n    address src;\n    uint256 amount;\n    address target;\n    bytes data;\n    uint256 minOut;\n  }\n\n  /// @notice The struct for output token convert parameters.\n  /// @param converter The address of converter contract.\n  /// @param minOut The minimum amount of output token should receive.\n  /// @param routes The convert route encodings.\n  struct ConvertOutParams {\n    address converter;\n    uint256 minOut;\n    uint256[] routes;\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Return the GatewayStorage reference.\n  function gatewayStorage() internal pure returns (GatewayStorage storage gs) {\n    bytes32 position = GATEWAY_STORAGE_POSITION;\n    assembly {\n      gs.slot := position\n    }\n  }\n\n  /// @dev Approve contract to be used in token converting.\n  function approveTarget(address target, address spender) internal {\n    GatewayStorage storage gs = gatewayStorage();\n\n    if (gs.approvedTargets.add(target) && target != spender) {\n      gs.spenders[target] = spender;\n    }\n  }\n\n  /// @dev Remove approve contract in token converting.\n  function removeTarget(address target) internal {\n    GatewayStorage storage gs = gatewayStorage();\n\n    if (gs.approvedTargets.remove(target)) {\n      delete gs.spenders[target];\n    }\n  }\n\n  /// @dev Whitelist account with type.\n  function updateWhitelist(address account, WhitelistKind kind) internal {\n    GatewayStorage storage gs = gatewayStorage();\n\n    gs.whitelisted[account] = kind;\n  }\n\n  /// @dev Check whether the account is whitelised with specific type.\n  function ensureWhitelised(address account, WhitelistKind kind) internal view {\n    GatewayStorage storage gs = gatewayStorage();\n\n    WhitelistKind cachedKind = gs.whitelisted[account];\n    if (cachedKind == WhitelistKind.None || cachedKind != kind) {\n      revert ErrorNotWhitelisted(kind, cachedKind);\n    }\n  }\n\n  /// @dev Transfer token into this contract and convert to `tokenOut`.\n  /// @param params The parameters used in token converting.\n  /// @param tokenOut The address of final converted token.\n  /// @return amountOut The amount of token received.\n  function transferInAndConvert(ConvertInParams memory params, address tokenOut) internal returns (uint256 amountOut) {\n    GatewayStorage storage gs = gatewayStorage();\n    if (!gs.approvedTargets.contains(params.target)) revert ErrorTargetNotApproved();\n\n    transferTokenIn(params.src, address(this), params.amount);\n\n    amountOut = IERC20Upgradeable(tokenOut).balanceOf(address(this));\n    bool _success;\n    if (params.src == address(0)) {\n      (_success, ) = params.target.call{ value: params.amount }(params.data);\n    } else {\n      address _spender = gs.spenders[params.target];\n      if (_spender == address(0)) _spender = params.target;\n\n      IERC20Upgradeable(params.src).safeApprove(_spender, 0);\n      IERC20Upgradeable(params.src).safeApprove(_spender, params.amount);\n      (_success, ) = params.target.call(params.data);\n    }\n\n    // below lines will propagate inner error up\n    if (!_success) {\n      // solhint-disable-next-line no-inline-assembly\n      assembly {\n        let ptr := mload(0x40)\n        let size := returndatasize()\n        returndatacopy(ptr, 0, size)\n        revert(ptr, size)\n      }\n    }\n\n    amountOut = IERC20Upgradeable(tokenOut).balanceOf(address(this)) - amountOut;\n  }\n\n  /// @dev Convert `tokenIn` to other token and transfer out.\n  /// @param params The parameters used in token converting.\n  /// @param tokenIn The address of token to convert.\n  /// @param amountIn The amount of token to convert.\n  /// @return amountOut The amount of token received.\n  function convertAndTransferOut(\n    ConvertOutParams memory params,\n    address tokenIn,\n    uint256 amountIn,\n    address receiver\n  ) internal returns (uint256 amountOut) {\n    GatewayStorage storage gs = gatewayStorage();\n    if (!gs.approvedTargets.contains(params.converter)) revert ErrorTargetNotApproved();\n    if (amountIn == 0) return 0;\n\n    amountOut = amountIn;\n    if (params.routes.length == 0) {\n      IERC20Upgradeable(tokenIn).safeTransfer(receiver, amountOut);\n    } else {\n      IERC20Upgradeable(tokenIn).safeTransfer(params.converter, amountOut);\n    }\n    for (uint256 i = 0; i < params.routes.length; i++) {\n      address _recipient = i == params.routes.length - 1 ? receiver : params.converter;\n      amountOut = ITokenConverter(params.converter).convert(params.routes[i], amountOut, _recipient);\n    }\n    if (amountOut < params.minOut) revert ErrorInsufficientOutput();\n  }\n\n  /// @dev Internal function to transfer token to this contract.\n  /// @param token The address of token to transfer.\n  /// @param amount The amount of token to transfer.\n  /// @return uint256 The amount of token transfered.\n  function transferTokenIn(\n    address token,\n    address receiver,\n    uint256 amount\n  ) internal returns (uint256) {\n    if (token == address(0)) {\n      if (msg.value != amount) revert ErrorMsgValueMismatch();\n    } else {\n      IERC20Upgradeable(token).safeTransferFrom(msg.sender, receiver, amount);\n    }\n    return amount;\n  }\n\n  /// @dev Internal function to refund extra token.\n  /// @param token The address of token to refund.\n  /// @param recipient The address of the token receiver.\n  function refundERC20(address token, address recipient) internal {\n    uint256 _balance = IERC20Upgradeable(token).balanceOf(address(this));\n    if (_balance > 0) {\n      IERC20Upgradeable(token).safeTransfer(recipient, _balance);\n    }\n  }\n\n  function approve(\n    address token,\n    address spender,\n    uint256 amount\n  ) internal {\n    IERC20Upgradeable(token).safeApprove(spender, 0);\n    IERC20Upgradeable(token).safeApprove(spender, amount);\n  }\n}\n"
      },
      "contracts/helpers/converter/ITokenConverter.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface ITokenConverter {\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of Converter Registry.\n  function registry() external view returns (address);\n\n  /// @notice Return the input token and output token for the route.\n  /// @param route The encoding of the route.\n  /// @return tokenIn The address of input token.\n  /// @return tokenOut The address of output token.\n  function getTokenPair(uint256 route) external view returns (address tokenIn, address tokenOut);\n\n  /// @notice Query the output token amount according to the encoding.\n  ///\n  /// @dev See the comments in `convert` for the meaning of encoding.\n  ///\n  /// @param encoding The encoding used to convert.\n  /// @param amountIn The amount of input token.\n  /// @param amountOut The amount of output token received.\n  function queryConvert(uint256 encoding, uint256 amountIn) external returns (uint256 amountOut);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Convert input token to output token according to the encoding.\n  /// Assuming that the input token is already in the contract.\n  ///\n  /// @dev encoding for single route\n  /// |   8 bits  | 2 bits |  246 bits  |\n  /// | pool_type | action | customized |\n  ///\n  /// + pool_type = 0: UniswapV2, only action = 0\n  ///   customized = |   160 bits   | 24 bits |     1 bit    | 1 bit | ... |\n  ///                | pool address | fee_num | zero_for_one | twamm | ... |\n  /// + pool_type = 1: UniswapV3, only action = 0\n  ///   customized = |   160 bits   | 24 bits |     1 bit    | ... |\n  ///                | pool address | fee_num | zero_for_one | ... |\n  /// + pool_type = 2: BalancerV1, only action = 0\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |\n  ///                | pool address | tokens | index in | index out | ... |\n  /// + pool_type = 3: BalancerV2, only action = 0\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |\n  ///                | pool address | tokens | index in | index out | ... |\n  /// + pool_type = 4: CurvePlainPool or CurveFactoryPlainPool\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |  1 bit  | ... |\n  ///                | pool address | tokens | index in | index out | use_eth | ... |\n  /// + pool_type = 5: CurveAPool\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |     1 bits     | ... |\n  ///                | pool address | tokens | index in | index out | use_underlying | ... |\n  /// + pool_type = 6: CurveYPool\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |     1 bits     | ... |\n  ///                | pool address | tokens | index in | index out | use_underlying | ... |\n  /// + pool_type = 7: CurveMetaPool or CurveFactoryMetaPool\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |\n  ///                | pool address | tokens | index in | index out | ... |\n  /// + pool_type = 8: CurveCryptoPool or CurveFactoryCryptoPool\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  |  1 bit  | ... |\n  ///                | pool address | tokens | index in | index out | use_eth | ... |\n  /// + pool_type = 9: ERC4626, no action 0\n  ///   customized = |   160 bits   | ... |\n  ///                | pool address | ... |\n  /// + pool_type = 10: Lido, no action 0\n  ///   customized = |   160 bits   | ... |\n  ///                | pool address | ... |\n  /// + pool_type = 11:  ETHLSDConverter v1, no action 0\n  ///   supported in other pool type\n  ///     puffer: pufETH is ERC4626, base is stETH\n  ///     frax: sfrxETH is ERC4626, base is frxETH\n  ///     pirex: apxETH is ERC4626, base is pxETH\n  ///   supported in this pool type\n  ///     0=wBETH: mint wBETH from ETH\n  ///     1=RocketPool: mint rETH from ETH\n  ///     2=frax: mint frxETH from ETH\n  ///     3=pirex: mint pxETH from ETH\n  ///     4=renzo: mint ezETH from ETH, stETH, wBETH\n  ///     5=ether.fi: mint eETH from ETH, mint weETH from eETH, unwrap weETH to eETH\n  ///     6=kelpdao.xyz: mint rsETH from ETH, ETHx, stETH, sfrxETH, and etc.\n  ///   customized = |   160 bits   |  8 bits  | ... |\n  ///                | pool address | protocol | ... |\n  /// + pool_type = 12: CurveStableSwapNG\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |\n  ///                | pool address | tokens | index in | index out | ... |\n  /// + pool_type = 13: CurveStableSwapMetaNG\n  ///   customized = |   160 bits   | 3 bits |  3 bits  |   3 bits  | ... |\n  ///                | pool address | tokens | index in | index out | ... |\n  /// + pool_type = 14: WETH\n  ///   customized = |   160 bits   | ... |\n  ///                | pool address | ... |\n  ///\n  /// Note: tokens + 1 is the number of tokens of the pool\n  ///\n  /// + action = 0: swap\n  /// + action = 1: add liquidity / wrap / stake\n  /// + action = 2: remove liquidity / unwrap / unstake\n  ///\n  /// @param encoding The encoding used to convert.\n  /// @param amountIn The amount of input token.\n  /// @param recipient The address of token receiver.\n  /// @return amountOut The amount of output token received.\n  function convert(\n    uint256 encoding,\n    uint256 amountIn,\n    address recipient\n  ) external payable returns (uint256 amountOut);\n\n  /// @notice Withdraw dust assets in this contract.\n  /// @param token The address of token to withdraw.\n  /// @param recipient The address of token receiver.\n  function withdrawFund(address token, address recipient) external;\n}\n"
      },
      "contracts/interfaces/f(x)/IFxBoostableRebalancePool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxBoostableRebalancePool {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when user deposit asset into this contract.\n  /// @param owner The address of asset owner.\n  /// @param reciever The address of receiver of the asset in this contract.\n  /// @param amount The amount of asset deposited.\n  event Deposit(address indexed owner, address indexed reciever, uint256 amount);\n\n  /// @notice Emitted when the amount of deposited asset changed due to liquidation or deposit or unlock.\n  /// @param owner The address of asset owner.\n  /// @param newDeposit The new amount of deposited asset.\n  /// @param loss The amount of asset used by liquidation.\n  event UserDepositChange(address indexed owner, uint256 newDeposit, uint256 loss);\n\n  /// @notice Emitted when user withdraw asset.\n  /// @param owner The address of asset owner.\n  /// @param reciever The address of receiver of the asset.\n  /// @param amount The amount of token to withdraw.\n  event Withdraw(address indexed owner, address indexed reciever, uint256 amount);\n\n  /// @notice Emitted when liquidation happens.\n  /// @param liquidated The amount of asset liquidated.\n  /// @param baseGained The amount of base token gained.\n  event Liquidate(uint256 liquidated, uint256 baseGained);\n\n  /// @notice Emitted when the address of reward wrapper is updated.\n  /// @param oldWrapper The address of previous reward wrapper.\n  /// @param newWrapper The address of current reward wrapper.\n  event UpdateWrapper(address indexed oldWrapper, address indexed newWrapper);\n\n  /// @notice Emitted when the liquidatable collateral ratio is updated.\n  /// @param oldRatio The previous liquidatable collateral ratio.\n  /// @param newRatio The current liquidatable collateral ratio.\n  event UpdateLiquidatableCollateralRatio(uint256 oldRatio, uint256 newRatio);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown then the src token mismatched.\n  error ErrorWrapperSrcMismatch();\n\n  /// @dev Thrown then the dst token mismatched.\n  error ErrorWrapperDstMismatch();\n\n  /// @dev Thrown when the deposited amount is zero.\n  error DepositZeroAmount();\n\n  /// @dev Thrown when the withdrawn amount is zero.\n  error WithdrawZeroAmount();\n\n  /// @dev Thrown the cannot liquidate.\n  error CannotLiquidate();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the address of treasury contract.\n  function treasury() external view returns (address);\n\n  /// @notice Return the address of market contract.\n  function market() external view returns (address);\n\n  /// @notice Return the address of base token.\n  function baseToken() external view returns (address);\n\n  /// @notice Return the address of underlying token of this contract.\n  function asset() external view returns (address);\n\n  /// @notice Return the total amount of asset deposited to this contract.\n  function totalSupply() external view returns (uint256);\n\n  /// @notice Return the amount of deposited asset for some specific user.\n  /// @param account The address of user to query.\n  function balanceOf(address account) external view returns (uint256);\n\n  /// @notice Return the current boost ratio for some specific user.\n  /// @param account The address of user to query, multiplied by 1e18.\n  function getBoostRatio(address account) external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Deposit some asset to this contract.\n  /// @dev Use `amount=uint256(-1)` if you want to deposit all asset held.\n  /// @param amount The amount of asset to deposit.\n  /// @param receiver The address of recipient for the deposited asset.\n  function deposit(uint256 amount, address receiver) external;\n\n  /// @notice Withdraw asset from this contract.\n  function withdraw(uint256 amount, address receiver) external;\n\n  /// @notice Liquidate asset for base token.\n  /// @param maxAmount The maximum amount of asset to liquidate.\n  /// @param minBaseOut The minimum amount of base token should receive.\n  /// @return liquidated The amount of asset liquidated.\n  /// @return baseOut The amount of base token received.\n  function liquidate(uint256 maxAmount, uint256 minBaseOut) external returns (uint256 liquidated, uint256 baseOut);\n}\n"
      },
      "contracts/interfaces/f(x)/IFxMarketV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxMarketV2 {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when fToken is minted.\n  /// @param owner The address of base token owner.\n  /// @param recipient The address of receiver for fToken or xToken.\n  /// @param baseTokenIn The amount of base token deposited.\n  /// @param fTokenOut The amount of fToken minted.\n  /// @param mintFee The amount of mint fee charged.\n  event MintFToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 baseTokenIn,\n    uint256 fTokenOut,\n    uint256 mintFee\n  );\n\n  /// @notice Emitted when xToken is minted.\n  /// @param owner The address of base token owner.\n  /// @param recipient The address of receiver for fToken or xToken.\n  /// @param baseTokenIn The amount of base token deposited.\n  /// @param xTokenOut The amount of xToken minted.\n  /// @param bonus The amount of base token as bonus.\n  /// @param mintFee The amount of mint fee charged.\n  event MintXToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 baseTokenIn,\n    uint256 xTokenOut,\n    uint256 bonus,\n    uint256 mintFee\n  );\n\n  /// @notice Emitted when someone redeem base token with fToken or xToken.\n  /// @param owner The address of fToken and xToken owner.\n  /// @param recipient The address of receiver for base token.\n  /// @param fTokenBurned The amount of fToken burned.\n  /// @param baseTokenOut The amount of base token redeemed.\n  /// @param bonus The amount of base token as bonus.\n  /// @param redeemFee The amount of redeem fee charged.\n  event RedeemFToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 fTokenBurned,\n    uint256 baseTokenOut,\n    uint256 bonus,\n    uint256 redeemFee\n  );\n\n  /// @notice Emitted when someone redeem base token with fToken or xToken.\n  /// @param owner The address of fToken and xToken owner.\n  /// @param recipient The address of receiver for base token.\n  /// @param xTokenBurned The amount of xToken burned.\n  /// @param baseTokenOut The amount of base token redeemed.\n  /// @param redeemFee The amount of redeem fee charged.\n  event RedeemXToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 xTokenBurned,\n    uint256 baseTokenOut,\n    uint256 redeemFee\n  );\n\n  /// @notice Emitted when the fee ratio for minting fToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateMintFeeRatioFToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the fee ratio for minting xToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateMintFeeRatioXToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the fee ratio for redeeming fToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateRedeemFeeRatioFToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the fee ratio for redeeming xToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateRedeemFeeRatioXToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the stability ratio is updated.\n  /// @param oldRatio The previous collateral ratio to enter stability mode, multiplied by 1e18.\n  /// @param newRatio The current collateral ratio to enter stability mode, multiplied by 1e18.\n  event UpdateStabilityRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the platform contract is updated.\n  /// @param oldPlatform The address of previous platform contract.\n  /// @param newPlatform The address of current platform contract.\n  event UpdatePlatform(address indexed oldPlatform, address indexed newPlatform);\n\n  /// @notice Emitted when the  reserve pool contract is updated.\n  /// @param oldReservePool The address of previous reserve pool contract.\n  /// @param newReservePool The address of current reserve pool contract.\n  event UpdateReservePool(address indexed oldReservePool, address indexed newReservePool);\n\n  /// @notice Emitted when the RebalancePoolRegistry contract is updated.\n  /// @param oldRegistry The address of previous RebalancePoolRegistry contract.\n  /// @param newRegistry The address of current RebalancePoolRegistry contract.\n  event UpdateRebalancePoolRegistry(address indexed oldRegistry, address indexed newRegistry);\n\n  /// @notice Pause or unpause mint.\n  /// @param oldStatus The previous status for mint.\n  /// @param newStatus The current status for mint.\n  event UpdateMintStatus(bool oldStatus, bool newStatus);\n\n  /// @notice Pause or unpause redeem.\n  /// @param oldStatus The previous status for redeem.\n  /// @param newStatus The current status for redeem.\n  event UpdateRedeemStatus(bool oldStatus, bool newStatus);\n\n  /// @notice Pause or unpause fToken mint in stability mode.\n  /// @param oldStatus The previous status for mint.\n  /// @param newStatus The current status for mint.\n  event UpdateFTokenMintStatusInStabilityMode(bool oldStatus, bool newStatus);\n\n  /// @notice Pause or unpause xToken redeem in stability mode.\n  /// @param oldStatus The previous status for redeem.\n  /// @param newStatus The current status for redeem.\n  event UpdateXTokenRedeemStatusInStabilityMode(bool oldStatus, bool newStatus);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when the caller if not fUSD contract.\n  error ErrorCallerNotFUSD();\n\n  /// @dev Thrown when token mint is paused.\n  error ErrorMintPaused();\n\n  /// @dev Thrown when fToken mint is paused in stability mode.\n  error ErrorFTokenMintPausedInStabilityMode();\n\n  /// @dev Thrown when mint with zero amount base token.\n  error ErrorMintZeroAmount();\n\n  /// @dev Thrown when the amount of fToken is not enough.\n  error ErrorInsufficientFTokenOutput();\n\n  /// @dev Thrown when the amount of xToken is not enough.\n  error ErrorInsufficientXTokenOutput();\n\n  /// @dev Thrown when token redeem is paused.\n  error ErrorRedeemPaused();\n\n  /// @dev Thrown when xToken redeem is paused in stability mode.\n  error ErrorXTokenRedeemPausedInStabilityMode();\n\n  /// @dev Thrown when redeem with zero amount fToken or xToken.\n  error ErrorRedeemZeroAmount();\n\n  /// @dev Thrown when the amount of base token is not enough.\n  error ErrorInsufficientBaseOutput();\n\n  /// @dev Thrown when the stability ratio is too large.\n  error ErrorStabilityRatioTooLarge();\n\n  /// @dev Thrown when the default fee is too large.\n  error ErrorDefaultFeeTooLarge();\n\n  /// @dev Thrown when the delta fee is too small.\n  error ErrorDeltaFeeTooSmall();\n\n  /// @dev Thrown when the sum of default fee and delta fee is too large.\n  error ErrorTotalFeeTooLarge();\n\n  /// @dev Thrown when the given address is zero.\n  error ErrorZeroAddress();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of Treasury contract.\n  function treasury() external view returns (address);\n\n  /// @notice Return the address of base token.\n  function baseToken() external view returns (address);\n\n  /// @notice Return the address fractional base token.\n  function fToken() external view returns (address);\n\n  /// @notice Return the address leveraged base token.\n  function xToken() external view returns (address);\n\n  /// @notice Return the address of fxUSD token.\n  function fxUSD() external view returns (address);\n\n  /// @notice Return the collateral ratio to enter stability mode, multiplied by 1e18.\n  function stabilityRatio() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint some fToken with some base token.\n  /// @param baseIn The amount of wrapped value of base token supplied, use `uint256(-1)` to supply all base token.\n  /// @param recipient The address of receiver for fToken.\n  /// @param minFTokenMinted The minimum amount of fToken should be received.\n  /// @return fTokenMinted The amount of fToken should be received.\n  function mintFToken(\n    uint256 baseIn,\n    address recipient,\n    uint256 minFTokenMinted\n  ) external returns (uint256 fTokenMinted);\n\n  /// @notice Mint some xToken with some base token.\n  /// @param baseIn The amount of wrapped value of base token supplied, use `uint256(-1)` to supply all base token.\n  /// @param recipient The address of receiver for xToken.\n  /// @param minXTokenMinted The minimum amount of xToken should be received.\n  /// @return xTokenMinted The amount of xToken should be received.\n  /// @return bonus The amount of wrapped value of base token as bonus.\n  function mintXToken(\n    uint256 baseIn,\n    address recipient,\n    uint256 minXTokenMinted\n  ) external returns (uint256 xTokenMinted, uint256 bonus);\n\n  /// @notice Redeem base token with fToken.\n  /// @param fTokenIn the amount of fToken to redeem, use `uint256(-1)` to redeem all fToken.\n  /// @param recipient The address of receiver for base token.\n  /// @param minBaseOut The minimum amount of wrapped value of base token should be received.\n  /// @return baseOut The amount of wrapped value of base token should be received.\n  /// @return bonus The amount of wrapped value of base token as bonus.\n  function redeemFToken(\n    uint256 fTokenIn,\n    address recipient,\n    uint256 minBaseOut\n  ) external returns (uint256 baseOut, uint256 bonus);\n\n  /// @notice Redeem base token with xToken.\n  /// @param xTokenIn the amount of xToken to redeem, use `uint256(-1)` to redeem all xToken.\n  /// @param recipient The address of receiver for base token.\n  /// @param minBaseOut The minimum amount of wrapped value of base token should be received.\n  /// @return baseOut The amount of wrapped value of base token should be received.\n  function redeemXToken(\n    uint256 xTokenIn,\n    address recipient,\n    uint256 minBaseOut\n  ) external returns (uint256 baseOut);\n}\n"
      },
      "contracts/interfaces/f(x)/IFxShareableRebalancePool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { IFxBoostableRebalancePool } from \"./IFxBoostableRebalancePool.sol\";\n\ninterface IFxShareableRebalancePool is IFxBoostableRebalancePool {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when one user share votes to another user.\n  /// @param owner The address of votes owner.\n  /// @param staker The address of staker to share votes.\n  event ShareVote(address indexed owner, address indexed staker);\n\n  /// @notice Emitted when the owner cancel sharing to some staker.\n  /// @param owner The address of votes owner.\n  /// @param staker The address of staker to cancel votes share.\n  event CancelShareVote(address indexed owner, address indexed staker);\n\n  /// @notice Emitted when staker accept the vote sharing.\n  /// @param staker The address of the staker.\n  /// @param oldOwner The address of the previous vote sharing owner.\n  /// @param newOwner The address of the current vote sharing owner.\n  event AcceptSharedVote(address indexed staker, address indexed oldOwner, address indexed newOwner);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when caller shares votes to self.\n  error ErrorSelfSharingIsNotAllowed();\n\n  /// @dev Thrown when a staker with shared votes try to share its votes to others.\n  error ErrorCascadedSharingIsNotAllowed();\n\n  /// @dev Thrown when staker try to accept non-allowed vote sharing.\n  error ErrorVoteShareNotAllowed();\n\n  /// @dev Thrown when staker try to reject a non-existed vote sharing.\n  error ErrorNoAcceptedSharedVote();\n\n  /// @dev Thrown when the staker has ability to share ve balance.\n  error ErrorVoteOwnerCannotStake();\n\n  /// @dev Thrown when staker try to accept twice.\n  error ErrorRepeatAcceptSharedVote();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the owner of votes of some staker.\n  /// @param account The address of user to query.\n  function getStakerVoteOwner(address account) external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Withdraw asset from this contract on behalf of someone\n  function withdrawFrom(\n    address owner,\n    uint256 amount,\n    address receiver\n  ) external;\n\n  /// @notice Owner changes the vote sharing state for some user.\n  /// @param staker The address of user to change.\n  function toggleVoteSharing(address staker) external;\n\n  /// @notice Staker accepts the vote sharing.\n  /// @param newOwner The address of the owner of the votes.\n  function acceptSharedVote(address newOwner) external;\n\n  /// @notice Staker reject the current vote sharing.\n  function rejectSharedVote() external;\n}\n"
      },
      "contracts/interfaces/f(x)/IFxTreasuryV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxTreasuryV2 {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the platform contract is updated.\n  /// @param oldPlatform The address of previous platform contract.\n  /// @param newPlatform The address of current platform contract.\n  event UpdatePlatform(address indexed oldPlatform, address indexed newPlatform);\n\n  /// @notice Emitted when the RebalancePoolSplitter contract is updated.\n  /// @param oldRebalancePoolSplitter The address of previous RebalancePoolSplitter contract.\n  /// @param newRebalancePoolSplitter The address of current RebalancePoolSplitter.\n  event UpdateRebalancePoolSplitter(address indexed oldRebalancePoolSplitter, address indexed newRebalancePoolSplitter);\n\n  /// @notice Emitted when the price oracle contract is updated.\n  /// @param oldPriceOracle The address of previous price oracle.\n  /// @param newPriceOracle The address of current price oracle.\n  event UpdatePriceOracle(address indexed oldPriceOracle, address indexed newPriceOracle);\n\n  /// @notice Emitted when the strategy contract is updated.\n  /// @param oldStrategy The address of previous strategy.\n  /// @param newStrategy The address of current strategy.\n  event UpdateStrategy(address indexed oldStrategy, address indexed newStrategy);\n\n  /// @notice Emitted when the base token cap is updated.\n  /// @param oldBaseTokenCap The value of previous base token cap.\n  /// @param newBaseTokenCap The value of current base token cap.\n  event UpdateBaseTokenCap(uint256 oldBaseTokenCap, uint256 newBaseTokenCap);\n\n  /// @notice Emitted when the EMA sample interval is updated.\n  /// @param oldSampleInterval The value of previous EMA sample interval.\n  /// @param newSampleInterval The value of current EMA sample interval.\n  event UpdateEMASampleInterval(uint256 oldSampleInterval, uint256 newSampleInterval);\n\n  /// @notice Emitted when the reference price is updated.\n  /// @param oldPrice The value of previous reference price.\n  /// @param newPrice The value of current reference price.\n  event Settle(uint256 oldPrice, uint256 newPrice);\n\n  /// @notice Emitted when the ratio for rebalance pool is updated.\n  /// @param oldRatio The value of the previous ratio, multipled by 1e9.\n  /// @param newRatio The value of the current ratio, multipled by 1e9.\n  event UpdateRebalancePoolRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the ratio for harvester is updated.\n  /// @param oldRatio The value of the previous ratio, multipled by 1e9.\n  /// @param newRatio The value of the current ratio, multipled by 1e9.\n  event UpdateHarvesterRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when someone harvest pending stETH rewards.\n  /// @param caller The address of caller.\n  /// @param totalRewards The amount of total harvested rewards.\n  /// @param rebalancePoolRewards The amount of harvested rewards distributed to stability pool.\n  /// @param harvestBounty The amount of harvested rewards distributed to caller as harvest bounty.\n  event Harvest(address indexed caller, uint256 totalRewards, uint256 rebalancePoolRewards, uint256 harvestBounty);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when the collateral ratio is smaller than 100%.\n  error ErrorCollateralRatioTooSmall();\n\n  /// @dev Thrown when mint exceed total capacity.\n  error ErrorExceedTotalCap();\n\n  /// @dev Thrown when the oracle price is invalid.\n  error ErrorInvalidOraclePrice();\n\n  /// @dev Thrown when the twap price is invalid.\n  error ErrorInvalidTwapPrice();\n\n  /// @dev Thrown when initialize protocol twice.\n  error ErrorProtocolInitialized();\n\n  /// @dev Thrown when the initial amount of base token is not enough.\n  error ErrorInsufficientInitialBaseToken();\n\n  /// @dev Thrown when current is under collateral.\n  error ErrorUnderCollateral();\n\n  /// @dev Thrown when the sample internal for EMA is too small.\n  error ErrorEMASampleIntervalTooSmall();\n\n  /// @dev Thrown when the expense ratio exceeds `MAX_REBALANCE_POOL_RATIO`.\n  error ErrorRebalancePoolRatioTooLarge();\n\n  /// @dev Thrown when the harvester ratio exceeds `MAX_HARVESTER_RATIO`.\n  error ErrorHarvesterRatioTooLarge();\n\n  /// @dev Thrown when the given address is zero.\n  error ErrorZeroAddress();\n\n  /*********\n   * Enums *\n   *********/\n\n  enum Action {\n    None,\n    MintFToken,\n    MintXToken,\n    RedeemFToken,\n    RedeemXToken\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the address of base token.\n  function baseToken() external view returns (address);\n\n  /// @notice Return the address fractional base token.\n  function fToken() external view returns (address);\n\n  /// @notice Return the address leveraged base token.\n  function xToken() external view returns (address);\n\n  /// @notice The reference base token price.\n  function referenceBaseTokenPrice() external view returns (uint256);\n\n  /// @notice The current base token price.\n  function currentBaseTokenPrice() external view returns (uint256);\n\n  /// @notice Return whether the price is valid.\n  function isBaseTokenPriceValid() external view returns (bool);\n\n  /// @notice Return the total amount of underlying value of base token deposited.\n  function totalBaseToken() external view returns (uint256);\n\n  /// @notice Return the address of strategy contract.\n  function strategy() external view returns (address);\n\n  /// @notice Return the total amount of base token managed by strategy.\n  function strategyUnderlying() external view returns (uint256);\n\n  /// @notice Return the current collateral ratio of fToken, multipled by 1e18.\n  function collateralRatio() external view returns (uint256);\n\n  /// @notice Return whether the system is under collateral.\n  function isUnderCollateral() external view returns (bool);\n\n  /// @notice Compute the amount of base token needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseIn The amount of underlying value of base token needed.\n  /// @return maxFTokenMintable The amount of fToken can be minted.\n  function maxMintableFToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseIn, uint256 maxFTokenMintable);\n\n  /// @notice Compute the amount of base token needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseIn The amount of underlying value of base token needed.\n  /// @return maxXTokenMintable The amount of xToken can be minted.\n  function maxMintableXToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseIn, uint256 maxXTokenMintable);\n\n  /// @notice Compute the amount of fToken needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseOut The amount of underlying value of base token redeemed.\n  /// @return maxFTokenRedeemable The amount of fToken needed.\n  function maxRedeemableFToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseOut, uint256 maxFTokenRedeemable);\n\n  /// @notice Compute the amount of xToken needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseOut The amount of underlying value of base token redeemed.\n  /// @return maxXTokenRedeemable The amount of xToken needed.\n  function maxRedeemableXToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseOut, uint256 maxXTokenRedeemable);\n\n  /// @notice Return the exponential moving average of the leverage ratio.\n  function leverageRatio() external view returns (uint256);\n\n  /// @notice Convert underlying token amount to wrapped token amount.\n  /// @param amount The underlying token amount.\n  function getWrapppedValue(uint256 amount) external view returns (uint256);\n\n  /// @notice Convert wrapped token amount to underlying token amount.\n  /// @param amount The wrapped token amount.\n  function getUnderlyingValue(uint256 amount) external view returns (uint256);\n\n  /// @notice Return the fee ratio distributed to rebalance pool, multipled by 1e9.\n  function getRebalancePoolRatio() external view returns (uint256);\n\n  /// @notice Return the fee ratio distributed to harvester, multipled by 1e9.\n  function getHarvesterRatio() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Initialize the protocol.\n  /// @param baseIn The amount of underlying value of the base token used to initialize.\n  function initializeProtocol(uint256 baseIn) external returns (uint256 fTokenOut, uint256 xTokenOut);\n\n  /// @notice Mint fToken with some base token.\n  /// @param baseIn The amount of underlying value of base token deposited.\n  /// @param recipient The address of receiver.\n  /// @return fTokenOut The amount of fToken minted.\n  function mintFToken(uint256 baseIn, address recipient) external returns (uint256 fTokenOut);\n\n  /// @notice Mint xToken with some base token.\n  /// @param baseIn The amount of underlying value of base token deposited.\n  /// @param recipient The address of receiver.\n  /// @return xTokenOut The amount of xToken minted.\n  function mintXToken(uint256 baseIn, address recipient) external returns (uint256 xTokenOut);\n\n  /// @notice Redeem fToken and xToken to base tokne.\n  /// @param fTokenIn The amount of fToken to redeem.\n  /// @param xTokenIn The amount of xToken to redeem.\n  /// @param owner The owner of the fToken or xToken.\n  /// @param baseOut The amount of underlying value of base token redeemed.\n  function redeem(\n    uint256 fTokenIn,\n    uint256 xTokenIn,\n    address owner\n  ) external returns (uint256 baseOut);\n\n  /// @notice Settle the nav of base token, fToken and xToken.\n  function settle() external;\n\n  /// @notice Transfer some base token to strategy contract.\n  /// @param amount The amount of token to transfer.\n  function transferToStrategy(uint256 amount) external;\n\n  /// @notice Notify base token profit from strategy contract.\n  /// @param amount The amount of base token.\n  function notifyStrategyProfit(uint256 amount) external;\n\n  /// @notice Harvest pending rewards to stability pool.\n  function harvest() external;\n}\n"
      },
      "contracts/interfaces/f(x)/IFxUSD.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxUSD {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when a new market is added.\n  /// @param baseToken The address of base token of the market.\n  /// @param mintCap The mint capacity of the market.\n  event AddMarket(address indexed baseToken, uint256 mintCap);\n\n  /// @notice Emitted when the mint capacity is updated.\n  /// @param baseToken The address of base token of the market.\n  /// @param oldCap The value of previous mint capacity.\n  /// @param newCap The value of current mint capacity.\n  event UpdateMintCap(address indexed baseToken, uint256 oldCap, uint256 newCap);\n\n  /// @notice Emitted when a new rebalance pool is added.\n  /// @param baseToken The address of base token of the market.\n  /// @param pool The address of the rebalance pool.\n  event AddRebalancePool(address indexed baseToken, address indexed pool);\n\n  /// @notice Emitted when a new rebalance pool is removed.\n  /// @param baseToken The address of base token of the market.\n  /// @param pool The address of the rebalance pool.\n  event RemoveRebalancePool(address indexed baseToken, address indexed pool);\n\n  /// @notice Emitted when someone wrap fToken as fxUSD.\n  /// @param baseToken The address of base token of the market.\n  /// @param owner The address of fToken owner.\n  /// @param receiver The address of fxUSD recipient.\n  /// @param amount The amount of fxUSD minted.\n  event Wrap(address indexed baseToken, address indexed owner, address indexed receiver, uint256 amount);\n\n  /// @notice Emitted when someone unwrap fxUSD as fToken.\n  /// @param baseToken The address of base token of the market.\n  /// @param owner The address of fxUSD owner.\n  /// @param receiver The address of base token recipient.\n  /// @param amount The amount of fxUSD burned.\n  event Unwrap(address indexed baseToken, address indexed owner, address indexed receiver, uint256 amount);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when someone tries to interact with unsupported market.\n  error ErrorUnsupportedMarket();\n\n  /// @dev Thrown when someone tries to interact with unsupported rebalance pool.\n  error ErrorUnsupportedRebalancePool();\n\n  /// @dev Thrown when someone tries to interact with market in stability mode.\n  error ErrorMarketInStabilityMode();\n\n  /// @dev Thrown when someone tries to interact with market has invalid price.\n  error ErrorMarketWithInvalidPrice();\n\n  /// @dev Thrown when someone tries to add a supported market.\n  error ErrorMarketAlreadySupported();\n\n  /// @dev Thrown when the total supply of fToken exceed mint capacity.\n  error ErrorExceedMintCap();\n\n  /// @dev Thrown when the amount of fToken is not enough for redeem.\n  error ErrorInsufficientLiquidity();\n\n  /// @dev Thrown when current is under collateral.\n  error ErrorUnderCollateral();\n\n  /// @dev Thrown when the length of two arrays is mismatch.\n  error ErrorLengthMismatch();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the list of supported markets.\n  function getMarkets() external view returns (address[] memory);\n\n  /// @notice Return the list of supported rebalance pools.\n  function getRebalancePools() external view returns (address[] memory);\n\n  /// @notice Return the nav of fxUSD.\n  function nav() external view returns (uint256);\n\n  /// @notice Return whether the system is under collateral.\n  function isUnderCollateral() external view returns (bool);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Wrap fToken to fxUSD.\n  /// @param baseToken The address of corresponding base token.\n  /// @param amount The amount of fToken to wrap.\n  /// @param receiver The address of fxUSD recipient.\n  function wrap(\n    address baseToken,\n    uint256 amount,\n    address receiver\n  ) external;\n\n  /// @notice Wrap fToken from rebalance pool to fxUSD.\n  /// @param pool The address of rebalance pool.\n  /// @param amount The amount of fToken to wrap.\n  /// @param receiver The address of fxUSD recipient.\n  function wrapFrom(\n    address pool,\n    uint256 amount,\n    address receiver\n  ) external;\n\n  /// @notice Mint fxUSD with base token.\n  /// @param baseToken The address of the base token.\n  /// @param amountIn The amount of base token to use.\n  /// @param receiver The address of fxUSD recipient.\n  /// @param minOut The minimum amount of fxUSD should receive.\n  /// @return amountOut The amount of fxUSD received by the receiver.\n  function mint(\n    address baseToken,\n    uint256 amountIn,\n    address receiver,\n    uint256 minOut\n  ) external returns (uint256 amountOut);\n\n  /// @notice Deposit fxUSD to rebalance pool.\n  /// @param pool The address of rebalance pool.\n  /// @param amount The amount of fxUSD to use.\n  /// @param receiver The address of rebalance pool share recipient.\n  function earn(\n    address pool,\n    uint256 amount,\n    address receiver\n  ) external;\n\n  /// @notice Mint fxUSD with base token and deposit to rebalance pool.\n  /// @param pool The address of rebalance pool.\n  /// @param amountIn The amount of base token to use.\n  /// @param receiver The address of rebalance pool recipient.\n  /// @param minOut The minimum amount of rebalance pool shares should receive.\n  /// @return amountOut The amount of rebalance pool shares received by the receiver.\n  function mintAndEarn(\n    address pool,\n    uint256 amountIn,\n    address receiver,\n    uint256 minOut\n  ) external returns (uint256 amountOut);\n\n  /// @notice Redeem fxUSD to base token.\n  /// @param baseToken The address of the base token.\n  /// @param amountIn The amount of fxUSD to redeem.\n  /// @param receiver The address of base token recipient.\n  /// @param minOut The minimum amount of base token should receive.\n  /// @return amountOut The amount of base token received by the receiver.\n  /// @return bonusOut The amount of bonus base token received by the receiver.\n  function redeem(\n    address baseToken,\n    uint256 amountIn,\n    address receiver,\n    uint256 minOut\n  ) external returns (uint256 amountOut, uint256 bonusOut);\n\n  /// @notice Redeem fToken from rebalance pool to base token.\n  /// @param amountIn The amount of fxUSD to redeem.\n  /// @param receiver The address of base token recipient.\n  /// @param minOut The minimum amount of base token should receive.\n  /// @return amountOut The amount of base token received by the receiver.\n  /// @return bonusOut The amount of bonus base token received by the receiver.\n  function redeemFrom(\n    address pool,\n    uint256 amountIn,\n    address receiver,\n    uint256 minOut\n  ) external returns (uint256 amountOut, uint256 bonusOut);\n\n  /// @notice Redeem fxUSD to base token optimally.\n  /// @param amountIn The amount of fxUSD to redeem.\n  /// @param receiver The address of base token recipient.\n  /// @param minOuts The list of minimum amount of base token should receive.\n  /// @return baseTokens The list of base token received by the receiver.\n  /// @return amountOuts The list of amount of base token received by the receiver.\n  /// @return bonusOuts The list of amount of bonus base token received by the receiver.\n  function autoRedeem(\n    uint256 amountIn,\n    address receiver,\n    uint256[] memory minOuts\n  )\n    external\n    returns (\n      address[] memory baseTokens,\n      uint256[] memory amountOuts,\n      uint256[] memory bonusOuts\n    );\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "evmVersion": "shanghai",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}