creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable-v4/access/AccessControlUpgradeable.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 \"./IAccessControlUpgradeable.sol\";\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../utils/StringsUpgradeable.sol\";\nimport \"../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {\n    function __AccessControl_init() internal onlyInitializing {\n    }\n\n    function __AccessControl_init_unchained() internal onlyInitializing {\n    }\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(IAccessControlUpgradeable).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                        StringsUpgradeable.toHexString(account),\n                        \" is missing role \",\n                        StringsUpgradeable.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    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable-v4/access/IAccessControlUpgradeable.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 IAccessControlUpgradeable {\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-upgradeable-v4/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized != type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable-v4/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      },
      "@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/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\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 ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\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    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable-v4/utils/introspection/ERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165Upgradeable).interfaceId;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable-v4/utils/introspection/IERC165Upgradeable.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 IERC165Upgradeable {\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-upgradeable-v4/utils/math/MathUpgradeable.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 MathUpgradeable {\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-upgradeable-v4/utils/math/SignedMathUpgradeable.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 SignedMathUpgradeable {\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-upgradeable-v4/utils/StringsUpgradeable.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/MathUpgradeable.sol\";\nimport \"./math/SignedMathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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 = MathUpgradeable.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(SignedMathUpgradeable.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, MathUpgradeable.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/common/codec/WordCodec.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n// solhint-disable no-inline-assembly\n\n/// @dev A subset copied from the following contracts:\n///\n/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol`\n/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodecHelpers.sol`\nlibrary WordCodec {\n  /// @dev Inserts an unsigned integer of bitLength, shifted by an offset, into a 256 bit word,\n  /// replacing the old value. Returns the new word.\n  function insertUint(\n    bytes32 word,\n    uint256 value,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32 result) {\n    // Equivalent to:\n    // uint256 mask = (1 << bitLength) - 1;\n    // bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));\n    // result = clearedWord | bytes32(value << offset);\n    assembly {\n      let mask := sub(shl(bitLength, 1), 1)\n      let clearedWord := and(word, not(shl(offset, mask)))\n      result := or(clearedWord, shl(offset, value))\n    }\n  }\n\n  /// @dev Decodes and returns an unsigned integer with `bitLength` bits, shifted by an offset, from a 256 bit word.\n  function decodeUint(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (uint256 result) {\n    // Equivalent to:\n    // result = uint256(word >> offset) & ((1 << bitLength) - 1);\n    assembly {\n      result := and(shr(offset, word), sub(shl(bitLength, 1), 1))\n    }\n  }\n\n  /// @dev Inserts a signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns\n  /// the new word.\n  ///\n  /// Assumes `value` can be represented using `bitLength` bits.\n  function insertInt(\n    bytes32 word,\n    int256 value,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32) {\n    unchecked {\n      uint256 mask = (1 << bitLength) - 1;\n      bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));\n      // Integer values need masking to remove the upper bits of negative values.\n      return clearedWord | bytes32((uint256(value) & mask) << offset);\n    }\n  }\n\n  /// @dev Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word.\n  function decodeInt(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (int256 result) {\n    unchecked {\n      int256 maxInt = int256((1 << (bitLength - 1)) - 1);\n      uint256 mask = (1 << bitLength) - 1;\n\n      int256 value = int256(uint256(word >> offset) & mask);\n      // In case the decoded value is greater than the max positive integer that can be represented with bitLength\n      // bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit\n      // representation.\n      //\n      // Equivalent to:\n      // result = value > maxInt ? (value | int256(~mask)) : value;\n      assembly {\n        result := or(mul(gt(value, maxInt), not(mask)), value)\n      }\n    }\n  }\n\n  /// @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.\n  function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool result) {\n    // Equivalent to:\n    // result = (uint256(word >> offset) & 1) == 1;\n    assembly {\n      result := and(shr(offset, word), 1)\n    }\n  }\n\n  /// @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new\n  /// word.\n  function insertBool(\n    bytes32 word,\n    bool value,\n    uint256 offset\n  ) internal pure returns (bytes32 result) {\n    // Equivalent to:\n    // bytes32 clearedWord = bytes32(uint256(word) & ~(1 << offset));\n    // bytes32 referenceInsertBool = clearedWord | bytes32(uint256(value ? 1 : 0) << offset);\n    assembly {\n      let clearedWord := and(word, not(shl(offset, 1)))\n      result := or(clearedWord, shl(offset, value))\n    }\n  }\n\n  function clearWordAtPosition(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32 clearedWord) {\n    unchecked {\n      uint256 mask = (1 << bitLength) - 1;\n      clearedWord = bytes32(uint256(word) & ~(mask << offset));\n    }\n  }\n}\n"
      },
      "contracts/common/math/ExponentialMovingAverageV8.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { LogExpMathV8 } from \"./LogExpMathV8.sol\";\n\n// solhint-disable not-rely-on-time\n\n/// @dev See https://en.wikipedia.org/wiki/Exponential_smoothing\n/// It is the same as `ExponentialMovingAverageV7` with `unchecked` scope.\nlibrary ExponentialMovingAverageV8 {\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The precision used to compute EMA.\n  uint256 private constant PRECISION = 1e18;\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev Compiler will pack this into single `uint256`.\n  /// @param lastTime The last timestamp when the storage is updated.\n  /// @param sampleInterval The sampling time interval used in the EMA.\n  /// @param lastValue The last value in the data sequence, with precision 1e18.\n  /// @param lastEmaValue The last EMA value computed, with precision 1e18.\n  struct EMAStorage {\n    uint40 lastTime;\n    uint24 sampleInterval;\n    uint96 lastValue;\n    uint96 lastEmaValue;\n  }\n\n  /// @dev Save value of EMA storage.\n  /// @param s The EMA storage.\n  /// @param value The new value, with precision 1e18.\n  function saveValue(EMAStorage memory s, uint96 value) internal view {\n    s.lastEmaValue = uint96(emaValue(s));\n    s.lastValue = value;\n    s.lastTime = uint40(block.timestamp);\n  }\n\n  /// @dev Return the current ema value.\n  /// @param s The EMA storage.\n  function emaValue(EMAStorage memory s) internal view returns (uint256) {\n    unchecked {\n      if (uint256(s.lastTime) < block.timestamp) {\n        uint256 dt = block.timestamp - uint256(s.lastTime);\n        uint256 e = (dt * PRECISION) / s.sampleInterval;\n        if (e > 41e18) {\n          return s.lastValue;\n        } else {\n          uint256 alpha = uint256(LogExpMathV8.exp(-int256(e)));\n          return (s.lastValue * (PRECISION - alpha) + s.lastEmaValue * alpha) / PRECISION;\n        }\n      } else {\n        return s.lastEmaValue;\n      }\n    }\n  }\n}\n"
      },
      "contracts/common/math/LogExpMathV8.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n\n// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\npragma solidity ^0.8.0;\n\n/* solhint-disable */\n\n/**\n * @dev Copied from https://github.com/balancer/balancer-v2-monorepo/blob/master/pkg/solidity-utils/contracts/math/LogExpMath.sol\n *\n * Some modifications are made due to compile error.\n *\n * It is the same as `LogExpMathV8` with `unchecked` scope.\n *\n * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).\n *\n * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural\n * exponentiation and logarithm (where the base is Euler's number).\n *\n * @author Fernando Martinelli - @fernandomartinelli\n * @author Sergio Yuhjtman - @sergioyuhjtman\n * @author Daniel Fernandez - @dmf7z\n */\nlibrary LogExpMathV8 {\n  // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying\n  // two numbers, and multiply by ONE when dividing them.\n\n  // All arguments and return values are 18 decimal fixed point numbers.\n  int256 constant ONE_18 = 1e18;\n\n  // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the\n  // case of ln36, 36 decimals.\n  int256 constant ONE_20 = 1e20;\n  int256 constant ONE_36 = 1e36;\n\n  // The domain of natural exponentiation is bound by the word size and number of decimals used.\n  //\n  // Because internally the result will be stored using 20 decimals, the largest possible result is\n  // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.\n  // The smallest possible result is 10^(-18), which makes largest negative argument\n  // ln(10^(-18)) = -41.446531673892822312.\n  // We use 130.0 and -41.0 to have some safety margin.\n  int256 constant MAX_NATURAL_EXPONENT = 130e18;\n  int256 constant MIN_NATURAL_EXPONENT = -41e18;\n\n  // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point\n  // 256 bit integer.\n  int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;\n  int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;\n\n  uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);\n\n  // 18 decimal constants\n  int256 constant x0 = 128000000000000000000; // 2ˆ7\n  int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)\n  int256 constant x1 = 64000000000000000000; // 2ˆ6\n  int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)\n\n  // 20 decimal constants\n  int256 constant x2 = 3200000000000000000000; // 2ˆ5\n  int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)\n  int256 constant x3 = 1600000000000000000000; // 2ˆ4\n  int256 constant a3 = 888611052050787263676000000; // eˆ(x3)\n  int256 constant x4 = 800000000000000000000; // 2ˆ3\n  int256 constant a4 = 298095798704172827474000; // eˆ(x4)\n  int256 constant x5 = 400000000000000000000; // 2ˆ2\n  int256 constant a5 = 5459815003314423907810; // eˆ(x5)\n  int256 constant x6 = 200000000000000000000; // 2ˆ1\n  int256 constant a6 = 738905609893065022723; // eˆ(x6)\n  int256 constant x7 = 100000000000000000000; // 2ˆ0\n  int256 constant a7 = 271828182845904523536; // eˆ(x7)\n  int256 constant x8 = 50000000000000000000; // 2ˆ-1\n  int256 constant a8 = 164872127070012814685; // eˆ(x8)\n  int256 constant x9 = 25000000000000000000; // 2ˆ-2\n  int256 constant a9 = 128402541668774148407; // eˆ(x9)\n  int256 constant x10 = 12500000000000000000; // 2ˆ-3\n  int256 constant a10 = 113314845306682631683; // eˆ(x10)\n  int256 constant x11 = 6250000000000000000; // 2ˆ-4\n  int256 constant a11 = 106449445891785942956; // eˆ(x11)\n\n  /**\n   * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.\n   *\n   * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.\n   */\n  function pow(uint256 x, uint256 y) internal pure returns (uint256) {\n    unchecked {\n      if (y == 0) {\n        // We solve the 0^0 indetermination by making it equal one.\n        return uint256(ONE_18);\n      }\n\n      if (x == 0) {\n        return 0;\n      }\n\n      // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to\n      // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means\n      // x^y = exp(y * ln(x)).\n\n      // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.\n      require(x >> 255 == 0, \"X_OUT_OF_BOUNDS\");\n      int256 x_int256 = int256(x);\n\n      // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In\n      // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.\n\n      // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.\n      require(y < MILD_EXPONENT_BOUND, \"Y_OUT_OF_BOUNDS\");\n      int256 y_int256 = int256(y);\n\n      int256 logx_times_y;\n      if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {\n        int256 ln_36_x = _ln_36(x_int256);\n\n        // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just\n        // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal\n        // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the\n        // (downscaled) last 18 decimals.\n        logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);\n      } else {\n        logx_times_y = _ln(x_int256) * y_int256;\n      }\n      logx_times_y /= ONE_18;\n\n      // Finally, we compute exp(y * ln(x)) to arrive at x^y\n      require(MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, \"PRODUCT_OUT_OF_BOUNDS\");\n\n      return uint256(exp(logx_times_y));\n    }\n  }\n\n  /**\n   * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.\n   *\n   * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.\n   */\n  function exp(int256 x) internal pure returns (int256) {\n    unchecked {\n      require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, \"INVALID_EXPONENT\");\n\n      if (x < 0) {\n        // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it\n        // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).\n        // Fixed point division requires multiplying by ONE_18.\n        return ((ONE_18 * ONE_18) / exp(-x));\n      }\n\n      // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,\n      // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7\n      // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the\n      // decomposition.\n      // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this\n      // decomposition, which will be lower than the smallest x_n.\n      // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.\n      // We mutate x by subtracting x_n, making it the remainder of the decomposition.\n\n      // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause\n      // intermediate overflows. Instead we store them as plain integers, with 0 decimals.\n      // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the\n      // decomposition.\n\n      // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct\n      // it and compute the accumulated product.\n\n      int256 firstAN;\n      if (x >= x0) {\n        x -= x0;\n        firstAN = a0;\n      } else if (x >= x1) {\n        x -= x1;\n        firstAN = a1;\n      } else {\n        firstAN = 1; // One with no decimal places\n      }\n\n      // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the\n      // smaller terms.\n      x *= 100;\n\n      // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point\n      // one. Recall that fixed point multiplication requires dividing by ONE_20.\n      int256 product = ONE_20;\n\n      if (x >= x2) {\n        x -= x2;\n        product = (product * a2) / ONE_20;\n      }\n      if (x >= x3) {\n        x -= x3;\n        product = (product * a3) / ONE_20;\n      }\n      if (x >= x4) {\n        x -= x4;\n        product = (product * a4) / ONE_20;\n      }\n      if (x >= x5) {\n        x -= x5;\n        product = (product * a5) / ONE_20;\n      }\n      if (x >= x6) {\n        x -= x6;\n        product = (product * a6) / ONE_20;\n      }\n      if (x >= x7) {\n        x -= x7;\n        product = (product * a7) / ONE_20;\n      }\n      if (x >= x8) {\n        x -= x8;\n        product = (product * a8) / ONE_20;\n      }\n      if (x >= x9) {\n        x -= x9;\n        product = (product * a9) / ONE_20;\n      }\n\n      // x10 and x11 are unnecessary here since we have high enough precision already.\n\n      // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series\n      // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).\n\n      int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.\n      int256 term; // Each term in the sum, where the nth term is (x^n / n!).\n\n      // The first term is simply x.\n      term = x;\n      seriesSum += term;\n\n      // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,\n      // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.\n\n      term = ((term * x) / ONE_20) / 2;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 3;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 4;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 5;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 6;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 7;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 8;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 9;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 10;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 11;\n      seriesSum += term;\n\n      term = ((term * x) / ONE_20) / 12;\n      seriesSum += term;\n\n      // 12 Taylor terms are sufficient for 18 decimal precision.\n\n      // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor\n      // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply\n      // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),\n      // and then drop two digits to return an 18 decimal value.\n\n      return (((product * seriesSum) / ONE_20) * firstAN) / 100;\n    }\n  }\n\n  /**\n   * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.\n   */\n  function log(int256 arg, int256 base) internal pure returns (int256) {\n    unchecked {\n      // This performs a simple base change: log(arg, base) = ln(arg) / ln(base).\n\n      // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by\n      // upscaling.\n\n      int256 logBase;\n      if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {\n        logBase = _ln_36(base);\n      } else {\n        logBase = _ln(base) * ONE_18;\n      }\n\n      int256 logArg;\n      if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {\n        logArg = _ln_36(arg);\n      } else {\n        logArg = _ln(arg) * ONE_18;\n      }\n\n      // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places\n      return (logArg * ONE_18) / logBase;\n    }\n  }\n\n  /**\n   * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.\n   */\n  function ln(int256 a) internal pure returns (int256) {\n    unchecked {\n      // The real natural logarithm is not defined for negative numbers or zero.\n      require(a > 0, \"OUT_OF_BOUNDS\");\n      if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {\n        return _ln_36(a) / ONE_18;\n      } else {\n        return _ln(a);\n      }\n    }\n  }\n\n  /**\n   * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.\n   */\n  function _ln(int256 a) private pure returns (int256) {\n    unchecked {\n      if (a < ONE_18) {\n        // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less\n        // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.\n        // Fixed point division requires multiplying by ONE_18.\n        return (-_ln((ONE_18 * ONE_18) / a));\n      }\n\n      // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which\n      // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,\n      // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot\n      // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.\n      // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this\n      // decomposition, which will be lower than the smallest a_n.\n      // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.\n      // We mutate a by subtracting a_n, making it the remainder of the decomposition.\n\n      // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point\n      // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by\n      // ONE_18 to convert them to fixed point.\n      // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide\n      // by it and compute the accumulated sum.\n\n      int256 sum = 0;\n      if (a >= a0 * ONE_18) {\n        a /= a0; // Integer, not fixed point division\n        sum += x0;\n      }\n\n      if (a >= a1 * ONE_18) {\n        a /= a1; // Integer, not fixed point division\n        sum += x1;\n      }\n\n      // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.\n      sum *= 100;\n      a *= 100;\n\n      // Because further a_n are  20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.\n\n      if (a >= a2) {\n        a = (a * ONE_20) / a2;\n        sum += x2;\n      }\n\n      if (a >= a3) {\n        a = (a * ONE_20) / a3;\n        sum += x3;\n      }\n\n      if (a >= a4) {\n        a = (a * ONE_20) / a4;\n        sum += x4;\n      }\n\n      if (a >= a5) {\n        a = (a * ONE_20) / a5;\n        sum += x5;\n      }\n\n      if (a >= a6) {\n        a = (a * ONE_20) / a6;\n        sum += x6;\n      }\n\n      if (a >= a7) {\n        a = (a * ONE_20) / a7;\n        sum += x7;\n      }\n\n      if (a >= a8) {\n        a = (a * ONE_20) / a8;\n        sum += x8;\n      }\n\n      if (a >= a9) {\n        a = (a * ONE_20) / a9;\n        sum += x9;\n      }\n\n      if (a >= a10) {\n        a = (a * ONE_20) / a10;\n        sum += x10;\n      }\n\n      if (a >= a11) {\n        a = (a * ONE_20) / a11;\n        sum += x11;\n      }\n\n      // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series\n      // that converges rapidly for values of `a` close to one - the same one used in ln_36.\n      // Let z = (a - 1) / (a + 1).\n      // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))\n\n      // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires\n      // division by ONE_20.\n      int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);\n      int256 z_squared = (z * z) / ONE_20;\n\n      // num is the numerator of the series: the z^(2 * n + 1) term\n      int256 num = z;\n\n      // seriesSum holds the accumulated sum of each term in the series, starting with the initial z\n      int256 seriesSum = num;\n\n      // In each step, the numerator is multiplied by z^2\n      num = (num * z_squared) / ONE_20;\n      seriesSum += num / 3;\n\n      num = (num * z_squared) / ONE_20;\n      seriesSum += num / 5;\n\n      num = (num * z_squared) / ONE_20;\n      seriesSum += num / 7;\n\n      num = (num * z_squared) / ONE_20;\n      seriesSum += num / 9;\n\n      num = (num * z_squared) / ONE_20;\n      seriesSum += num / 11;\n\n      // 6 Taylor terms are sufficient for 36 decimal precision.\n\n      // Finally, we multiply by 2 (non fixed point) to compute ln(remainder)\n      seriesSum *= 2;\n\n      // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both\n      // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal\n      // value.\n\n      return (sum + seriesSum) / 100;\n    }\n  }\n\n  /**\n   * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,\n   * for x close to one.\n   *\n   * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.\n   */\n  function _ln_36(int256 x) private pure returns (int256) {\n    unchecked {\n      // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits\n      // worthwhile.\n\n      // First, we transform x to a 36 digit fixed point value.\n      x *= ONE_18;\n\n      // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).\n      // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))\n\n      // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires\n      // division by ONE_36.\n      int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);\n      int256 z_squared = (z * z) / ONE_36;\n\n      // num is the numerator of the series: the z^(2 * n + 1) term\n      int256 num = z;\n\n      // seriesSum holds the accumulated sum of each term in the series, starting with the initial z\n      int256 seriesSum = num;\n\n      // In each step, the numerator is multiplied by z^2\n      num = (num * z_squared) / ONE_36;\n      seriesSum += num / 3;\n\n      num = (num * z_squared) / ONE_36;\n      seriesSum += num / 5;\n\n      num = (num * z_squared) / ONE_36;\n      seriesSum += num / 7;\n\n      num = (num * z_squared) / ONE_36;\n      seriesSum += num / 9;\n\n      num = (num * z_squared) / ONE_36;\n      seriesSum += num / 11;\n\n      num = (num * z_squared) / ONE_36;\n      seriesSum += num / 13;\n\n      num = (num * z_squared) / ONE_36;\n      seriesSum += num / 15;\n\n      // 8 Taylor terms are sufficient for 36 decimal precision.\n\n      // All that remains is multiplying by 2 (non fixed point).\n      return seriesSum * 2;\n    }\n  }\n}\n"
      },
      "contracts/f(x)/funding-cost-market/funding-rate-adapter/CrvUSDBorrowRateAdapter.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.20;\n\nimport { AccessControlUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/access/AccessControlUpgradeable.sol\";\n\nimport { ICrvUSDAmm } from \"../../../interfaces/curve/ICrvUSDAmm.sol\";\n\nabstract contract CrvUSDBorrowRateAdapter is AccessControlUpgradeable {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the funding cost scale is updated.\n  /// @param oldScale The value of previous funding cost scale.\n  /// @param newScale The value of current funding cost scale.\n  event UpdateFundingCostScale(uint256 oldScale, uint256 newScale);\n\n  /// @notice Emitted when the funding rate snapshot is taken.\n  /// @param timestamp The timestamp to capture.\n  /// @param borrowIndex The crvUSD borrow index.\n  event CaptureFundingRate(uint256 timestamp, uint256 borrowIndex);\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The precision of borrow rate.\n  uint256 private constant PRECISION = 1e18;\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev The struct for crvUSD borrow rate snapshot.\n  /// @param borrowIndex The current borrow index of crvUSD.\n  /// @param timestamp The timestamp when the snapshot is taken.\n  struct BorrowRateSnapshot {\n    // In AggMonetaryPolicy, the maximum apy is 300%. It takes about 34 years to reach `uint128.max` in worse case.\n    // So it should be safe to user `uint128` for `borrowIndex`. Here is how 34 years comes from:\n    //   + The maximum APR per second is 4.3959106799e-08 because (1+4.3959106799e-08)^(365 * 86400) = 4\n    //   + We need to solve the (1+4.3959106799e-08)^(x * 86400 * 365) = 2^128 / 10^18, x = 34.102647135518694.\n    uint128 borrowIndex;\n    uint128 timestamp;\n  }\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @notice The address of crvUSD AMM.\n  address public amm;\n\n  /// @notice The snapshot for crvUSD borrow rate.\n  BorrowRateSnapshot public borrowRateSnapshot;\n\n  /// @notice The scale for the funding cost based on crvUSD borrow rate.\n  uint256 public fundingCostScale;\n\n  /// @dev Slots for future use.\n  uint256[47] private _gap;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  function __CrvUSDBorrowRateAdaptor_init(address _amm) internal onlyInitializing {\n    amm = _amm;\n\n    _updateFundingCostScale(5e17); // 0.5 as initial value\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the current funding rate with scale.\n  function getFundingRate() public view returns (uint256 _fundingRate) {\n    uint256 prevBorrowIndex = borrowRateSnapshot.borrowIndex;\n    uint256 newBorrowIndex = ICrvUSDAmm(amm).get_rate_mul();\n    _fundingRate = ((newBorrowIndex - uint256(prevBorrowIndex)) * PRECISION) / uint128(prevBorrowIndex);\n    _fundingRate = (_fundingRate * fundingCostScale) / PRECISION;\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Internal function update the funding cost scale.\n  /// @param _newScale The value of new funding rate scale, multipled by 1e18.\n  function updateFundingCostScale(uint256 _newScale) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    _updateFundingCostScale(_newScale);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to calculate the funding rate since last snapshot and take snapshot.\n  function _captureFundingRate() internal {\n    BorrowRateSnapshot memory cachedBorrowRateSnapshot = borrowRateSnapshot;\n\n    uint256 newBorrowIndex = ICrvUSDAmm(amm).get_rate_mul();\n    cachedBorrowRateSnapshot.borrowIndex = uint128(newBorrowIndex);\n    cachedBorrowRateSnapshot.timestamp = uint128(block.timestamp);\n    borrowRateSnapshot = cachedBorrowRateSnapshot;\n\n    emit CaptureFundingRate(block.timestamp, newBorrowIndex);\n  }\n\n  /// @dev Internal function update the funding cost scale.\n  /// @param _newScale The value of new funding rate scale, multipled by 1e18.\n  function _updateFundingCostScale(uint256 _newScale) internal {\n    uint256 _oldScale = fundingCostScale;\n    fundingCostScale = _newScale;\n\n    emit UpdateFundingCostScale(_oldScale, _newScale);\n  }\n}\n"
      },
      "contracts/f(x)/funding-cost-market/TreasuryWithFundingCost.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 { ICrvUSDAmm } from \"../../interfaces/curve/ICrvUSDAmm.sol\";\nimport { IFxTreasuryV2 } from \"../../interfaces/f(x)/IFxTreasuryV2.sol\";\n\nimport { ExponentialMovingAverageV8 } from \"../../common/math/ExponentialMovingAverageV8.sol\";\nimport { FxStableMath } from \"../math/FxStableMath.sol\";\nimport { TreasuryV2 } from \"../v2/TreasuryV2.sol\";\nimport { CrvUSDBorrowRateAdapter } from \"./funding-rate-adapter/CrvUSDBorrowRateAdapter.sol\";\n\ncontract TreasuryWithFundingCost is TreasuryV2, CrvUSDBorrowRateAdapter {\n  using ExponentialMovingAverageV8 for ExponentialMovingAverageV8.EMAStorage;\n  using FxStableMath for FxStableMath.SwapState;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(\n    address _baseToken,\n    address _fToken,\n    address _xToken\n  ) TreasuryV2(_baseToken, _fToken, _xToken) {}\n\n  function initialize(\n    address _platform,\n    address _rebalancePoolSplitter,\n    address _priceOracle,\n    uint256 _baseTokenCap,\n    uint24 sampleInterval,\n    address _amm\n  ) external initializer {\n    __Context_init();\n    __ERC165_init();\n    __AccessControl_init();\n\n    __TreasuryV2_init(_platform, _rebalancePoolSplitter, _priceOracle, _baseTokenCap, sampleInterval);\n    __CrvUSDBorrowRateAdaptor_init(_amm);\n\n    _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc TreasuryV2\n  function harvestable() public view override returns (uint256) {\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.None, false);\n    return _harvestable(_state);\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc TreasuryV2\n  function harvest() external virtual override {\n    // no need to harvest\n    if (borrowRateSnapshot.timestamp == block.timestamp) return;\n\n    // silently return when invalid price or under collateral\n    // since `MarketWithFundingCost` would call this in each action.\n    if (!isBaseTokenPriceValid()) return;\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.None, false);\n    if (_state.xNav == 0) return;\n    // update leverage\n    _updateEMALeverageRatio(_state);\n\n    uint256 _totalRewards = _harvestable(_state);\n    totalBaseToken -= getUnderlyingValue(_totalRewards);\n    _captureFundingRate();\n\n    _distributedHarvestedRewards(_totalRewards);\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @inheritdoc IFxTreasuryV2\n  function initializeProtocol(uint256 _baseIn)\n    external\n    virtual\n    override\n    onlyRole(PROTOCOL_INITIALIZER_ROLE)\n    returns (uint256 fTokenOut, uint256 xTokenOut)\n  {\n    (fTokenOut, xTokenOut) = _initializeProtocol(_baseIn);\n    borrowRateSnapshot = BorrowRateSnapshot(uint128(ICrvUSDAmm(amm).get_rate_mul()), uint128(block.timestamp));\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @inheritdoc TreasuryV2\n  function _loadSwapState(Action _action)\n    internal\n    view\n    virtual\n    override\n    returns (FxStableMath.SwapState memory _state)\n  {\n    return _loadSwapState(_action, true);\n  }\n\n  /// @dev Internal function to load swap variable to memory and deduct funding cost if needed.\n  function _loadSwapState(Action _action, bool _deductFundingCost)\n    private\n    view\n    returns (FxStableMath.SwapState memory _state)\n  {\n    _state.baseSupply = totalBaseToken;\n    (_state.baseTwapNav, _state.baseNav) = _fetchBaseTokenPrice(_action);\n\n    if (_state.baseSupply == 0) {\n      _state.xNav = PRECISION;\n    } else {\n      _state.fSupply = IERC20Upgradeable(fToken).totalSupply();\n      _state.xSupply = IERC20Upgradeable(xToken).totalSupply();\n      _computeXTokenNav(_state);\n    }\n\n    // deduct funding costs if possible\n    if (_deductFundingCost && borrowRateSnapshot.timestamp < block.timestamp) {\n      _state.baseSupply -= getUnderlyingValue(_harvestable(_state));\n      // recompute xToken nav\n      _computeXTokenNav(_state);\n    }\n  }\n\n  /// @dev Internal function to compute xToken nav\n  function _computeXTokenNav(FxStableMath.SwapState memory _state) private pure {\n    if (_state.xSupply == 0) {\n      // no xToken, treat the nav of xToken as 1.0\n      _state.xNav = PRECISION;\n    } else {\n      uint256 _baseVal = _state.baseSupply * _state.baseNav;\n      uint256 _fVal = _state.fSupply * PRECISION;\n      if (_baseVal >= _fVal) {\n        _state.xNav = (_baseVal - _fVal) / _state.xSupply;\n      } else {\n        // under collateral\n        _state.xNav = 0;\n      }\n    }\n  }\n\n  /// @dev Internal function to compute the funding costs.\n  function _harvestable(FxStableMath.SwapState memory _state) private view returns (uint256) {\n    // usually the leverage should always >= 1.0, but if < 1.0, the function will revert.\n    uint256 _leverage = _state.leverageRatio();\n    uint256 _fundingRate = getFundingRate();\n    // funding cost = (xToken Value * (leverage - 1) / leverage * funding rate * scale) / baseNav\n    uint256 _fundingCost = ((_state.xNav * _state.xSupply * (_leverage - PRECISION)) / _leverage);\n    _fundingCost = (_fundingCost * _fundingRate) / PRECISION;\n    _fundingCost /= _state.baseNav;\n\n    return getWrapppedValue(_fundingCost);\n  }\n}\n"
      },
      "contracts/f(x)/math/FxStableMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @dev In this library, we assume the nav for fractional token is always 1.\nlibrary FxStableMath {\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The precision used to compute nav.\n  uint256 internal constant PRECISION = 1e18;\n\n  /// @dev The precision used to compute nav.\n  int256 internal constant PRECISION_I256 = 1e18;\n\n  /// @dev The maximum value of leverage ratio.\n  uint256 internal constant MAX_LEVERAGE_RATIO = 100e18;\n\n  /***********\n   * Structs *\n   ***********/\n\n  struct SwapState {\n    // Current supply of base token\n    uint256 baseSupply;\n    // Current nav of base token\n    uint256 baseNav;\n    // Current nav of base token\n    uint256 baseTwapNav;\n    // Current supply of fractional token\n    uint256 fSupply;\n    // Current supply of leveraged token\n    uint256 xSupply;\n    // Current nav of leveraged token\n    uint256 xNav;\n  }\n\n  /// @notice Compute the amount of base token needed to reach the new collateral ratio.\n  ///\n  /// @dev If the current collateral ratio <= new collateral ratio, we should return 0.\n  ///\n  /// @param state The current state.\n  /// @param _newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return _maxBaseIn The amount of base token needed.\n  /// @return _maxFTokenMintable The amount of fToken can be minted.\n  function maxMintableFToken(SwapState memory state, uint256 _newCollateralRatio)\n    internal\n    pure\n    returns (uint256 _maxBaseIn, uint256 _maxFTokenMintable)\n  {\n    //  n * v = nf * vf + nx * vx\n    //  (n + dn) * v = (nf + df) * vf + nx * vx\n    //  (n + dn) * v / ((nf + df) * vf) = ncr\n    // =>\n    //  n * v - ncr * nf * vf = (ncr - 1) * dn * v\n    //  n * v - ncr * nf * vf = (ncr - 1) * df * vf\n    // =>\n    //  dn = (n * v - ncr * nf * vf) / ((ncr - 1) * v)\n    //  df = (n * v - ncr * nf * vf) / ((ncr - 1) * vf)\n\n    uint256 _baseVal = state.baseSupply * (state.baseNav) * (PRECISION);\n    uint256 _fVal = _newCollateralRatio * (state.fSupply) * (PRECISION);\n\n    if (_baseVal > _fVal) {\n      _newCollateralRatio = _newCollateralRatio - (PRECISION);\n      uint256 _delta = _baseVal - _fVal;\n\n      _maxBaseIn = _delta / (state.baseNav * (_newCollateralRatio));\n      _maxFTokenMintable = _delta / (PRECISION * (_newCollateralRatio));\n    }\n  }\n\n  /// @notice Compute the amount of base token needed to reach the new collateral ratio.\n  ///\n  /// @dev If the current collateral ratio >= new collateral ratio, we should return 0.\n  ///\n  /// @param state The current state.\n  /// @param _newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return _maxBaseIn The amount of base token needed.\n  /// @return _maxXTokenMintable The amount of xToken can be minted.\n  function maxMintableXToken(SwapState memory state, uint256 _newCollateralRatio)\n    internal\n    pure\n    returns (uint256 _maxBaseIn, uint256 _maxXTokenMintable)\n  {\n    //  n * v = nf * vf + nx * vx\n    //  (n + dn) * v = nf * vf + (nx + dx) * vx\n    //  (n + dn) * v / (nf * vf) = ncr\n    // =>\n    //  n * v + dn * v = ncr * nf * vf\n    //  n * v + dx * vx = ncr * nf * vf\n    // =>\n    //  dn = (ncr * nf * vf - n * v) / v\n    //  dx = (ncr * nf * vf - n * v) / vx\n\n    uint256 _baseVal = state.baseNav * (state.baseSupply) * (PRECISION);\n    uint256 _fVal = _newCollateralRatio * (state.fSupply) * (PRECISION);\n\n    if (_fVal > _baseVal) {\n      uint256 _delta = _fVal - _baseVal;\n\n      _maxBaseIn = _delta / (state.baseNav * (PRECISION));\n      _maxXTokenMintable = _delta / (state.xNav * (PRECISION));\n    }\n  }\n\n  /// @notice Compute the amount of fToken needed to reach the new collateral ratio.\n  ///\n  /// @dev If the current collateral ratio >= new collateral ratio, we should return 0.\n  ///\n  /// @param state The current state.\n  /// @param _newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return _maxBaseOut The amount of base token redeemed.\n  /// @return _maxFTokenRedeemable The amount of fToken needed.\n  function maxRedeemableFToken(SwapState memory state, uint256 _newCollateralRatio)\n    internal\n    pure\n    returns (uint256 _maxBaseOut, uint256 _maxFTokenRedeemable)\n  {\n    //  n * v = nf * vf + nx * vx\n    //  (n - dn) * v = (nf - df) * vf + nx * vx\n    //  (n - dn) * v / ((nf - df) * vf) = ncr\n    // =>\n    //  n * v - dn * v = ncr * nf * vf - ncr * dn * v\n    //  n * v - df * vf = ncr * nf * vf - ncr * df * vf\n    // =>\n    //  df = (ncr * nf * vf - n * v) / ((ncr - 1) * vf)\n    //  dn = (ncr * nf * vf - n * v) / ((ncr - 1) * v)\n\n    uint256 _baseVal = state.baseSupply * (state.baseNav) * (PRECISION);\n    uint256 _fVal = _newCollateralRatio * (state.fSupply) * (PRECISION);\n\n    if (_fVal > _baseVal) {\n      uint256 _delta = _fVal - _baseVal;\n      _newCollateralRatio = _newCollateralRatio - (PRECISION);\n\n      _maxFTokenRedeemable = _delta / (_newCollateralRatio * (PRECISION));\n      _maxBaseOut = _delta / (_newCollateralRatio * (state.baseNav));\n    }\n  }\n\n  /// @notice Compute the amount of xToken needed to reach the new collateral ratio.\n  ///\n  /// @dev If the current collateral ratio <= new collateral ratio, we should return 0.\n  ///\n  /// @param state The current state.\n  /// @param _newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return _maxBaseOut The amount of base token redeemed.\n  /// @return _maxXTokenRedeemable The amount of xToken needed.\n  function maxRedeemableXToken(SwapState memory state, uint256 _newCollateralRatio)\n    internal\n    pure\n    returns (uint256 _maxBaseOut, uint256 _maxXTokenRedeemable)\n  {\n    //  n * v = nf * vf + nx * vx\n    //  (n - dn) * v = nf * vf + (nx - dx) * vx\n    //  (n - dn) * v / (nf * vf) = ncr\n    // =>\n    //  n * v - dn * v = ncr * nf * vf\n    //  n * v - dx * vx = ncr * nf * vf\n    // =>\n    //  dn = (n * v - ncr * nf * vf) / v\n    //  dx = (n * v - ncr * nf * vf) / vx\n\n    uint256 _baseVal = state.baseSupply * (state.baseNav) * (PRECISION);\n    uint256 _fVal = _newCollateralRatio * (state.fSupply) * (PRECISION);\n\n    if (_baseVal > _fVal) {\n      uint256 _delta = _baseVal - _fVal;\n\n      _maxXTokenRedeemable = _delta / (state.xNav * (PRECISION));\n      _maxBaseOut = _delta / (state.baseNav * (PRECISION));\n    }\n  }\n\n  /// @notice Mint fToken.\n  /// @param state The current state.\n  /// @param _baseIn The amount of base token supplied.\n  /// @return _fTokenOut The amount of fToken expected.\n  function mintFToken(SwapState memory state, uint256 _baseIn) internal pure returns (uint256 _fTokenOut) {\n    //  n * v = nf * vf + nx * vx\n    //  (n + dn) * v = (nf + df) * vf + nx * vx\n    // =>\n    //  df = dn * v / vf\n    _fTokenOut = (_baseIn * state.baseNav) / PRECISION;\n  }\n\n  /// @notice Mint xToken.\n  /// @param state The current state.\n  /// @param _baseIn The amount of base token supplied.\n  /// @return _xTokenOut The amount of xToken expected.\n  function mintXToken(SwapState memory state, uint256 _baseIn) internal pure returns (uint256 _xTokenOut) {\n    //  n * v = nf * vf + nx * vx\n    //  (n + dn) * v = nf * vf + (nx + dx) * vx\n    // =>\n    //  dx = (dn * v * nx) / (n * v - nf * vf)\n    _xTokenOut = _baseIn * state.baseNav * state.xSupply;\n    _xTokenOut = _xTokenOut / (state.baseSupply * state.baseNav - state.fSupply * PRECISION);\n  }\n\n  /// @notice Redeem base token with fToken and xToken.\n  /// @param state The current state.\n  /// @param _fTokenIn The amount of fToken supplied.\n  /// @param _xTokenIn The amount of xToken supplied.\n  /// @return _baseOut The amount of base token expected.\n  function redeem(\n    SwapState memory state,\n    uint256 _fTokenIn,\n    uint256 _xTokenIn\n  ) internal pure returns (uint256 _baseOut) {\n    uint256 _xVal = state.baseSupply * state.baseNav - state.fSupply * PRECISION;\n\n    //  n * v = nf * vf + nx * vx\n    //  (n - dn) * v = (nf - df) * vf + (nx - dx) * vx\n    // =>\n    //  dn = (df * vf + dx * (n * v - nf * vf) / nx) / v\n\n    if (state.xSupply == 0) {\n      _baseOut = (_fTokenIn * PRECISION) / state.baseNav;\n    } else {\n      _baseOut = _fTokenIn * PRECISION;\n      _baseOut += (_xTokenIn * _xVal) / state.xSupply;\n      _baseOut /= state.baseNav;\n    }\n  }\n\n  /// @notice Compute current leverage ratio for xToken.\n  ///\n  /// @dev We use `baseTwapNav` to compute leverage ratio to avoid manipulation.\n  ///\n  /// @param state The current state.\n  /// @return ratio The current leverage ratio.\n  function leverageRatio(SwapState memory state) internal pure returns (uint256 ratio) {\n    // ratio = (1 - rho * beta * (1 + r)) / (1 - rho), and beta = 0\n    // ratio = 1 / (1 - rho)\n    uint256 rho = (state.fSupply * PRECISION * PRECISION) / (state.baseSupply * state.baseTwapNav);\n    if (rho >= PRECISION) {\n      // under collateral, assume infinite leverage\n      ratio = MAX_LEVERAGE_RATIO;\n    } else {\n      ratio = (PRECISION * PRECISION) / (PRECISION - rho);\n      if (ratio > MAX_LEVERAGE_RATIO) ratio = MAX_LEVERAGE_RATIO;\n    }\n  }\n}\n"
      },
      "contracts/f(x)/v2/TreasuryV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.20;\n\nimport { AccessControlUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/access/AccessControlUpgradeable.sol\";\nimport { IERC20MetadataUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/extensions/IERC20MetadataUpgradeable.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 { WordCodec } from \"../../common/codec/WordCodec.sol\";\nimport { ExponentialMovingAverageV8 } from \"../../common/math/ExponentialMovingAverageV8.sol\";\n\nimport { IAssetStrategy } from \"../../interfaces/f(x)/IAssetStrategy.sol\";\nimport { IFxFractionalTokenV2 } from \"../../interfaces/f(x)/IFxFractionalTokenV2.sol\";\nimport { IFxLeveragedTokenV2 } from \"../../interfaces/f(x)/IFxLeveragedTokenV2.sol\";\nimport { IFxMarketV2 } from \"../../interfaces/f(x)/IFxMarketV2.sol\";\nimport { IFxPriceOracleV2 } from \"../../interfaces/f(x)/IFxPriceOracleV2.sol\";\nimport { IFxRateProvider } from \"../../interfaces/f(x)/IFxRateProvider.sol\";\nimport { IFxRebalancePoolSplitter } from \"../../interfaces/f(x)/IFxRebalancePoolSplitter.sol\";\nimport { IFxTreasuryV2 } from \"../../interfaces/f(x)/IFxTreasuryV2.sol\";\n\nimport { FxStableMath } from \"../math/FxStableMath.sol\";\n\n// solhint-disable no-empty-blocks\n// solhint-disable not-rely-on-time\n\nabstract contract TreasuryV2 is AccessControlUpgradeable, IFxTreasuryV2 {\n  using SafeERC20Upgradeable for IERC20Upgradeable;\n\n  using ExponentialMovingAverageV8 for ExponentialMovingAverageV8.EMAStorage;\n  using FxStableMath for FxStableMath.SwapState;\n  using WordCodec for bytes32;\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @inheritdoc IFxTreasuryV2\n  address public immutable override baseToken;\n\n  /// @inheritdoc IFxTreasuryV2\n  address public immutable override fToken;\n\n  /// @inheritdoc IFxTreasuryV2\n  address public immutable override xToken;\n\n  /// @dev The scale to make sure base token amount are with precision 1e18.\n  uint256 private immutable baseTokenScale;\n\n  /// @notice The role for f(x) market contract.\n  bytes32 public constant FX_MARKET_ROLE = keccak256(\"FX_MARKET_ROLE\");\n\n  /// @notice The role for f(x) settle whitelist.\n  bytes32 public constant SETTLE_WHITELIST_ROLE = keccak256(\"SETTLE_WHITELIST_ROLE\");\n\n  /// @notice The role for f(x) settle whitelist.\n  bytes32 public constant PROTOCOL_INITIALIZER_ROLE = keccak256(\"PROTOCOL_INITIALIZER_ROLE\");\n\n  /// @dev The precision used to compute fees.\n  uint256 internal constant FEE_PRECISION = 1e9;\n\n  /// @dev The precision used to compute nav.\n  uint256 internal constant PRECISION = 1e18;\n\n  /// @dev The precision used to compute nav.\n  int256 private constant PRECISION_I256 = 1e18;\n\n  /// @dev The offset of expense ratio in `_miscData`.\n  uint256 private constant REBALANCE_POOL_RATIO_OFFSET = 0;\n\n  /// @dev The offset of harvester ratio in `_miscData`.\n  uint256 private constant HARVESTER_RATIO_OFFSET = 30;\n\n  /// @dev The maximum expense ratio.\n  uint256 private constant MAX_REBALANCE_POOL_RATIO = 1e9; // 100%\n\n  /// @dev The maximum harvester ratio.\n  uint256 private constant MAX_HARVESTER_RATIO = 1e8; // 10%\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @notice The address of price oracle contract.\n  address public priceOracle;\n\n  /// @inheritdoc IFxTreasuryV2\n  uint256 public override referenceBaseTokenPrice;\n\n  /// @inheritdoc IFxTreasuryV2\n  uint256 public override totalBaseToken;\n\n  /// @notice The maximum amount of base token can be deposited.\n  uint256 public baseTokenCap;\n\n  /// @inheritdoc IFxTreasuryV2\n  address public override strategy;\n\n  /// @inheritdoc IFxTreasuryV2\n  uint256 public override strategyUnderlying;\n\n  /// @notice The ema storage of the leverage ratio.\n  ExponentialMovingAverageV8.EMAStorage public emaLeverageRatio;\n\n  /// @notice The address platform contract.\n  address public platform;\n\n  /// @notice The address of RebalancePoolSplitter contract.\n  address public rebalancePoolSplitter;\n\n  /// @dev `_miscData` is a storage slot that can be used to store unrelated pieces of information.\n  /// All pools store the *expense ratio* and *harvester ratio*, but the `miscData`can be extended\n  /// to store more pieces of information.\n  ///\n  /// The *expense ratio* is stored in the first most significant 32 bits, and the *harvester ratio* is\n  /// stored in the next most significant 32 bits leaving the remaining 196 bits free to store any\n  /// other information derived pools might need.\n  ///\n  /// - The *expense ratio* and *harvester ratio* are charged each time when harvester harvest the pool revenue.\n  ///\n  /// [ expense ratio | harvester ratio | available ]\n  /// [    30 bits    |     30 bits     |  196 bits ]\n  /// [ MSB                                     LSB ]\n  bytes32 internal _miscData;\n\n  /// @dev Slots for future use.\n  uint256[40] private _gap;\n\n  /************\n   * Modifier *\n   ************/\n\n  modifier onlyStrategy() {\n    require(msg.sender == strategy, \"Only strategy\");\n    _;\n  }\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(\n    address _baseToken,\n    address _fToken,\n    address _xToken\n  ) {\n    baseToken = _baseToken;\n    fToken = _fToken;\n    xToken = _xToken;\n    baseTokenScale = 10**(18 - IERC20MetadataUpgradeable(_baseToken).decimals());\n  }\n\n  function __TreasuryV2_init(\n    address _platform,\n    address _rebalancePoolSplitter,\n    address _priceOracle,\n    uint256 _baseTokenCap,\n    uint24 sampleInterval\n  ) internal onlyInitializing {\n    _updatePlatform(_platform);\n    _updateRebalancePoolSplitter(_rebalancePoolSplitter);\n    _updatePriceOracle(_priceOracle);\n    _updateBaseTokenCap(_baseTokenCap);\n    _updateEMASampleInterval(sampleInterval);\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc IFxTreasuryV2\n  function getRebalancePoolRatio() public view override returns (uint256) {\n    return _miscData.decodeUint(REBALANCE_POOL_RATIO_OFFSET, 30);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function getHarvesterRatio() public view override returns (uint256) {\n    return _miscData.decodeUint(HARVESTER_RATIO_OFFSET, 30);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function collateralRatio() public view override returns (uint256) {\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.None);\n\n    if (_state.baseSupply == 0) return PRECISION;\n    if (_state.fSupply == 0) return PRECISION * PRECISION;\n\n    return (_state.baseSupply * _state.baseNav) / _state.fSupply;\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function isUnderCollateral() public view returns (bool) {\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.None);\n    return _state.xNav == 0;\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  /// @dev If the current collateral ratio <= new collateral ratio, we should return 0.\n  function maxMintableFToken(uint256 _newCollateralRatio)\n    external\n    view\n    override\n    returns (uint256 _maxBaseIn, uint256 _maxFTokenMintable)\n  {\n    if (_newCollateralRatio <= PRECISION) revert ErrorCollateralRatioTooSmall();\n\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.MintFToken);\n    (_maxBaseIn, _maxFTokenMintable) = _state.maxMintableFToken(_newCollateralRatio);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  /// @dev If the current collateral ratio >= new collateral ratio, we should return 0.\n  function maxMintableXToken(uint256 _newCollateralRatio)\n    external\n    view\n    override\n    returns (uint256 _maxBaseIn, uint256 _maxXTokenMintable)\n  {\n    if (_newCollateralRatio <= PRECISION) revert ErrorCollateralRatioTooSmall();\n\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.MintXToken);\n    (_maxBaseIn, _maxXTokenMintable) = _state.maxMintableXToken(_newCollateralRatio);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  /// @dev If the current collateral ratio >= new collateral ratio, we should return 0.\n  function maxRedeemableFToken(uint256 _newCollateralRatio)\n    external\n    view\n    override\n    returns (uint256 _maxBaseOut, uint256 _maxFTokenRedeemable)\n  {\n    if (_newCollateralRatio <= PRECISION) revert ErrorCollateralRatioTooSmall();\n\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.RedeemFToken);\n    (_maxBaseOut, _maxFTokenRedeemable) = _state.maxRedeemableFToken(_newCollateralRatio);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  /// @dev If the current collateral ratio <= new collateral ratio, we should return 0.\n  function maxRedeemableXToken(uint256 _newCollateralRatio)\n    external\n    view\n    override\n    returns (uint256 _maxBaseOut, uint256 _maxXTokenRedeemable)\n  {\n    if (_newCollateralRatio <= PRECISION) revert ErrorCollateralRatioTooSmall();\n\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.RedeemXToken);\n    (_maxBaseOut, _maxXTokenRedeemable) = _state.maxRedeemableXToken(_newCollateralRatio);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  /// @dev This function is used to calculate the nav of fToken and xToken.\n  /// To avoid, price manipulation, we return the twap.\n  function currentBaseTokenPrice() external view override returns (uint256) {\n    (uint256 price, ) = _fetchBaseTokenPrice(Action.None);\n    return price;\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function isBaseTokenPriceValid() public view returns (bool _isValid) {\n    (_isValid, , , ) = IFxPriceOracleV2(priceOracle).getPrice();\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function leverageRatio() external view override returns (uint256) {\n    return emaLeverageRatio.emaValue();\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function getWrapppedValue(uint256 amount) public view virtual returns (uint256) {\n    return amount / baseTokenScale;\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function getUnderlyingValue(uint256 amount) public view virtual returns (uint256) {\n    return amount * baseTokenScale;\n  }\n\n  /// @notice Return then amount of base token can be harvested.\n  function harvestable() public view virtual returns (uint256) {\n    uint256 balance = IERC20Upgradeable(baseToken).balanceOf(address(this));\n    uint256 managed = getWrapppedValue(totalBaseToken);\n    if (balance < managed) return 0;\n    else return balance - managed;\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IFxTreasuryV2\n  function mintFToken(uint256 _baseIn, address _recipient)\n    external\n    override\n    onlyRole(FX_MARKET_ROLE)\n    returns (uint256 _fTokenOut)\n  {\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.MintFToken);\n    if (_state.xNav == 0) revert ErrorUnderCollateral();\n    if (_state.baseSupply + _baseIn > baseTokenCap) revert ErrorExceedTotalCap();\n\n    _updateEMALeverageRatio(_state);\n\n    _fTokenOut = _state.mintFToken(_baseIn);\n    totalBaseToken = _state.baseSupply + _baseIn;\n\n    IFxFractionalTokenV2(fToken).mint(_recipient, _fTokenOut);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function mintXToken(uint256 _baseIn, address _recipient)\n    external\n    override\n    onlyRole(FX_MARKET_ROLE)\n    returns (uint256 _xTokenOut)\n  {\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.MintXToken);\n    if (_state.xNav == 0) revert ErrorUnderCollateral();\n    if (_state.baseSupply + _baseIn > baseTokenCap) revert ErrorExceedTotalCap();\n\n    _updateEMALeverageRatio(_state);\n\n    _xTokenOut = _state.mintXToken(_baseIn);\n    totalBaseToken = _state.baseSupply + _baseIn;\n\n    IFxLeveragedTokenV2(xToken).mint(_recipient, _xTokenOut);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function redeem(\n    uint256 _fTokenIn,\n    uint256 _xTokenIn,\n    address _owner\n  ) external override onlyRole(FX_MARKET_ROLE) returns (uint256 _baseOut) {\n    FxStableMath.SwapState memory _state;\n\n    if (_fTokenIn > 0) {\n      _state = _loadSwapState(Action.RedeemFToken);\n    } else {\n      _state = _loadSwapState(Action.RedeemXToken);\n    }\n    _updateEMALeverageRatio(_state);\n\n    if (_state.xNav == 0) {\n      if (_xTokenIn > 0) revert ErrorUnderCollateral();\n      // only redeem fToken proportionally when under collateral.\n      _baseOut = (_fTokenIn * _state.baseSupply) / _state.fSupply;\n    } else {\n      _baseOut = _state.redeem(_fTokenIn, _xTokenIn);\n    }\n\n    if (_fTokenIn > 0) {\n      IFxFractionalTokenV2(fToken).burn(_owner, _fTokenIn);\n    }\n\n    if (_xTokenIn > 0) {\n      IFxLeveragedTokenV2(xToken).burn(_owner, _xTokenIn);\n    }\n\n    totalBaseToken = _state.baseSupply - _baseOut;\n\n    _transferBaseToken(_baseOut, msg.sender);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function settle() external override onlyRole(SETTLE_WHITELIST_ROLE) {\n    if (totalBaseToken == 0) return;\n\n    uint256 _oldPrice = referenceBaseTokenPrice;\n    (uint256 _newPrice, ) = _fetchBaseTokenPrice(Action.None);\n    referenceBaseTokenPrice = _newPrice;\n\n    emit Settle(_oldPrice, _newPrice);\n\n    // update leverage ratio at the end\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.None);\n    _updateEMALeverageRatio(_state);\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  function transferToStrategy(uint256 _amount) external override onlyStrategy {\n    IERC20Upgradeable(baseToken).safeTransfer(strategy, _amount);\n    strategyUnderlying += _amount;\n  }\n\n  /// @inheritdoc IFxTreasuryV2\n  /// @dev For future use.\n  function notifyStrategyProfit(uint256 _amount) external override onlyStrategy {}\n\n  /// @notice Harvest pending rewards to stability pool.\n  function harvest() external virtual {\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.None);\n    _updateEMALeverageRatio(_state);\n\n    _distributedHarvestedRewards(harvestable());\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @inheritdoc IFxTreasuryV2\n  function initializeProtocol(uint256 _baseIn)\n    external\n    virtual\n    onlyRole(PROTOCOL_INITIALIZER_ROLE)\n    returns (uint256, uint256)\n  {\n    return _initializeProtocol(_baseIn);\n  }\n\n  /// @notice Change address of strategy contract.\n  /// @param _strategy The new address of strategy contract.\n  function updateStrategy(address _strategy) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    _updateStrategy(_strategy);\n  }\n\n  /// @notice Change address of price oracle contract.\n  /// @param _priceOracle The new address of price oracle contract.\n  function updatePriceOracle(address _priceOracle) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    _updatePriceOracle(_priceOracle);\n  }\n\n  /// @notice Update the base token cap.\n  /// @param _baseTokenCap The new base token cap.\n  function updateBaseTokenCap(uint256 _baseTokenCap) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    _updateBaseTokenCap(_baseTokenCap);\n  }\n\n  /// @notice Update the EMA sample interval.\n  /// @param _sampleInterval The new EMA sample interval.\n  function updateEMASampleInterval(uint24 _sampleInterval) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    FxStableMath.SwapState memory _state = _loadSwapState(Action.None);\n    _updateEMALeverageRatio(_state);\n\n    _updateEMASampleInterval(_sampleInterval);\n  }\n\n  /// @notice Change address of platform contract.\n  /// @param _platform The new address of platform contract.\n  function updatePlatform(address _platform) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    _updatePlatform(_platform);\n  }\n\n  /// @notice Change address of RebalancePoolSplitter contract.\n  /// @param _splitter The new address of RebalancePoolSplitter contract.\n  function updateRebalancePoolSplitter(address _splitter) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    _updateRebalancePoolSplitter(_splitter);\n  }\n\n  /// @notice Update the fee ratio distributed to treasury.\n  /// @param _newRatio The new ratio to update, multiplied by 1e9.\n  function updateRebalancePoolRatio(uint32 _newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    if (uint256(_newRatio) > MAX_REBALANCE_POOL_RATIO) {\n      revert ErrorRebalancePoolRatioTooLarge();\n    }\n\n    bytes32 _data = _miscData;\n    uint256 _oldRatio = _miscData.decodeUint(REBALANCE_POOL_RATIO_OFFSET, 30);\n    _miscData = _data.insertUint(_newRatio, REBALANCE_POOL_RATIO_OFFSET, 30);\n\n    emit UpdateRebalancePoolRatio(_oldRatio, _newRatio);\n  }\n\n  /// @notice Update the fee ratio distributed to harvester.\n  /// @param _newRatio The new ratio to update, multiplied by 1e9.\n  function updateHarvesterRatio(uint32 _newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    if (uint256(_newRatio) > MAX_HARVESTER_RATIO) {\n      revert ErrorHarvesterRatioTooLarge();\n    }\n\n    bytes32 _data = _miscData;\n    uint256 _oldRatio = _miscData.decodeUint(HARVESTER_RATIO_OFFSET, 30);\n    _miscData = _data.insertUint(_newRatio, HARVESTER_RATIO_OFFSET, 30);\n\n    emit UpdateHarvesterRatio(_oldRatio, _newRatio);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  function _distributedHarvestedRewards(uint256 _totalRewards) internal {\n    uint256 _harvestBounty = (getHarvesterRatio() * _totalRewards) / FEE_PRECISION;\n    uint256 _rebalancePoolRewards = (getRebalancePoolRatio() * _totalRewards) / FEE_PRECISION;\n\n    emit Harvest(msg.sender, _totalRewards, _rebalancePoolRewards, _harvestBounty);\n\n    if (_harvestBounty > 0) {\n      IERC20Upgradeable(baseToken).safeTransfer(_msgSender(), _harvestBounty);\n      unchecked {\n        _totalRewards = _totalRewards - _harvestBounty;\n      }\n    }\n\n    if (_rebalancePoolRewards > 0) {\n      _distributeRebalancePoolRewards(baseToken, _rebalancePoolRewards);\n      unchecked {\n        _totalRewards = _totalRewards - _rebalancePoolRewards;\n      }\n    }\n\n    if (_totalRewards > 0) {\n      IERC20Upgradeable(baseToken).safeTransfer(platform, _totalRewards);\n    }\n  }\n\n  /// @dev Internal function to initialize protocol.\n  /// @param _baseIn The amount of underlying value of the base token used to initialize.\n  /// @return fTokenOut The amount of fToken minted.\n  /// @return xTokenOut The amount of xToken minted.\n  function _initializeProtocol(uint256 _baseIn) internal returns (uint256 fTokenOut, uint256 xTokenOut) {\n    if (referenceBaseTokenPrice > 0) revert ErrorProtocolInitialized();\n    if (getUnderlyingValue(IERC20Upgradeable(baseToken).balanceOf(address(this))) < _baseIn) {\n      revert ErrorInsufficientInitialBaseToken();\n    }\n\n    // initialize reference price\n    address _sender = _msgSender();\n    (uint256 _price, ) = _fetchBaseTokenPrice(Action.None);\n    referenceBaseTokenPrice = _price;\n    emit Settle(0, _price);\n\n    // mint fToken and xToken\n    totalBaseToken = _baseIn;\n    fTokenOut = (_baseIn * _price) / (2 * PRECISION);\n    xTokenOut = fTokenOut;\n    IFxFractionalTokenV2(fToken).mint(_sender, fTokenOut);\n    IFxLeveragedTokenV2(xToken).mint(_sender, xTokenOut);\n\n    // initialize EMA leverage\n    ExponentialMovingAverageV8.EMAStorage memory cachedEmaLeverageRatio = emaLeverageRatio;\n    cachedEmaLeverageRatio.lastTime = uint40(block.timestamp);\n    cachedEmaLeverageRatio.lastValue = uint96(PRECISION * 2);\n    cachedEmaLeverageRatio.lastEmaValue = uint96(PRECISION * 2);\n    emaLeverageRatio = cachedEmaLeverageRatio;\n  }\n\n  /// @dev Internal function to change the address of strategy contract.\n  /// @param _newStrategy The new address of strategy contract.\n  function _updateStrategy(address _newStrategy) internal {\n    address _oldStrategy = strategy;\n    strategy = _newStrategy;\n\n    emit UpdateStrategy(_oldStrategy, _newStrategy);\n  }\n\n  /// @dev Internal function to change the address of price oracle contract.\n  /// @param _newPriceOracle The new address of price oracle contract.\n  function _updatePriceOracle(address _newPriceOracle) internal {\n    if (_newPriceOracle == address(0)) revert ErrorZeroAddress();\n\n    address _oldPriceOracle = priceOracle;\n    priceOracle = _newPriceOracle;\n\n    emit UpdatePriceOracle(_oldPriceOracle, _newPriceOracle);\n  }\n\n  /// @dev Internal function to update the base token cap.\n  /// @param _newBaseTokenCap The new base token cap.\n  function _updateBaseTokenCap(uint256 _newBaseTokenCap) internal {\n    uint256 _oldBaseTokenCap = baseTokenCap;\n    baseTokenCap = _newBaseTokenCap;\n\n    emit UpdateBaseTokenCap(_oldBaseTokenCap, _newBaseTokenCap);\n  }\n\n  /// @dev Internal function to update the EMA sample interval.\n  /// @param _newSampleInterval The new EMA sample interval.\n  function _updateEMASampleInterval(uint24 _newSampleInterval) internal {\n    if (_newSampleInterval < 1 minutes) revert ErrorEMASampleIntervalTooSmall();\n\n    uint256 _oldSampleInterval = emaLeverageRatio.sampleInterval;\n    emaLeverageRatio.sampleInterval = _newSampleInterval;\n\n    emit UpdateEMASampleInterval(_oldSampleInterval, _newSampleInterval);\n  }\n\n  /// @dev Internal function to change the address of platform contract.\n  /// @param _newPlatform The new address of platform contract.\n  function _updatePlatform(address _newPlatform) internal {\n    if (_newPlatform == address(0)) revert ErrorZeroAddress();\n\n    address _oldPlatform = platform;\n    platform = _newPlatform;\n\n    emit UpdatePlatform(_oldPlatform, _newPlatform);\n  }\n\n  /// @dev Internal function to change the address of RebalancePoolSplitter contract.\n  /// @param _newRebalancePoolSplitter The new address of RebalancePoolSplitter contract.\n  function _updateRebalancePoolSplitter(address _newRebalancePoolSplitter) internal {\n    if (_newRebalancePoolSplitter == address(0)) revert ErrorZeroAddress();\n    address _oldRebalancePoolSplitter = rebalancePoolSplitter;\n    rebalancePoolSplitter = _newRebalancePoolSplitter;\n\n    emit UpdateRebalancePoolSplitter(_oldRebalancePoolSplitter, _newRebalancePoolSplitter);\n  }\n\n  /// @dev Internal function to transfer base token to receiver.\n  /// @param _amount The amount of base token to transfer.\n  /// @param _recipient The address of receiver.\n  function _transferBaseToken(uint256 _amount, address _recipient) internal returns (uint256) {\n    _amount = getWrapppedValue(_amount);\n\n    uint256 _balance = IERC20Upgradeable(baseToken).balanceOf(address(this));\n    if (_balance < _amount) {\n      uint256 _diff = _amount - _balance;\n      IAssetStrategy(strategy).withdrawToTreasury(_diff);\n      strategyUnderlying = strategyUnderlying - _diff;\n\n      // consider possible slippage here.\n      _balance = IERC20Upgradeable(baseToken).balanceOf(address(this));\n      if (_amount > _balance) {\n        _amount = _balance;\n      }\n    }\n\n    IERC20Upgradeable(baseToken).safeTransfer(_recipient, _amount);\n\n    return _amount;\n  }\n\n  /// @dev Internal function to load swap variable to memory\n  function _loadSwapState(Action _action) internal view virtual returns (FxStableMath.SwapState memory _state) {\n    _state.baseSupply = totalBaseToken;\n    (_state.baseTwapNav, _state.baseNav) = _fetchBaseTokenPrice(_action);\n\n    if (_state.baseSupply == 0) {\n      _state.xNav = PRECISION;\n    } else {\n      _state.fSupply = IERC20Upgradeable(fToken).totalSupply();\n      _state.xSupply = IERC20Upgradeable(xToken).totalSupply();\n      if (_state.xSupply == 0) {\n        // no xToken, treat the nav of xToken as 1.0\n        _state.xNav = PRECISION;\n      } else {\n        uint256 _baseVal = _state.baseSupply * _state.baseNav;\n        uint256 _fVal = _state.fSupply * PRECISION;\n        if (_baseVal >= _fVal) {\n          _state.xNav = (_baseVal - _fVal) / _state.xSupply;\n        } else {\n          // under collateral\n          _state.xNav = 0;\n        }\n      }\n    }\n  }\n\n  /// @dev Internal function to update ema leverage ratio.\n  function _updateEMALeverageRatio(FxStableMath.SwapState memory _state) internal {\n    uint256 _ratio = _state.leverageRatio();\n\n    ExponentialMovingAverageV8.EMAStorage memory cachedEmaLeverageRatio = emaLeverageRatio;\n    // The value is capped with 100*10^18, it is safe to cast.\n    cachedEmaLeverageRatio.saveValue(uint96(_ratio));\n    emaLeverageRatio = cachedEmaLeverageRatio;\n  }\n\n  /// @dev Internal function to fetch twap price.\n  /// @return _twap The twap price of the base token.\n  function _fetchBaseTokenPrice(Action _action) internal view returns (uint256 _twap, uint256 _price) {\n    uint256 _minPrice;\n    uint256 _maxPrice;\n    (, _twap, _minPrice, _maxPrice) = IFxPriceOracleV2(priceOracle).getPrice();\n\n    if (_action == Action.MintFToken || _action == Action.RedeemXToken) _price = _minPrice;\n    else if (_action == Action.MintXToken || _action == Action.RedeemFToken) _price = _maxPrice;\n    else _price = _maxPrice;\n\n    if (_twap == 0) revert ErrorInvalidTwapPrice();\n  }\n\n  /// @dev Internal function to distribute rewards to rebalance pool.\n  /// @param _token The address of token to distribute.\n  /// @param _amount The amount of token to distribute.\n  function _distributeRebalancePoolRewards(address _token, uint256 _amount) internal virtual {\n    address _splitter = rebalancePoolSplitter;\n\n    IERC20Upgradeable(_token).safeTransfer(_splitter, _amount);\n    IFxRebalancePoolSplitter(_splitter).split(_token);\n  }\n}\n"
      },
      "contracts/interfaces/curve/ICrvUSDAmm.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ICrvUSDAmm {\n  function get_rate_mul() external view returns (uint256);\n}\n"
      },
      "contracts/interfaces/f(x)/IAssetStrategy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface IAssetStrategy {\n  /// @notice Withdraw assets from strategy to treasury.\n  /// @param amount The amount of token to withdraw.\n  function withdrawToTreasury(uint256 amount) external;\n}\n"
      },
      "contracts/interfaces/f(x)/IFxFractionalTokenV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxFractionalTokenV2 {\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when caller is not treasury contract.\n  error ErrorCallerIsNotTreasury();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the net asset value for the token, multipled by 1e18.\n  function nav() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint some token to someone.\n  /// @param to The address of recipient.\n  /// @param amount The amount of token to mint.\n  function mint(address to, uint256 amount) external;\n\n  /// @notice Burn some token from someone.\n  /// @param from The address of owner to burn.\n  /// @param amount The amount of token to burn.\n  function burn(address from, uint256 amount) external;\n}\n"
      },
      "contracts/interfaces/f(x)/IFxLeveragedTokenV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxLeveragedTokenV2 {\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when caller is not treasury contract.\n  error ErrorCallerIsNotTreasury();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the net asset value for the token.\n  function nav() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint some token to someone.\n  /// @param to The address of recipient.\n  /// @param amount The amount of token to mint.\n  function mint(address to, uint256 amount) external;\n\n  /// @notice Burn some token from someone.\n  /// @param from The address of owner to burn.\n  /// @param amount The amount of token to burn.\n  function burn(address from, uint256 amount) external;\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)/IFxPriceOracleV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface IFxPriceOracleV2 {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the value of maximum price deviation is updated.\n  /// @param oldValue The value of the previous maximum price deviation.\n  /// @param newValue The value of the current maximum price deviation.\n  event UpdateMaxPriceDeviation(uint256 oldValue, uint256 newValue);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the oracle price with 18 decimal places.\n  /// @return isValid Whether the oracle price is valid -- the difference between `minPrice` and `maxPrice` is reasonable.\n  /// @return twap The time-weighted average price, multiplied by 1e18. It should be the anchor price for this asset, which is hard to manipulate.\n  /// @return minPrice The minimum oracle price among all available price sources (including twap), multiplied by 1e18.\n  /// @return maxPrice The maximum oracle price among all available price sources (including twap), multiplied by 1e18.\n  function getPrice()\n    external\n    view\n    returns (\n      bool isValid,\n      uint256 twap,\n      uint256 minPrice,\n      uint256 maxPrice\n    );\n}\n"
      },
      "contracts/interfaces/f(x)/IFxRateProvider.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface IFxRateProvider {\n  /// @notice Return the exchange rate from wrapped token to underlying rate,\n  /// multiplied by 1e18.\n  function getRate() external view returns (uint256);\n}\n"
      },
      "contracts/interfaces/f(x)/IFxRebalancePoolSplitter.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface IFxRebalancePoolSplitter {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the address of splitter is updated.\n  /// @param token The address of the token.\n  /// @param oldSplitter The address of previous token splitter.\n  /// @param newSplitter The address of current token splitter.\n  event UpdateSplitter(address indexed token, address indexed oldSplitter, address indexed newSplitter);\n\n  /// @notice Emitted when a new receiver is added.\n  /// @param token The address of the token.\n  /// @param receiver The address of the receiver.\n  event RegisterReceiver(address indexed token, address indexed receiver);\n\n  /// @notice Emitted when an exsited receiver is removed.\n  /// @param token The address of the token.\n  /// @param receiver The address of the receiver.\n  event DeregisterReceiver(address indexed token, address indexed receiver);\n\n  /// @notice Emitted when the split ratio is updated.\n  /// @param token The address of the token.\n  /// @param ratios The list of new split ratios.\n  event UpdateSplitRatios(address indexed token, uint256[] ratios);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the splitter of the given token.\n  /// @param token The address of token to query.\n  function splitter(address token) external view returns (address);\n\n  /// @notice Return the receivers and split ratios for the given token.\n  /// @param token The address of token to query.\n  /// @return receivers The address list of receivers.\n  /// @return ratios The list of corresponding split ratio.\n  function getReceivers(address token) external view returns (address[] memory receivers, uint256[] memory ratios);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Split token to different RebalancePool.\n  /// @param token The address of token to split.\n  function split(address token) 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"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "evmVersion": "shanghai",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}