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/security/ReentrancyGuardUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n\n    /**\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/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/SafeCastUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCastUpgradeable {\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     *\n     * _Available since v3.0._\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\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"
      },
      "@openzeppelin/contracts-upgradeable-v4/utils/structs/EnumerableSetUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSetUpgradeable {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "contracts/common/math/DecrementalFloatingPoint.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n// solhint-disable no-inline-assembly\n\n/// @title DecrementalFloatingPoint\n///\n/// @dev The real number is `magnitude * 10^{-18 - 9 * exponent}`, where `magnitude` is in range `(0, 10^18]`.\n/// And the floating point is encoded as:\n///\n/// [  epoch  | exponent | magnitude ]\n/// [ 24 bits | 24  bits |  64 bits  ]\n/// [ MSB                        LSB ]\n///\n/// Hopefully, the `epoch` and `exponent` won't exceed `type(uint24).max`.\nlibrary DecrementalFloatingPoint {\n  /// @dev The precision of the `magnitude` in the floating point.\n  uint64 internal constant PRECISION = 1e18;\n\n  /// @dev The half precision of the `magnitude` in the floating point.\n  uint64 internal constant HALF_PRECISION = 1e9;\n\n  /// @dev Encode `_epoch`, `_exponent` and `_magnitude` to the floating point.\n  function encode(\n    uint24 _epoch,\n    uint24 _exponent,\n    uint64 _magnitude\n  ) internal pure returns (uint112 prod) {\n    assembly {\n      prod := add(_magnitude, add(shl(64, _exponent), shl(88, _epoch)))\n    }\n  }\n\n  /// @dev Return the epoch of the floating point.\n  /// @param prod The current encoded floating point.\n  function epoch(uint112 prod) internal pure returns (uint24 _epoch) {\n    assembly {\n      _epoch := shr(88, prod)\n    }\n  }\n\n  /// @dev Return the exponent of the floating point.\n  /// @param prod The current encoded floating point.\n  function exponent(uint112 prod) internal pure returns (uint24 _exponent) {\n    assembly {\n      _exponent := and(shr(64, prod), 0xffffff)\n    }\n  }\n\n  /// @dev Return the epoch and exponent of the floating point.\n  /// @param prod The current encoded floating point.\n  function epochAndExponent(uint112 prod) internal pure returns (uint48 _epochExponent) {\n    assembly {\n      _epochExponent := shr(64, prod)\n    }\n  }\n\n  /// @dev Return the magnitude of the floating point.\n  /// @param prod The current encoded floating point.\n  function magnitude(uint112 prod) internal pure returns (uint64 _magnitude) {\n    assembly {\n      _magnitude := and(prod, 0xffffffffffffffff)\n    }\n  }\n\n  /// @dev Multiply the floating point by a scalar no more than 1.0.\n  ///\n  /// Caller should make sure `scale` is always smaller than or equals to 1.0\n  ///\n  /// @param prod The current encoded floating point.\n  /// @param scale The multiplier applied to the product, multiplied by 1e18.\n  function mul(uint112 prod, uint64 scale) internal pure returns (uint112) {\n    uint24 _epoch = epoch(prod);\n    uint24 _exponent = exponent(prod);\n    uint256 _magnitude = magnitude(prod);\n\n    unchecked {\n      if (scale == 0) {\n        _epoch += 1;\n        _exponent = 0;\n        _magnitude = PRECISION;\n      } else if ((uint256(scale) * _magnitude) / PRECISION < HALF_PRECISION) {\n        _exponent += 1;\n        _magnitude = (_magnitude * uint256(scale)) / HALF_PRECISION;\n      } else {\n        _magnitude = (_magnitude * uint256(scale)) / PRECISION;\n      }\n    }\n\n    // it is safe to direct convert `_magnitude` to uint64.\n    return encode(_epoch, _exponent, uint64(_magnitude));\n  }\n}\n"
      },
      "contracts/common/rewards/accumulator/IMultipleRewardAccumulator.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IMultipleRewardAccumulator {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when user claim pending rewards.\n  /// @param account The address of user.\n  /// @param token The address of token claimed.\n  /// @param receiver The address of token receiver.\n  /// @param amount The amount of token claimed.\n  event Claim(address indexed account, address indexed token, address indexed receiver, uint256 amount);\n\n  /// @notice Emitted when the reward receiver is updated.\n  /// @param account The address of the account.\n  /// @param oldReceiver The address of the previous reward receiver.\n  /// @param newReceiver The address of the current reward receiver.\n  event UpdateRewardReceiver(address indexed account, address indexed oldReceiver, address indexed newReceiver);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when caller claim others reward to another user.\n  error ClaimOthersRewardToAnother();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of default reward receiver for given user.\n  /// @param account The address of user to query.\n  function rewardReceiver(address account) external view returns (address);\n\n  /// @notice Get the amount of pending rewards.\n  /// @param account The address of user to query.\n  /// @param token The address of reward token to query.\n  /// @return amount The amount of pending rewards.\n  function claimable(address account, address token) external view returns (uint256 amount);\n\n  /// @notice Get the total amount of rewards claimed from this contract.\n  /// @param account The address of user to query.\n  /// @param token The address of reward token to query.\n  /// @return amount The amount of claimed rewards.\n  function claimed(address account, address token) external view returns (uint256 amount);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Set the default reward receiver for the caller.\n  /// @dev When set to address(0), rewards are sent to the caller.\n  /// @param _newReceiver The new receiver address for any rewards claimed via `claim`.\n  function setRewardReceiver(address _newReceiver) external;\n\n  /// @notice Update the global and user snapshot.\n  /// @param account The address of user to update.\n  function checkpoint(address account) external;\n\n  /// @notice Claim pending rewards of all active tokens for the caller.\n  function claim() external;\n\n  /// @notice Claim pending rewards of all active tokens for some user.\n  /// @param account The address of the user.\n  function claim(address account) external;\n\n  /// @notice Claim pending rewards of all active tokens for the user and transfer to others.\n  /// @param account The address of the user.\n  /// @param receiver The address of the recipient.\n  function claim(address account, address receiver) external;\n\n  /// @notice Claim pending rewards of historical reward tokens for the caller.\n  /// @param tokens The address list of historical reward tokens to claim.\n  function claimHistorical(address[] memory tokens) external;\n\n  /// @notice Claim pending rewards of historical reward tokens for some user.\n  /// @param account The address of the user.\n  /// @param tokens The address list of historical reward tokens to claim.\n  function claimHistorical(address account, address[] memory tokens) external;\n}\n"
      },
      "contracts/common/rewards/accumulator/MultipleRewardCompoundingAccumulator.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/security/ReentrancyGuardUpgradeable.sol\";\n\nimport { IMultipleRewardAccumulator } from \"./IMultipleRewardAccumulator.sol\";\n\nimport { DecrementalFloatingPoint } from \"../../math/DecrementalFloatingPoint.sol\";\nimport { LinearMultipleRewardDistributor } from \"../distributor/LinearMultipleRewardDistributor.sol\";\n\n// solhint-disable not-rely-on-time\n\n/// @title MultipleRewardCompoundingAccumulator\n/// @notice `MultipleRewardCompoundingAccumulator` is a reward accumulator for reward distribution in a staking pool.\n/// In the staking pool, the total stakes will decrease unexpectedly and the user stakes will also decrease proportionally.\n/// The contract will distribute rewards in proportion to a staker’s share of total stakes with only O(1) complexity.\n///\n/// Assume that there are n events e[1], e[2], ..., and e[n]. The types of events are user stake,\n/// user unstake, total stakes decrease and reward distribution.\n/// Right after event e[i], let the total pool stakes be s[i], the user pool stakes be u[i],\n/// the total stake decrease is d[i], and the rewards distributed be r[i].\n///\n/// The basic assumptions are, if\n///   + e[i] is user stake, r[i] = 0, u[i] > u[i-1] and s[i] - s[i-1] = u[i] - u[i-1].\n///   + e[i] is user unstake, r[i] = 0, u[i] < u[i-1] and s[i] - s[i-1] = u[i] - u[i-1].\n///   + e[i] is total stakes decrease, r[i] = 0, d[i] > 0, s[i] = s[i-1] - d[i] and u[i] = u[i-1] * (1 - d[i] / s[i-1])\n///   + e[i] is reward distribution, r[i] > 0, u[i] = u[i-1] and s[i] = s[i-1].\n///\n/// So under the assumptions, if\n///  + e[i] is user stake/unstake, we can maintain the value of u[i] and s[i] easily.\n///  + e[i] is total stakes decrease, we can only maintain the value of s[i] easily.\n///\n/// To compute the value of u[i], assuming the only events are total stakes decrease. Then after n events,\n///   u[n] = u[0] * (1 - d[1]/s[0]) * (1 - d[2]/s[1]) * ... * (1 - d[n]/s[n-1])\n///\n/// To compute the user stakes correctly, we can maintain the value of\n///   p[n] = (1 - d[1]/s[0]) * (1 - d[2]/s[1]) * ... * (1 - d[n]/s[n-1])\n///\n/// Then the user stakes from event x to event y is u[y] = u[x] * p[y] / p[x]\n///\n/// As for the accumutated rewards, the total amount of rewards for the user is:\n///                 u[0]          u[1]                u[n-1]\n///   g[n] = r[1] * ---- + r[2] * ---- + ... + r[n] * ------\n///                 s[0]          s[1]                s[n-1]\n///\n/// Also, u[n] = u[0] * p[n], we have\n///                         p[0]          p[1]                p[n-1]\n///   g[n] = u[0] * (r[1] * ---- + r[2] * ---- + ... + r[n] * ------)\n///                         s[0]          s[1]                s[n-1]\n///\n/// And, the rewards from event x to event y (both inclusive) for the user is:\n///                            p[x-1]            p[x]                p[y-1]\n///   g[x->y] = u[x] * (r[x] * ------ + r[x+1] * ---- + ... + r[y] * ------)\n///                            s[x-1]            s[x]                s[y-1]\n///\n/// To check the accumulated total user rewards, we can maintain the value of\n///                p[0]          p[1]                p[n-1]\n///   acc = r[1] * ---- + r[2] * ---- + ... + r[n] * ------\n///                s[0]          s[1]                s[n-1]\n///\n/// For each event, if\n///   + e[i] is user stake or unstake, new accumulated rewards is\n///      gain += u[i-1] * (acc - last_user_acc) / last_user_prod,\n///      and update `last_user_acc` to `acc`\n///      and update `last_user_prod` to p[i].\n///   + e[i] is total stakes decrease, p[i] *= (1 - d[i] / s[i-1])\n///   + e[i] is reward distribution, acc += r[i] * p[i-1] / s[i-1].\n///\n/// Notice that total stakes decrease event will possible make s[i] be zero. We introduce epoch to handle this problem.\n/// When the total supply reduces to zero, we start a new epoch.\n///\n/// Another problem is precision loss in solidity, the p[i] will eventually become a very small nonzero value. To solve\n/// the problem, we treat p[i] as m[i] * 10^{-18 - 9 * e[i]}, where m[i] is the magnitude and e[i] is the exponent.\n/// When the value of m[i] is smaller than 10^9, we will multiply m[i] by 1e9 and then increase e[i] by one.\n///\n/// @dev The method comes from liquity's StabilityPool, the paper is in\n/// https://github.com/liquity/dev/blob/main/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf\nabstract contract MultipleRewardCompoundingAccumulator is\n  ReentrancyGuardUpgradeable,\n  LinearMultipleRewardDistributor,\n  IMultipleRewardAccumulator\n{\n  using SafeERC20Upgradeable for IERC20Upgradeable;\n  using DecrementalFloatingPoint for uint112;\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The precision used to calculate accumulated rewards.\n  uint256 internal constant REWARD_PRECISION = 1e18;\n\n  /// @dev Compiler will pack this into single `uint256`.\n  struct RewardSnapshot {\n    // The timestamp when the snapshot is updated.\n    uint64 timestamp;\n    // The reward integral until now.\n    uint192 integral;\n  }\n\n  /// @dev Compiler will pack this into single `uint256`.\n  struct ClaimData {\n    // The number of pending rewards.\n    uint128 pending;\n    // The number of claimed rewards.\n    uint128 claimed;\n  }\n\n  /// @dev Compiler will pack this into two `uint256`.\n  struct UserRewardSnapshot {\n    // The claim data for the user.\n    ClaimData rewards;\n    // The reward snapshot for user.\n    RewardSnapshot checkpoint;\n  }\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  mapping(address => address) public override rewardReceiver;\n\n  /// @notice Mapping from reward token address to global reward snapshot.\n  ///\n  /// - The inner mapping records the `acc` at different `(epoch, exponent)`\n  /// - The outer mapping records the ((epoch, exponent) => acc) mappings, for different tokens.\n  ///\n  /// @dev The integral is defined as 1e18 * ∫(rate(t) * prod(t) / totalPoolShare(t) dt).\n  mapping(address => mapping(uint256 => RewardSnapshot)) public epochToExponentToRewardSnapshot;\n\n  /// @notice Mapping from user address to reward token address to user reward snapshot.\n  ///\n  /// @dev The integral is the value of `rewardSnapshot[token].integral` when the snapshot is taken.\n  mapping(address => mapping(address => UserRewardSnapshot)) public userRewardSnapshot;\n\n  /// @dev reserved slots.\n  uint256[47] private __gap;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  // solhint-disable-next-line func-name-mixedcase\n  function __MultipleRewardCompoundingAccumulator_init() internal onlyInitializing {\n    __LinearMultipleRewardDistributor_init();\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claimable(address _account, address _token) public view virtual override returns (uint256) {\n    return _claimable(_account, _token);\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claimed(address _account, address _token) external view returns (uint256) {\n    return userRewardSnapshot[_account][_token].rewards.claimed;\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function setRewardReceiver(address _newReceiver) external {\n    address _caller = _msgSender();\n    address _oldReceiver = rewardReceiver[_caller];\n    rewardReceiver[_caller] = _newReceiver;\n\n    emit UpdateRewardReceiver(_caller, _oldReceiver, _newReceiver);\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function checkpoint(address _account) external virtual override nonReentrant {\n    _checkpoint(_account);\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claim() external override {\n    address _sender = _msgSender();\n    claim(_sender, address(0));\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claim(address _account) external override {\n    claim(_account, address(0));\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claim(address _account, address _receiver) public override nonReentrant {\n    if (_account != _msgSender() && _receiver != address(0)) {\n      revert ClaimOthersRewardToAnother();\n    }\n\n    _checkpoint(_account);\n    _claim(_account, _receiver);\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claimHistorical(address[] memory _tokens) external nonReentrant {\n    address _sender = _msgSender();\n    _checkpoint(_sender);\n\n    address _receiver = rewardReceiver[_sender];\n    if (_receiver == address(0)) _receiver = _sender;\n\n    for (uint256 i = 0; i < _tokens.length; i++) {\n      _claimSingle(_sender, _tokens[i], _receiver);\n    }\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claimHistorical(address _account, address[] memory _tokens) external nonReentrant {\n    _checkpoint(_account);\n\n    address _receiver = rewardReceiver[_account];\n    if (_receiver == address(0)) _receiver = _account;\n\n    for (uint256 i = 0; i < _tokens.length; i++) {\n      _claimSingle(_account, _tokens[i], _receiver);\n    }\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  function _claimable(address _account, address _token) internal view virtual returns (uint256) {\n    UserRewardSnapshot memory _userSnapshot = userRewardSnapshot[_account][_token];\n    (uint112 previousProd, uint256 shares) = _getUserPoolShare(_account);\n    if (shares == 0) return _userSnapshot.rewards.pending;\n\n    uint256 epochExponent = previousProd.epochAndExponent();\n    uint256 magnitude = previousProd.magnitude();\n\n    // Grab the sum 'S' from the epoch at which the stake was made. The gain may span up to one scale change.\n    // If it does, the second portion of the gain is scaled by 1e9.\n    // If the gain spans no scale change, the second portion will be 0.\n    uint256 firstPortion = epochToExponentToRewardSnapshot[_token][epochExponent].integral -\n      _userSnapshot.checkpoint.integral;\n    uint256 secondPortion = epochToExponentToRewardSnapshot[_token][epochExponent + 1].integral /\n      uint256(DecrementalFloatingPoint.HALF_PRECISION);\n\n    return\n      uint256(_userSnapshot.rewards.pending) +\n      (shares * (firstPortion + secondPortion)) /\n      (magnitude * REWARD_PRECISION);\n  }\n\n  /// @dev Internal function to update the global and user snapshot.\n  ///\n  /// @param _account The address of user to update. Use zero address\n  ///        if you only want to update global snapshot.\n  function _checkpoint(address _account) internal virtual {\n    _distributePendingReward();\n\n    if (_account != address(0)) {\n      // checkpoint active reward tokens\n      address[] memory _rewardTokens = getActiveRewardTokens();\n      for (uint256 i = 0; i < _rewardTokens.length; i++) {\n        _updateSnapshot(_account, _rewardTokens[i]);\n      }\n\n      // checkpoint historical reward tokens\n      _rewardTokens = getHistoricalRewardTokens();\n      for (uint256 i = 0; i < _rewardTokens.length; i++) {\n        _updateSnapshot(_account, _rewardTokens[i]);\n      }\n    }\n  }\n\n  /// @notice Internal function to update snapshot for single token.\n  /// @param _account The address of user to update.\n  /// @param _token The address of token to update.\n  function _updateSnapshot(address _account, address _token) internal virtual {\n    UserRewardSnapshot memory _snapshot = userRewardSnapshot[_account][_token];\n    (uint112 currentProd, ) = _getTotalPoolShare();\n    uint48 epochExponent = currentProd.epochAndExponent();\n\n    _snapshot.rewards.pending = uint128(_claimable(_account, _token));\n    _snapshot.checkpoint = epochToExponentToRewardSnapshot[_token][epochExponent];\n    _snapshot.checkpoint.timestamp = uint64(block.timestamp);\n    userRewardSnapshot[_account][_token] = _snapshot;\n  }\n\n  /// @dev Internal function to claim active reward tokens.\n  ///\n  /// @param _account The address of user to claim.\n  /// @param _receiver The address of recipient of the reward token.\n  function _claim(address _account, address _receiver) internal virtual {\n    address _receiverStored = rewardReceiver[_account];\n    if (_receiverStored != address(0) && _receiver == address(0)) {\n      _receiver = _receiverStored;\n    }\n    if (_receiver == address(0)) _receiver = _account;\n\n    address[] memory _activeRewardTokens = getActiveRewardTokens();\n    for (uint256 i = 0; i < _activeRewardTokens.length; i++) {\n      _claimSingle(_account, _activeRewardTokens[i], _receiver);\n    }\n  }\n\n  /// @dev Internal function to claim single reward token.\n  /// Caller should make sure `_checkpoint` is called before this function.\n  ///\n  /// @param _account The address of user to claim.\n  /// @param _token The address of reward token.\n  /// @param _receiver The address of recipient of the reward token.\n  function _claimSingle(\n    address _account,\n    address _token,\n    address _receiver\n  ) internal virtual returns (uint256) {\n    ClaimData memory _rewards = userRewardSnapshot[_account][_token].rewards;\n    uint256 _amount = _rewards.pending;\n    if (_amount > 0) {\n      _rewards.claimed += _rewards.pending;\n      _rewards.pending = 0;\n      userRewardSnapshot[_account][_token].rewards = _rewards;\n\n      IERC20Upgradeable(_token).safeTransfer(_receiver, _amount);\n\n      emit Claim(_account, _token, _receiver, _amount);\n    }\n    return _amount;\n  }\n\n  /// @inheritdoc LinearMultipleRewardDistributor\n  function _accumulateReward(address _token, uint256 _amount) internal virtual override {\n    if (_amount == 0) return;\n\n    (uint112 currentProd, uint256 totalShare) = _getTotalPoolShare();\n    if (totalShare == 0) {\n      // no deposits, queue rewards\n      rewardData[_token].queued += uint96(_amount);\n      return;\n    }\n\n    uint48 epochExponent = currentProd.epochAndExponent();\n    uint256 magnitude = currentProd.magnitude();\n\n    RewardSnapshot memory _snapshot = epochToExponentToRewardSnapshot[_token][epochExponent];\n    _snapshot.timestamp = uint64(block.timestamp);\n    // @note usually `_amount <= 10^6 * 10^18` and `magnitude <= 10^18`,\n    // so the value of `_amount * REWARD_PRECISION` won't exceed type(uint192).max.\n    // For the other parts, we rely on the overflow check provided by solc 0.8.\n    _snapshot.integral += (uint192((_amount * REWARD_PRECISION) / totalShare) * uint192(magnitude));\n    epochToExponentToRewardSnapshot[_token][epochExponent] = _snapshot;\n  }\n\n  /// @dev Internal function to get the total pool shares.\n  function _getTotalPoolShare() internal view virtual returns (uint112 currentProd, uint256 totalShare);\n\n  /// @dev Internal function to get the amount of user shares.\n  ///\n  /// @param _account The address of user to query.\n  function _getUserPoolShare(address _account) internal view virtual returns (uint112 previousProd, uint256 share);\n}\n"
      },
      "contracts/common/rewards/distributor/IMultipleRewardDistributor.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IMultipleRewardDistributor {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when new reward token is registered.\n  ///\n  /// @param token The address of reward token.\n  /// @param distributor The address of reward distributor.\n  event RegisterRewardToken(address indexed token, address indexed distributor);\n\n  /// @notice Emitted when the reward distributor is updated.\n  ///\n  /// @param token The address of reward token.\n  /// @param oldDistributor The address of previous reward distributor.\n  /// @param newDistributor The address of current reward distributor.\n  event UpdateRewardDistributor(address indexed token, address indexed oldDistributor, address indexed newDistributor);\n\n  /// @notice Emitted when a reward token is unregistered.\n  ///\n  /// @param token The address of reward token.\n  event UnregisterRewardToken(address indexed token);\n\n  /// @notice Emitted when a reward token is deposited.\n  ///\n  /// @param token The address of reward token.\n  /// @param amount The amount of reward token deposited.\n  event DepositReward(address indexed token, uint256 amount);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when caller access an unactive reward token.\n  error NotActiveRewardToken();\n\n  /// @dev Thrown when the address of reward distributor is `address(0)`.\n  error RewardDistributorIsZero();\n\n  /// @dev Thrown when caller is not reward distributor.\n  error NotRewardDistributor();\n\n  /// @dev Thrown when caller try to register an existing reward token.\n  error DuplicatedRewardToken();\n\n  /// @dev Thrown when caller try to unregister a reward with pending rewards.\n  error RewardDistributionNotFinished();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the address of reward distributor.\n  ///\n  /// @param token The address of reward token.\n  function distributors(address token) external view returns (address);\n\n  /// @notice Return the list of active reward tokens.\n  function getActiveRewardTokens() external view returns (address[] memory);\n\n  /// @notice Return the list of historical reward tokens.\n  function getHistoricalRewardTokens() external view returns (address[] memory);\n\n  /// @notice Return the amount of pending distributed rewards in current period.\n  ///\n  /// @param token The address of reward token.\n  /// @return distributable The amount of reward token can be distributed in current period.\n  /// @return undistributed The amount of reward token still locked in current period.\n  function pendingRewards(address token) external view returns (uint256 distributable, uint256 undistributed);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Deposit new rewards to this contract.\n  ///\n  /// @param token The address of reward token.\n  /// @param amount The amount of new rewards.\n  function depositReward(address token, uint256 amount) external;\n}\n"
      },
      "contracts/common/rewards/distributor/LinearMultipleRewardDistributor.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { AccessControlUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/access/AccessControlUpgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { EnumerableSetUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/utils/structs/EnumerableSetUpgradeable.sol\";\n\nimport { IMultipleRewardDistributor } from \"./IMultipleRewardDistributor.sol\";\nimport { LinearReward } from \"./LinearReward.sol\";\n\n// solhint-disable no-empty-blocks\n// solhint-disable not-rely-on-time\n\nabstract contract LinearMultipleRewardDistributor is AccessControlUpgradeable, IMultipleRewardDistributor {\n  using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n  using SafeERC20Upgradeable for IERC20Upgradeable;\n\n  using LinearReward for LinearReward.RewardData;\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @notice The role used to manage rewards.\n  bytes32 public constant REWARD_MANAGER_ROLE = keccak256(\"REWARD_MANAGER_ROLE\");\n\n  /// @notice The length of reward period in seconds.\n  /// @dev If the value is zero, the reward will be distributed immediately.\n  /// @dev It is either zero or at least 1 day (which is 86400).\n  uint40 public immutable periodLength;\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @inheritdoc IMultipleRewardDistributor\n  mapping(address => address) public override distributors;\n\n  /// @notice Mapping from reward token address to linear distribution reward data.\n  mapping(address => LinearReward.RewardData) public rewardData;\n\n  /// @dev The list of active reward tokens.\n  EnumerableSetUpgradeable.AddressSet internal activeRewardTokens;\n\n  /// @dev The list of historical reward tokens.\n  EnumerableSetUpgradeable.AddressSet private historicalRewardTokens;\n\n  /// @dev reserved slots.\n  uint256[46] private __gap;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(uint40 _periodLength) {\n    require(_periodLength == 0 || (_periodLength >= 1 days && _periodLength <= 28 days), \"invalid period length\");\n\n    periodLength = _periodLength;\n  }\n\n  // solhint-disable-next-line func-name-mixedcase\n  function __LinearMultipleRewardDistributor_init() internal onlyInitializing {}\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc IMultipleRewardDistributor\n  function getActiveRewardTokens() public view override returns (address[] memory _rewardTokens) {\n    uint256 _length = activeRewardTokens.length();\n    _rewardTokens = new address[](_length);\n\n    for (uint256 i = 0; i < _length; i++) {\n      _rewardTokens[i] = activeRewardTokens.at(i);\n    }\n  }\n\n  /// @inheritdoc IMultipleRewardDistributor\n  function getHistoricalRewardTokens() public view override returns (address[] memory _rewardTokens) {\n    uint256 _length = historicalRewardTokens.length();\n    _rewardTokens = new address[](_length);\n\n    for (uint256 i = 0; i < _length; i++) {\n      _rewardTokens[i] = historicalRewardTokens.at(i);\n    }\n  }\n\n  /// @inheritdoc IMultipleRewardDistributor\n  function pendingRewards(address _token) external view override returns (uint256, uint256) {\n    return rewardData[_token].pending();\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IMultipleRewardDistributor\n  function depositReward(address _token, uint256 _amount) external override {\n    address _distributor = _msgSender();\n    if (!activeRewardTokens.contains(_token)) revert NotActiveRewardToken();\n    if (distributors[_token] != _distributor) revert NotRewardDistributor();\n\n    if (_amount > 0) {\n      IERC20Upgradeable(_token).safeTransferFrom(_distributor, address(this), _amount);\n    }\n\n    _distributePendingReward();\n\n    _notifyReward(_token, _amount);\n\n    emit DepositReward(_token, _amount);\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Register a new reward token.\n  /// @dev Make sure no fee on transfer token is added as reward token.\n  ///\n  /// @param _token The address of reward token.\n  /// @param _distributor The address of reward distributor.\n  function registerRewardToken(address _token, address _distributor) external onlyRole(REWARD_MANAGER_ROLE) {\n    if (_distributor == address(0)) revert RewardDistributorIsZero();\n    if (activeRewardTokens.contains(_token)) revert DuplicatedRewardToken();\n\n    activeRewardTokens.add(_token);\n    distributors[_token] = _distributor;\n    historicalRewardTokens.remove(_token);\n\n    emit RegisterRewardToken(_token, _distributor);\n  }\n\n  /// @notice Update the distributor for reward token.\n  ///\n  /// @param _token The address of reward token.\n  /// @param _newDistributor The address of new reward distributor.\n  function updateRewardDistributor(address _token, address _newDistributor) external onlyRole(REWARD_MANAGER_ROLE) {\n    if (_newDistributor == address(0)) revert RewardDistributorIsZero();\n    if (!activeRewardTokens.contains(_token)) revert NotActiveRewardToken();\n\n    address _oldDistributor = distributors[_token];\n    distributors[_token] = _newDistributor;\n\n    emit UpdateRewardDistributor(_token, _oldDistributor, _newDistributor);\n  }\n\n  /// @notice Unregister an existing reward token.\n  ///\n  /// @param _token The address of reward token.\n  function unregisterRewardToken(address _token) external onlyRole(REWARD_MANAGER_ROLE) {\n    if (!activeRewardTokens.contains(_token)) revert NotActiveRewardToken();\n\n    LinearReward.RewardData memory _data = rewardData[_token];\n    unchecked {\n      (uint256 _distributable, uint256 _undistributed) = _data.pending();\n      if (_data.queued < periodLength) _data.queued = 0; // ignore round error\n      if (_data.queued + _distributable + _undistributed > 0) revert RewardDistributionNotFinished();\n    }\n\n    activeRewardTokens.remove(_token);\n    distributors[_token] = address(0);\n    historicalRewardTokens.add(_token);\n\n    emit UnregisterRewardToken(_token);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to notify new rewards.\n  ///\n  /// @param _token The address of token.\n  /// @param _amount The amount of new rewards.\n  function _notifyReward(address _token, uint256 _amount) internal {\n    if (periodLength == 0) {\n      _accumulateReward(_token, _amount);\n    } else {\n      LinearReward.RewardData memory _data = rewardData[_token];\n      _data.increase(periodLength, _amount);\n      rewardData[_token] = _data;\n    }\n  }\n\n  /// @dev Internal function to distribute all pending reward tokens.\n  function _distributePendingReward() internal {\n    if (periodLength == 0 || activeRewardTokens.length() == 0) return;\n\n    address[] memory _activeRewardTokens = getActiveRewardTokens();\n    for (uint256 i = 0; i < _activeRewardTokens.length; i++) {\n      address _token = _activeRewardTokens[i];\n      (uint256 _pending, ) = rewardData[_token].pending();\n      rewardData[_token].lastUpdate = uint40(block.timestamp);\n\n      if (_pending > 0) {\n        _accumulateReward(_token, _pending);\n      }\n    }\n  }\n\n  /// @dev Internal function to accumulate distributed rewards.\n  ///\n  /// @param _token The address of token.\n  /// @param _amount The amount of rewards to accumulate.\n  function _accumulateReward(address _token, uint256 _amount) internal virtual;\n}\n"
      },
      "contracts/common/rewards/distributor/LinearReward.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { SafeCastUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/utils/math/SafeCastUpgradeable.sol\";\n\n// solhint-disable not-rely-on-time\n\nlibrary LinearReward {\n  using SafeCastUpgradeable for uint256;\n\n  /// @dev Compiler will pack this into single `uint256`.\n  /// Usually, we assume the amount of rewards won't exceed `uint96.max`.\n  /// In such case, the rate won't exceed `uint80.max`, since `periodLength` is at least `86400`.\n  /// Also `uint40.max` is enough for timestamp, which is about 30000 years.\n  struct RewardData {\n    // The amount of rewards pending to distribute.\n    uint96 queued;\n    // The current reward rate per second.\n    uint80 rate;\n    // The last timestamp when the reward is distributed.\n    uint40 lastUpdate;\n    // The timestamp when this period will finish.\n    uint40 finishAt;\n  }\n\n  /// @dev Add new rewards to current one. It is possible that the rewards will not distribute immediately.\n  /// The rewards will be only distributed when current period is end or the current increase or\n  /// decrease no more than 10%.\n  ///\n  /// @param _data The struct of reward data, will be modified inplace.\n  /// @param _periodLength The length of a period, caller should make sure it is at least `86400`.\n  /// @param _amount The amount of new rewards to distribute.\n  function increase(\n    RewardData memory _data,\n    uint256 _periodLength,\n    uint256 _amount\n  ) internal view {\n    _amount = _amount + _data.queued;\n    _data.queued = 0;\n\n    if (block.timestamp >= _data.finishAt) {\n      // period finished, distribute to next period\n      _data.rate = (_amount / _periodLength).toUint80();\n      _data.queued = uint96(_amount - (_data.rate * _periodLength)); // keep rounding error\n      _data.lastUpdate = uint40(block.timestamp);\n      _data.finishAt = uint40(block.timestamp + _periodLength);\n    } else {\n      uint256 _elapsed = block.timestamp - (_data.finishAt - _periodLength);\n      uint256 _distributed = uint256(_data.rate) * _elapsed;\n      if (_distributed * 9 <= _amount * 10) {\n        // APR increase or drop no more than 10%, distribute\n        _amount = _amount + uint256(_data.rate) * (_data.finishAt - _data.lastUpdate);\n        _data.rate = (_amount / _periodLength).toUint80();\n        _data.queued = uint96(_amount - (_data.rate * _periodLength)); // keep rounding error\n        _data.lastUpdate = uint40(block.timestamp);\n        _data.finishAt = uint40(block.timestamp + _periodLength);\n        _data.lastUpdate = uint40(block.timestamp);\n      } else {\n        // APR drop more than 10%, wait for more rewards\n        _data.queued = _amount.toUint96();\n      }\n    }\n  }\n\n  /// @dev Return the amount of pending distributed rewards in current period.\n  ///\n  /// @param _data The struct of reward data.\n  function pending(RewardData memory _data) internal view returns (uint256, uint256) {\n    uint256 _elapsed;\n    uint256 _left;\n    if (block.timestamp > _data.finishAt) {\n      // finishAt >= lastUpdate will happen, if `_notifyReward` is not called during current period.\n      _elapsed = _data.finishAt >= _data.lastUpdate ? _data.finishAt - _data.lastUpdate : 0;\n    } else {\n      unchecked {\n        _elapsed = block.timestamp - _data.lastUpdate;\n        _left = uint256(_data.finishAt) - block.timestamp;\n      }\n    }\n\n    return (uint256(_data.rate) * _elapsed, uint256(_data.rate) * _left);\n  }\n}\n"
      },
      "contracts/f(x)/rebalance-pool/FxUSDShareableRebalancePool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.20;\n\nimport { IFxBoostableRebalancePool } from \"../../interfaces/f(x)/IFxBoostableRebalancePool.sol\";\n\nimport { ShareableRebalancePoolV2 } from \"./ShareableRebalancePoolV2.sol\";\n\ncontract FxUSDShareableRebalancePool is ShareableRebalancePoolV2 {\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(\n    address _fxn,\n    address _ve,\n    address _veHelper,\n    address _minter\n  ) ShareableRebalancePoolV2(_fxn, _ve, _veHelper, _minter) {}\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function withdraw(uint256 _amount, address _receiver) external override {\n    // not allowed to withdraw as fToken in fxUSD.\n    // _withdraw(_msgSender(), _amount, _receiver);\n  }\n}\n"
      },
      "contracts/f(x)/rebalance-pool/ShareableRebalancePool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.20;\n\nimport { AccessControlUpgradeable } from \"@openzeppelin/contracts-upgradeable-v4/access/AccessControlUpgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport { DecrementalFloatingPoint } from \"../../common/math/DecrementalFloatingPoint.sol\";\nimport { IMultipleRewardAccumulator } from \"../../common/rewards/accumulator/IMultipleRewardAccumulator.sol\";\nimport { MultipleRewardCompoundingAccumulator } from \"../../common/rewards/accumulator/MultipleRewardCompoundingAccumulator.sol\";\nimport { LinearMultipleRewardDistributor } from \"../../common/rewards/distributor/LinearMultipleRewardDistributor.sol\";\n\nimport { IFxBoostableRebalancePool } from \"../../interfaces/f(x)/IFxBoostableRebalancePool.sol\";\nimport { IFxMarket } from \"../../interfaces/f(x)/IFxMarket.sol\";\nimport { IFxShareableRebalancePool } from \"../../interfaces/f(x)/IFxShareableRebalancePool.sol\";\nimport { IFxTokenWrapper } from \"../../interfaces/f(x)/IFxTokenWrapper.sol\";\nimport { IFxTreasury } from \"../../interfaces/f(x)/IFxTreasury.sol\";\nimport { IVotingEscrow } from \"../../interfaces/voting-escrow/IVotingEscrow.sol\";\nimport { IVotingEscrowHelper } from \"../../interfaces/voting-escrow/IVotingEscrowHelper.sol\";\nimport { ICurveTokenMinter } from \"../../interfaces/ICurveTokenMinter.sol\";\n\n// solhint-disable not-rely-on-time\n\n/// @title ShareableRebalancePool\n/// @notice To add boost for FXN, we maintain a time-weighted boost ratio for each user.\n///   boost[u][i] = min(balance[u][i], 0.4 * balance[u][i] + ve[u][i] * totalSupply[i] / veTotal[i] * 0.6)\n///   ratio[u][x -> y] = sum(boost[u][i] / balance[u][i] * (t[i] - t[i - 1])) / (t[y] - t[x])\n///\n///   1. supply[w] is the total amount of token staked at the beginning of week `w`.\n///   2. veSupply[w] is the total ve supply at the beginning of week `w`.\n///   3. ve[u][w] is the ve balance for user `u` at the beginning of week `w`.\n///   4. balance[u][w] is the amount of token staked for user `u` at the beginning of week `w`.\ncontract ShareableRebalancePool is MultipleRewardCompoundingAccumulator, IFxShareableRebalancePool {\n  using SafeERC20Upgradeable for IERC20Upgradeable;\n  using DecrementalFloatingPoint for uint112;\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @notice The role for liquidator.\n  bytes32 public constant LIQUIDATOR_ROLE = keccak256(\"LIQUIDATOR_ROLE\");\n\n  /// @notice The role for ve balance sharing.\n  bytes32 public constant VE_SHARING_ROLE = keccak256(\"VE_SHARING_ROLE\");\n\n  /// @notice The role for ve balance sharing.\n  bytes32 public constant WITHDRAW_FROM_ROLE = keccak256(\"WITHDRAW_FROM_ROLE\");\n\n  /// @dev The precison use to calculation.\n  uint256 private constant PRECISION = 1e18;\n\n  /// @dev The number of seconds in one day.\n  uint256 private constant DAY = 1 days;\n\n  /// @dev The number of seconds in one week.\n  uint256 private constant WEEK = 7 days;\n\n  /// @notice The address of FXN token.\n  address public immutable fxn;\n\n  /// @notice The address of Voting Escrow FXN.\n  address public immutable ve;\n\n  /// @notice The address of VotingEscrowHelper contract.\n  address public immutable veHelper;\n\n  /// @notice The address of FXN token minter.\n  address public immutable minter;\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev The token balance struct. The compiler will pack this into single `uint256`.\n  ///\n  /// @param product The encoding product data, see the comments of `DecrementalFloatingPoint`.\n  /// @param amount The amount of token currently.\n  /// @param updateAt The timestamp in day when the struct is updated.\n  struct TokenBalance {\n    uint112 product;\n    uint104 amount;\n    uint40 updateAt;\n  }\n\n  /// @dev The gauge data struct. The compiler will pack this into single `uint256`.\n  ///\n  /// @param gauge The address of the gauge.\n  /// @param claimAt The timestamp in second when last claim happened.\n  struct Gauge {\n    address gauge;\n    uint64 claimAt;\n  }\n\n  /// @dev The boost checkpoint struct. The compiler will pack this into single `uint256`.\n  /// Each epoch `t` starts at timestamp `t * 86400 * 7` (inclusive) and ends at `(t + 1) * 86400 * 7` (not inclusive).\n  ///\n  /// @param boostRatio The boost ratio of current epoch.\n  /// @param historyIndex The index of supply in totalSupplyHistory at checkpoint.\n  struct BoostCheckpoint {\n    uint64 boostRatio;\n    uint64 historyIndex;\n  }\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  address public treasury;\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  address public market;\n\n  /// @notice The gauge struct.\n  Gauge public gauge;\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  address public override baseToken;\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  address public override asset;\n\n  /// @dev The TokenBalance struct for current total supply.\n  TokenBalance private _totalSupply;\n\n  /// @dev Mapping account address to TokenBalance struct.\n  mapping(address => TokenBalance) private _balances;\n\n  /// @dev It was used as the boostCheckpoint in previous version, now is deprecated.\n  mapping(address => bytes32) private _deprecated_boostCheckpoint;\n\n  /// @notice The number of total supply history.\n  uint256 public numTotalSupplyHistory;\n\n  /// @notice Mapping from index to history totalSupply.\n  ///\n  /// If there are multiple updates at the same timestamp, only the last one will be recorded.\n  mapping(uint256 => TokenBalance) public totalSupplyHistory;\n\n  /// @notice The maximum collateral ratio to call liquidate.\n  uint256 public liquidatableCollateralRatio;\n\n  /// @notice The address of token wrapper for liquidated base token;\n  address public wrapper;\n\n  /// @notice Error trackers for the error correction in the loss calculation.\n  uint256 public lastAssetLossError;\n\n  /// @notice Mapping from account address to index in `totalSupplyHistory`.\n  mapping(address => BoostCheckpoint) public boostCheckpoint;\n\n  /// @notice Mapping from vote owner address to current balance sum of accepted stakers.\n  mapping(address => TokenBalance) public voteOwnerBalances;\n\n  /// @notice Mapping from vote owner address to week timestamp to historical balance sum of accepted stakers.\n  mapping(address => mapping(uint256 => uint256)) public voteOwnerHistoryBalances;\n\n  /// @notice Mapping from owner address to staker address to the vote sharing status.\n  mapping(address => mapping(address => bool)) public isStakerAllowed;\n\n  /// @inheritdoc IFxShareableRebalancePool\n  mapping(address => address) public getStakerVoteOwner;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(\n    address _fxn,\n    address _ve,\n    address _veHelper,\n    address _minter\n  ) LinearMultipleRewardDistributor(1 weeks) {\n    fxn = _fxn;\n    ve = _ve;\n    veHelper = _veHelper;\n    minter = _minter;\n  }\n\n  function initialize(\n    address _treasury,\n    address _market,\n    address _gauge\n  ) external initializer {\n    // __Context_init(); // from ContextUpgradeable, comment out to reduce codesize\n    // __ERC165_init(); // from ERC165Upgradeable, comment out to reduce codesize\n    // __AccessControl_init(); // from AccessControlUpgradeable, comment out to reduce codesize\n    __ReentrancyGuard_init(); // from ReentrancyGuardUpgradeable\n\n    __MultipleRewardCompoundingAccumulator_init(); // from MultipleRewardCompoundingAccumulator\n\n    // access control\n    AccessControlUpgradeable._grantRole(DEFAULT_ADMIN_ROLE, _msgSender());\n    AccessControlUpgradeable._grantRole(REWARD_MANAGER_ROLE, _msgSender());\n\n    treasury = _treasury;\n    market = _market;\n    gauge.gauge = _gauge;\n\n    baseToken = IFxTreasury(_treasury).baseToken();\n    asset = IFxTreasury(_treasury).fToken();\n    wrapper = address(this);\n\n    _totalSupply.product = DecrementalFloatingPoint.encode(0, 0, uint64(PRECISION));\n    _totalSupply.updateAt = uint40(block.timestamp);\n    totalSupplyHistory[0] = _totalSupply;\n    numTotalSupplyHistory = 1;\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function totalSupply() external view returns (uint256) {\n    return _totalSupply.amount;\n  }\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function balanceOf(address _account) public view override returns (uint256) {\n    TokenBalance memory _balance = _balances[_account];\n    return _getCompoundedBalance(_balance.amount, _balance.product, _totalSupply.product);\n  }\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function getBoostRatio(address _account) public view returns (uint256) {\n    return _getBoostRatio(_account);\n  }\n\n  /// @inheritdoc IMultipleRewardAccumulator\n  function claimable(address _account, address _token) public view virtual override returns (uint256) {\n    if (_token == fxn) {\n      uint256 _pending = userRewardSnapshot[_account][_token].rewards.pending;\n      uint256 fullEarned = _claimable(_account, _token) - _pending;\n      uint256 ratio = getBoostRatio(_account);\n      uint256 boostEarned = (fullEarned * ratio) / PRECISION;\n      return _pending + boostEarned;\n    } else {\n      return _claimable(_account, _token);\n    }\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function deposit(uint256 _amount, address _receiver) external override {\n    if (hasRole(VE_SHARING_ROLE, _receiver)) revert ErrorVoteOwnerCannotStake();\n\n    address _sender = _msgSender();\n    // transfer asset token to this contract\n    address _asset = asset;\n    if (_amount == type(uint256).max) {\n      _amount = IERC20Upgradeable(_asset).balanceOf(_sender);\n    }\n    if (_amount == 0) revert DepositZeroAmount();\n    IERC20Upgradeable(_asset).safeTransferFrom(_sender, address(this), _amount);\n\n    // @note after checkpoint, the account balances are correct, we can `_balances` safely.\n    _checkpoint(_receiver);\n\n    // It should never exceed `type(uint104).max`.\n    TokenBalance memory _supply = _totalSupply;\n    TokenBalance memory _balance = _balances[_receiver];\n    TokenBalance memory _ownerBalance;\n    _supply.amount += uint104(_amount);\n    _supply.updateAt = uint40(block.timestamp);\n    _balance.amount += uint104(_amount);\n\n    // @note after checkpoint, the voteOwnerBalances are correct.\n    address _owner = getStakerVoteOwner[_receiver];\n    if (_owner != address(0)) {\n      _ownerBalance = voteOwnerBalances[_owner];\n      _ownerBalance.amount += uint104(_amount);\n    }\n\n    // this is already updated in `_checkpoint(_receiver)`.\n    // _balance.updateAt = uint40(block.timestamp);\n    // _ownerBalance.updateAt = uint40(block.timestamp);\n\n    _recordTotalSupply(_supply);\n    _balances[_receiver] = _balance;\n\n    // update boost checkpoint at last\n    _updateBoostCheckpoint(_receiver, _owner, _balance, _ownerBalance, _supply);\n\n    emit Deposit(_sender, _receiver, _amount);\n    emit UserDepositChange(_receiver, _balance.amount, 0);\n  }\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function withdraw(uint256 _amount, address _receiver) external virtual override {\n    _withdraw(_msgSender(), _amount, _receiver);\n  }\n\n  /// @inheritdoc IFxShareableRebalancePool\n  function withdrawFrom(\n    address _owner,\n    uint256 _amount,\n    address _receiver\n  ) external override onlyRole(WITHDRAW_FROM_ROLE) {\n    _withdraw(_owner, _amount, _receiver);\n  }\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function liquidate(uint256 _maxAmount, uint256 _minBaseOut)\n    external\n    virtual\n    override\n    onlyRole(LIQUIDATOR_ROLE)\n    returns (uint256 _liquidated, uint256 _baseOut)\n  {\n    _checkpoint(address(0));\n\n    IFxTreasury _treasury = IFxTreasury(treasury);\n    if (_treasury.collateralRatio() >= liquidatableCollateralRatio) {\n      revert CannotLiquidate();\n    }\n    (, uint256 _maxLiquidatable) = _treasury.maxRedeemableFToken(liquidatableCollateralRatio);\n\n    uint256 _amount = _maxLiquidatable;\n    if (_amount > _maxAmount) {\n      _amount = _maxAmount;\n    }\n\n    address _asset = asset;\n    address _market = market;\n    address _wrapper = wrapper;\n\n    _liquidated = IERC20Upgradeable(_asset).balanceOf(address(this));\n    if (_amount > _liquidated) {\n      // cannot liquidate more than assets in this contract.\n      _amount = _liquidated;\n    }\n    IERC20Upgradeable(_asset).safeApprove(_market, 0);\n    IERC20Upgradeable(_asset).safeApprove(_market, _amount);\n    (_baseOut, ) = IFxMarket(_market).redeem(_amount, 0, _wrapper, _minBaseOut);\n    _liquidated = _liquidated - IERC20Upgradeable(_asset).balanceOf(address(this));\n\n    emit Liquidate(_liquidated, _baseOut);\n\n    // wrap base token if needed\n    address _token = baseToken;\n    if (_wrapper != address(this)) {\n      _baseOut = IFxTokenWrapper(_wrapper).wrap(_baseOut);\n      _token = IFxTokenWrapper(_wrapper).dst();\n    }\n\n    // distribute liquidated base token\n    _accumulateReward(_token, _baseOut);\n\n    // notify loss\n    _notifyLoss(_liquidated);\n  }\n\n  /// @inheritdoc IFxShareableRebalancePool\n  function toggleVoteSharing(address _staker) external override onlyRole(VE_SHARING_ROLE) {\n    address _owner = _msgSender();\n    if (_staker == _owner) {\n      revert ErrorSelfSharingIsNotAllowed();\n    }\n    if (getStakerVoteOwner[_owner] != address(0)) {\n      revert ErrorCascadedSharingIsNotAllowed();\n    }\n\n    if (isStakerAllowed[_owner][_staker]) {\n      isStakerAllowed[_owner][_staker] = false;\n\n      emit CancelShareVote(_owner, _staker);\n    } else {\n      isStakerAllowed[_owner][_staker] = true;\n\n      emit ShareVote(_owner, _staker);\n    }\n\n    if (getStakerVoteOwner[_staker] == _owner) {\n      _revokeVoteSharing(_owner, _staker);\n    }\n  }\n\n  /// @inheritdoc IFxShareableRebalancePool\n  function acceptSharedVote(address _newOwner) external override {\n    address _staker = _msgSender();\n    if (!isStakerAllowed[_newOwner][_staker]) {\n      revert ErrorVoteShareNotAllowed();\n    }\n\n    address _oldOwner = getStakerVoteOwner[_staker];\n    if (_oldOwner == _newOwner) revert ErrorRepeatAcceptSharedVote();\n    if (_oldOwner != address(0)) {\n      _revokeVoteSharing(_oldOwner, _staker);\n    } else {\n      // @note after checkpoint, the epoch of `_balances[_staker]` and `voteOwnerBalances[_oldOwner]`\n      // are on the latest epoch, we can safely to do add or subtract.\n      _checkpoint(_staker);\n    }\n    getStakerVoteOwner[_staker] = _newOwner;\n\n    // update boost ratio for staker.\n    TokenBalance memory _balance = _balances[_staker];\n    TokenBalance memory _supply = _totalSupply;\n    TokenBalance memory _ownerBalance = _updateVoteOwnerBalance(_newOwner, _supply);\n    _ownerBalance.amount += _balance.amount;\n    _updateBoostCheckpoint(_staker, _newOwner, _balance, _ownerBalance, _supply);\n\n    emit AcceptSharedVote(_staker, address(0), _newOwner);\n  }\n\n  /// @inheritdoc IFxShareableRebalancePool\n  function rejectSharedVote() external override {\n    address _staker = _msgSender();\n    address _owner = getStakerVoteOwner[_staker];\n    if (_owner == address(0)) revert ErrorNoAcceptedSharedVote();\n\n    _revokeVoteSharing(_owner, _staker);\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Update the address of reward wrapper.\n  /// @param _newWrapper The new address of reward wrapper.\n  function updateWrapper(address _newWrapper) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    if (IFxTokenWrapper(_newWrapper).src() != baseToken) {\n      revert ErrorWrapperSrcMismatch();\n    }\n\n    address _oldWrapper = wrapper;\n    if (_oldWrapper != address(this) && IFxTokenWrapper(_oldWrapper).dst() != IFxTokenWrapper(_newWrapper).dst()) {\n      revert ErrorWrapperDstMismatch();\n    }\n\n    wrapper = _newWrapper;\n\n    emit UpdateWrapper(_oldWrapper, _newWrapper);\n  }\n\n  /// @notice Update the collateral ratio line for liquidation.\n  /// @param _newRatio The new liquidatable collateral ratio.\n  function updateLiquidatableCollateralRatio(uint256 _newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    uint256 _oldRatio = liquidatableCollateralRatio;\n    liquidatableCollateralRatio = _newRatio;\n\n    emit UpdateLiquidatableCollateralRatio(_oldRatio, _newRatio);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @inheritdoc AccessControlUpgradeable\n  function _grantRole(bytes32 _role, address _account) internal virtual override {\n    if (_role == VE_SHARING_ROLE && _balances[_account].amount > 0) {\n      revert ErrorVoteOwnerCannotStake();\n    }\n\n    AccessControlUpgradeable._grantRole(_role, _account);\n  }\n\n  /// @inheritdoc MultipleRewardCompoundingAccumulator\n  function _checkpoint(address _account) internal virtual override {\n    // fetch FXN from gauge every 24h\n    if (gauge.gauge != address(0) && block.timestamp > uint256(gauge.claimAt) + DAY) {\n      uint256 _balance = IERC20Upgradeable(fxn).balanceOf(address(this));\n      ICurveTokenMinter(minter).mint(gauge.gauge);\n      uint256 _minted = IERC20Upgradeable(fxn).balanceOf(address(this)) - _balance;\n      gauge.claimAt = uint64(block.timestamp);\n      _notifyReward(fxn, _minted);\n    }\n\n    address _owner = getStakerVoteOwner[_account];\n    if (_account != address(0)) {\n      IVotingEscrowHelper(veHelper).checkpoint(_owner == address(0) ? _account : _owner);\n    }\n    MultipleRewardCompoundingAccumulator._checkpoint(_account);\n\n    if (_account != address(0)) {\n      TokenBalance memory _supply = _totalSupply;\n      TokenBalance memory _balance = _updateUserBalance(_account, _supply);\n      TokenBalance memory _ownerBalance = _updateVoteOwnerBalance(_owner, _supply);\n      _updateBoostCheckpoint(_account, _owner, _balance, _ownerBalance, _supply);\n    }\n  }\n\n  /// @inheritdoc MultipleRewardCompoundingAccumulator\n  function _updateSnapshot(address _account, address _token) internal virtual override {\n    UserRewardSnapshot memory _snapshot = userRewardSnapshot[_account][_token];\n    uint48 epochExponent = _totalSupply.product.epochAndExponent();\n\n    if (_token == fxn) {\n      // update `voteOwnerBalance` here, since it is needed in `_getBoostRatio`\n      _updateVoteOwnerBalance(getStakerVoteOwner[_account], _totalSupply);\n\n      unchecked {\n        uint256 fullEarned = _claimable(_account, _token) - _snapshot.rewards.pending;\n        // save gas when on earned\n        if (fullEarned > 0) {\n          uint256 ratio = _getBoostRatio(_account);\n          uint256 boostEarned = (fullEarned * ratio) / PRECISION;\n          _snapshot.rewards.pending += uint128(boostEarned);\n          if (fullEarned > boostEarned) {\n            // redistribute unboosted rewards.\n            _notifyReward(fxn, fullEarned - boostEarned);\n          }\n        }\n      }\n    } else {\n      _snapshot.rewards.pending = uint128(_claimable(_account, _token));\n    }\n    _snapshot.checkpoint = epochToExponentToRewardSnapshot[_token][epochExponent];\n    _snapshot.checkpoint.timestamp = uint64(block.timestamp);\n    userRewardSnapshot[_account][_token] = _snapshot;\n  }\n\n  /// @inheritdoc MultipleRewardCompoundingAccumulator\n  function _getTotalPoolShare() internal view virtual override returns (uint112 _currentProd, uint256 _totalShare) {\n    TokenBalance memory _supply = _totalSupply;\n    _currentProd = _supply.product;\n    _totalShare = _supply.amount;\n  }\n\n  /// @inheritdoc MultipleRewardCompoundingAccumulator\n  function _getUserPoolShare(address _account)\n    internal\n    view\n    virtual\n    override\n    returns (uint112 _previousProd, uint256 _share)\n  {\n    TokenBalance memory _balance = _balances[_account];\n    _previousProd = _balance.product;\n    _share = _balance.amount;\n  }\n\n  /// @dev Internal function to withdraw assets from this contract.\n  /// @param _sender The address of owner to withdraw from.\n  /// @param _amount The amount of token to withdraw.\n  /// @param _receiver The address of token receiver.\n  function _withdraw(\n    address _sender,\n    uint256 _amount,\n    address _receiver\n  ) internal {\n    // @note after checkpoint, the account balances are correct, we can `_balances` safely.\n    _checkpoint(_sender);\n\n    TokenBalance memory _supply = _totalSupply;\n    TokenBalance memory _balance = _balances[_sender];\n    TokenBalance memory _ownerBalance;\n    if (_amount > _balance.amount) _amount = _balance.amount;\n    if (_amount == 0) revert WithdrawZeroAmount();\n\n    unchecked {\n      _supply.amount -= uint104(_amount);\n      _supply.updateAt = uint40(block.timestamp);\n      _balance.amount -= uint104(_amount);\n    }\n\n    // @note after checkpoint, the voteOwnerBalances are correct.\n    address _owner = getStakerVoteOwner[_sender];\n    if (_owner != address(0)) {\n      _ownerBalance = voteOwnerBalances[_owner];\n      _ownerBalance.amount -= uint104(_amount);\n    }\n\n    // this is already updated in `_checkpoint(_sender)`.\n    // _balance.updateAt = uint40(block.timestamp);\n    // _ownerBalance.updateAt = uint40(block.timestamp);\n\n    _recordTotalSupply(_supply);\n    _balances[_sender] = _balance;\n\n    // update boost checkpoint at last\n    _updateBoostCheckpoint(_sender, _owner, _balance, _ownerBalance, _supply);\n\n    IERC20Upgradeable(asset).safeTransfer(_receiver, _amount);\n\n    emit Withdraw(_sender, _receiver, _amount);\n    emit UserDepositChange(_sender, _balance.amount, 0);\n  }\n\n  /// @dev Internal function to revoke vote sharing.\n  /// @param _owner The address of vote owner.\n  /// @param _staker The address of staker to revoke.\n  function _revokeVoteSharing(address _owner, address _staker) internal {\n    // @note after checkpoint, the epoch of `_balances[_staker]` and `voteOwnerBalances[_oldOwner]`\n    // are on the latest epoch, we can safely to do add or subtract.\n    _checkpoint(_staker);\n    TokenBalance memory _balance = _balances[_staker];\n    TokenBalance memory _ownerBalance = voteOwnerBalances[_owner];\n    // no uncheck here, just in case\n    _ownerBalance.amount -= _balance.amount;\n\n    voteOwnerBalances[_owner] = _ownerBalance;\n    getStakerVoteOwner[_staker] = address(0);\n\n    // @note it is ok to pass a random `_ownerBalance` to this function\n    _updateBoostCheckpoint(_staker, address(0), _balance, _ownerBalance, _totalSupply);\n\n    emit AcceptSharedVote(_staker, _owner, address(0));\n  }\n\n  /// @dev Internal function to update the balance of vote owner.\n  /// @param _owner The address of vote owner.\n  /// @param _supply The latest total supply struct.\n  /// @return _balance The updated token balance for vote owner.\n  function _updateVoteOwnerBalance(address _owner, TokenBalance memory _supply)\n    internal\n    virtual\n    returns (TokenBalance memory _balance)\n  {\n    // update `voteOwnerBalances[_owner]` to latest epoch and record history value\n    if (_owner == address(0)) return _balance;\n    _balance = voteOwnerBalances[_owner];\n    // it happens the owner has no update before\n    if (_balance.updateAt == 0) _balance.updateAt = uint40(block.timestamp);\n\n    uint256 prevWeekTs = _getWeekTs(_balance.updateAt);\n    _balance.amount = uint104(_getCompoundedBalance(_balance.amount, _balance.product, _supply.product));\n    _balance.product = _supply.product;\n    _balance.updateAt = uint40(block.timestamp);\n\n    // @note since it will be updated in `_updateBoostCheckpoint`, we don't need to update it now.\n    // voteOwnerBalances[_owner] = _balance;\n\n    // @note Normally, `prevWeekTs` equals to `nextWeekTs` so we will only sstore 1 time in most of the time.\n    //\n    // When `prevWeekTs < nextWeekTs`, there are some extreme situation that liquidation happens between\n    // `_ownerBalance.updateAt` and `prevWeekTs`, also some time between `prevWeekTs` and `block.timestamp`.\n    // Then we cannot calculate the amount at `prevWeekTs` correctly. Since the situation rarely happens,\n    // it is ok to use `_ownerBalance.amount` only.\n    uint256 nextWeekTs = _getWeekTs(block.timestamp);\n    while (prevWeekTs < nextWeekTs) {\n      voteOwnerHistoryBalances[_owner][prevWeekTs] = _balance.amount;\n      prevWeekTs += WEEK;\n    }\n  }\n\n  /// @dev Internal function to update the balance of user.\n  /// @param _account The address of user to update.\n  /// @param _supply The latest total supply struct.\n  /// @return _balance The updated token balance for the user.\n  function _updateUserBalance(address _account, TokenBalance memory _supply)\n    internal\n    virtual\n    returns (TokenBalance memory _balance)\n  {\n    _balance = _balances[_account];\n    uint104 _newBalance = uint104(_getCompoundedBalance(_balance.amount, _balance.product, _supply.product));\n    if (_newBalance != _balance.amount) {\n      // no unchecked here, just in case\n      emit UserDepositChange(_account, _newBalance, _balance.amount - _newBalance);\n    }\n\n    _balance.amount = _newBalance;\n    _balance.product = _supply.product;\n    _balance.updateAt = uint40(block.timestamp);\n    _balances[_account] = _balance;\n  }\n\n  /// @dev Internal function update boost checkpoint for the user.\n  /// @param _account The address of user to update.\n  /// @param _balance The latest balance struct of the user.\n  /// @param _supply The latest total supply struct.\n  function _updateBoostCheckpoint(\n    address _account,\n    address _owner,\n    TokenBalance memory _balance,\n    TokenBalance memory _ownerBalance,\n    TokenBalance memory _supply\n  ) internal {\n    if (_owner == address(0)) {\n      _ownerBalance = _balance;\n      _owner = _account;\n    } else {\n      voteOwnerBalances[_owner] = _ownerBalance;\n      uint256 nextWeekTs = _getWeekTs(block.timestamp);\n      voteOwnerHistoryBalances[_owner][nextWeekTs] = _ownerBalance.amount;\n    }\n\n    uint256 _ratio = _computeBoostRatio(\n      _ownerBalance.amount,\n      _balance.amount,\n      _supply.amount,\n      IVotingEscrow(ve).balanceOf(_owner),\n      IVotingEscrow(ve).totalSupply()\n    );\n    unchecked {\n      boostCheckpoint[_account] = BoostCheckpoint(uint64(_ratio), uint64(numTotalSupplyHistory - 1));\n    }\n  }\n\n  /// @dev Internal function to reduce asset loss due to liquidation.\n  /// @param _loss The amount of asset used by liquidation.\n  function _notifyLoss(uint256 _loss) internal {\n    TokenBalance memory _supply = _totalSupply;\n\n    uint256 _assetLossPerUnitStaked;\n    // use >= here, in case someone send extra asset to this contract.\n    if (_loss >= _supply.amount) {\n      // all assets are liquidated.\n      _assetLossPerUnitStaked = PRECISION;\n      lastAssetLossError = 0;\n      _supply.amount = 0;\n    } else {\n      uint256 _lossNumerator = _loss * PRECISION - lastAssetLossError;\n      // Add 1 to make error in quotient positive. We want \"slightly too much\" LUSD loss,\n      // which ensures the error in any given compoundedAssetDeposit favors the Stability Pool.\n      _assetLossPerUnitStaked = (_lossNumerator / uint256(_supply.amount)) + 1;\n      lastAssetLossError = _assetLossPerUnitStaked * uint256(_supply.amount) - _lossNumerator;\n      _supply.amount -= uint104(_loss);\n    }\n\n    // The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool LUSD in the liquidation.\n    // We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - LUSDLossPerUnitStaked)\n    uint256 _newProductFactor = PRECISION - _assetLossPerUnitStaked;\n    _supply.product = _supply.product.mul(uint64(_newProductFactor));\n    _supply.updateAt = uint40(block.timestamp);\n\n    _recordTotalSupply(_supply);\n  }\n\n  /// @dev Internal function to record the historical total supply.\n  /// @param _supply The new total supply to record.\n  function _recordTotalSupply(TokenBalance memory _supply) internal {\n    unchecked {\n      uint256 _numTotalSupplyHistory = numTotalSupplyHistory;\n      if (totalSupplyHistory[_numTotalSupplyHistory - 1].updateAt == _supply.updateAt) {\n        totalSupplyHistory[_numTotalSupplyHistory - 1] = _supply;\n      } else {\n        totalSupplyHistory[_numTotalSupplyHistory] = _supply;\n        numTotalSupplyHistory = _numTotalSupplyHistory + 1;\n      }\n      _totalSupply = _supply;\n    }\n  }\n\n  /// @dev Internal function to compute the amount of asset deposited after several liquidation.\n  ///\n  /// @param _initialBalance The amount of asset deposited initially.\n  /// @param _initialProduct The epoch state snapshot at initial depositing.\n  /// @return _compoundedBalance The amount asset deposited after several liquidation.\n  function _getCompoundedBalance(\n    uint256 _initialBalance,\n    uint112 _initialProduct,\n    uint112 _currentProduct\n  ) internal pure returns (uint256 _compoundedBalance) {\n    // no balance before, return 0\n    if (_initialBalance == 0) {\n      return 0;\n    }\n\n    // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0\n    if (_initialProduct.epoch() < _currentProduct.epoch()) {\n      return 0;\n    }\n\n    uint256 _exponentDiff = _currentProduct.exponent() - _initialProduct.exponent();\n\n    // Compute the compounded stake. If a scale change in P was made during the stake's lifetime,\n    // account for it. If more than one scale change was made, then the stake has decreased by a factor of\n    // at least 1e-9 -- so return 0.\n    if (_exponentDiff == 0) {\n      _compoundedBalance =\n        (_initialBalance * uint256(_currentProduct.magnitude())) /\n        uint256(_initialProduct.magnitude());\n    } else if (_exponentDiff == 1) {\n      _compoundedBalance =\n        (_initialBalance * uint256(_currentProduct.magnitude())) /\n        uint256(_initialProduct.magnitude()) /\n        DecrementalFloatingPoint.HALF_PRECISION;\n    } else {\n      _compoundedBalance = 0;\n    }\n\n    // If compounded deposit is less than a billionth of the initial deposit, return 0.\n    //\n    // NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error\n    // corrections should ensure the error in P \"favors the Pool\", i.e. any given compounded deposit should slightly less\n    // than it's theoretical value.\n    //\n    // Thus it's unclear whether this line is still really needed.\n    if (_compoundedBalance < _initialBalance / 1e9) {\n      _compoundedBalance = 0;\n    }\n\n    return _compoundedBalance;\n  }\n\n  /// @dev Internal function to get boost ratio for the given account.\n  ///\n  /// @param _account The address of the account to query.\n  function _getBoostRatio(address _account) internal view returns (uint256 _boostRatio) {\n    TokenBalance memory _balance = _balances[_account];\n    // no deposit before\n    if (_balance.amount == 0) return 0;\n\n    BoostCheckpoint memory _boostCheckpoint = boostCheckpoint[_account];\n    if (uint256(_balance.updateAt) == block.timestamp) {\n      return _boostCheckpoint.boostRatio;\n    }\n\n    address _owner = getStakerVoteOwner[_account];\n    address _veHolder = _owner == address(0) ? _account : _owner;\n\n    uint256 _nextIndex = _boostCheckpoint.historyIndex;\n    uint256 _currentRatio = _boostCheckpoint.boostRatio;\n    uint256 _prevTs = _balance.updateAt;\n    // compute the time weighted boost from _balance.updateAt to now.\n    uint256 _nowTs = _getWeekTs(_prevTs);\n    unchecked {\n      for (uint256 i = 0; i < 256; ++i) {\n        // it is more than 4 years, should be enough\n        if (_nowTs > block.timestamp) _nowTs = block.timestamp;\n        _boostRatio += _currentRatio * (_nowTs - _prevTs);\n        if (_nowTs == block.timestamp) break;\n        uint256 _veBalance = IVotingEscrowHelper(veHelper).balanceOf(_veHolder, _nowTs);\n        uint256 _veSupply = IVotingEscrowHelper(veHelper).totalSupply(_nowTs);\n        (_currentRatio, _nextIndex) = _boostRatioAt(_owner, _balance, _veBalance, _veSupply, _nextIndex, _nowTs);\n        _prevTs = _nowTs;\n        _nowTs += WEEK;\n      }\n      _boostRatio /= uint256(block.timestamp - _balance.updateAt);\n    }\n  }\n\n  /// @dev Internal function to get boost ratio at specific time point.\n  ///\n  /// Caller should make sure `t` is always a multiple of `WEEK`.\n  function _boostRatioAt(\n    address _owner,\n    TokenBalance memory _balance,\n    uint256 _veBalance,\n    uint256 _veSupply,\n    uint256 startIndex,\n    uint256 t\n  ) internal view returns (uint256, uint256) {\n    // Binary search to find largest `index` that totalSupplyHistory[index].updateAt <= t.\n    // The largest `index` may not be the correct one if there are multiple deposit/withdraw/liquidation\n    // in the same block. However, we only care about the boost ratio after timestamp `t`,\n    // it is tolerable to use the largest `index`.\n    unchecked {\n      uint256 endIndex = numTotalSupplyHistory - 1;\n      while (startIndex < endIndex) {\n        uint256 mid = (startIndex + endIndex + 1) >> 1;\n        if (totalSupplyHistory[mid].updateAt <= t) startIndex = mid;\n        else endIndex = mid - 1;\n      }\n    }\n\n    // Find the actual balance base on the supply.\n    TokenBalance memory _supply = totalSupplyHistory[startIndex];\n    uint256 _realBalance = _getCompoundedBalance(_balance.amount, _balance.product, _supply.product);\n    uint256 _ownerBalance = _owner != address(0) ? _getVoteOwnerHistoryBalances(_owner, t) : _realBalance;\n\n    return (_computeBoostRatio(_ownerBalance, _realBalance, _supply.amount, _veBalance, _veSupply), startIndex);\n  }\n\n  /// @dev Internal function to get `voteOwnerHistoryBalances`\n  /// @param _owner The address of the owner.\n  /// @param t The timestamp to query.\n  function _getVoteOwnerHistoryBalances(address _owner, uint256 t) internal view returns (uint256) {\n    uint256 _updateAt = voteOwnerBalances[_owner].updateAt;\n    while (t > _updateAt) {\n      uint256 w = voteOwnerHistoryBalances[_owner][t];\n      if (w != 0) return w;\n      unchecked {\n        t -= WEEK;\n      }\n    }\n    return voteOwnerBalances[_owner].amount;\n  }\n\n  /// @dev Internal function to compute boost ratio with given parameters.\n  function _computeBoostRatio(\n    uint256 _ownerBalance,\n    uint256 _balance,\n    uint256 _supply,\n    uint256 _veBalance,\n    uint256 _veSupply\n  ) internal pure returns (uint256) {\n    unchecked {\n      if (_balance == 0) return (PRECISION * 4) / 10;\n\n      // Compute boost ratio with Curve's rule: min(balance, balance * 0.4 + 0.6 * veBalance * supply / veSupply) / balance\n      uint256 _boostedBalance = (_ownerBalance * 4) / 10;\n      if (_veSupply > 0) {\n        _boostedBalance += (((_veBalance * _supply) / _veSupply) * 6) / 10;\n      }\n      _boostedBalance = (_boostedBalance * _balance) / _ownerBalance;\n\n      if (_boostedBalance > _balance) {\n        _boostedBalance = _balance;\n      }\n\n      return (_boostedBalance * PRECISION) / _balance;\n    }\n  }\n\n  /// @dev Internal function to compute the smallest week aligned timestamp after given timestamp.\n  /// @param timestamp The given timestamp.\n  function _getWeekTs(uint256 timestamp) internal pure returns (uint256) {\n    unchecked {\n      return ((timestamp + WEEK - 1) / WEEK) * WEEK;\n    }\n  }\n}\n"
      },
      "contracts/f(x)/rebalance-pool/ShareableRebalancePoolV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.20;\n\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport { IFxBoostableRebalancePool } from \"../../interfaces/f(x)/IFxBoostableRebalancePool.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable-v4/token/ERC20/IERC20Upgradeable.sol\";\nimport { IFxMarketV2 } from \"../../interfaces/f(x)/IFxMarketV2.sol\";\nimport { IFxTokenWrapper } from \"../../interfaces/f(x)/IFxTokenWrapper.sol\";\nimport { IFxTreasuryV2 } from \"../../interfaces/f(x)/IFxTreasuryV2.sol\";\n\nimport { ShareableRebalancePool } from \"./ShareableRebalancePool.sol\";\n\ncontract ShareableRebalancePoolV2 is ShareableRebalancePool {\n  using SafeERC20Upgradeable for IERC20Upgradeable;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(\n    address _fxn,\n    address _ve,\n    address _veHelper,\n    address _minter\n  ) ShareableRebalancePool(_fxn, _ve, _veHelper, _minter) {}\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IFxBoostableRebalancePool\n  function liquidate(uint256 _maxAmount, uint256 _minBaseOut)\n    external\n    override\n    onlyRole(LIQUIDATOR_ROLE)\n    returns (uint256 _liquidated, uint256 _baseOut)\n  {\n    _checkpoint(address(0));\n\n    IFxTreasuryV2 _treasury = IFxTreasuryV2(treasury);\n    if (_treasury.collateralRatio() >= liquidatableCollateralRatio) {\n      revert CannotLiquidate();\n    }\n    (, uint256 _maxLiquidatable) = _treasury.maxRedeemableFToken(liquidatableCollateralRatio);\n\n    uint256 _amount = _maxLiquidatable;\n    if (_amount > _maxAmount) {\n      _amount = _maxAmount;\n    }\n\n    address _asset = asset;\n    address _market = market;\n    address _wrapper = wrapper;\n\n    _liquidated = IERC20Upgradeable(_asset).balanceOf(address(this));\n    if (_amount > _liquidated) {\n      // cannot liquidate more than assets in this contract.\n      _amount = _liquidated;\n    }\n    IERC20Upgradeable(_asset).safeApprove(_market, 0);\n    IERC20Upgradeable(_asset).safeApprove(_market, _amount);\n    (_baseOut, ) = IFxMarketV2(_market).redeemFToken(_amount, _wrapper, _minBaseOut);\n    _liquidated = _liquidated - IERC20Upgradeable(_asset).balanceOf(address(this));\n\n    emit Liquidate(_liquidated, _baseOut);\n\n    // wrap base token if needed\n    address _token = baseToken;\n    if (_wrapper != address(this)) {\n      _baseOut = IFxTokenWrapper(_wrapper).wrap(_baseOut);\n      _token = IFxTokenWrapper(_wrapper).dst();\n    }\n\n    // distribute liquidated base token\n    _accumulateReward(_token, _baseOut);\n\n    // notify loss\n    _notifyLoss(_liquidated);\n  }\n}\n"
      },
      "contracts/interfaces/f(x)/IFxBoostableRebalancePool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxBoostableRebalancePool {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when user deposit asset into this contract.\n  /// @param owner The address of asset owner.\n  /// @param reciever The address of receiver of the asset in this contract.\n  /// @param amount The amount of asset deposited.\n  event Deposit(address indexed owner, address indexed reciever, uint256 amount);\n\n  /// @notice Emitted when the amount of deposited asset changed due to liquidation or deposit or unlock.\n  /// @param owner The address of asset owner.\n  /// @param newDeposit The new amount of deposited asset.\n  /// @param loss The amount of asset used by liquidation.\n  event UserDepositChange(address indexed owner, uint256 newDeposit, uint256 loss);\n\n  /// @notice Emitted when user withdraw asset.\n  /// @param owner The address of asset owner.\n  /// @param reciever The address of receiver of the asset.\n  /// @param amount The amount of token to withdraw.\n  event Withdraw(address indexed owner, address indexed reciever, uint256 amount);\n\n  /// @notice Emitted when liquidation happens.\n  /// @param liquidated The amount of asset liquidated.\n  /// @param baseGained The amount of base token gained.\n  event Liquidate(uint256 liquidated, uint256 baseGained);\n\n  /// @notice Emitted when the address of reward wrapper is updated.\n  /// @param oldWrapper The address of previous reward wrapper.\n  /// @param newWrapper The address of current reward wrapper.\n  event UpdateWrapper(address indexed oldWrapper, address indexed newWrapper);\n\n  /// @notice Emitted when the liquidatable collateral ratio is updated.\n  /// @param oldRatio The previous liquidatable collateral ratio.\n  /// @param newRatio The current liquidatable collateral ratio.\n  event UpdateLiquidatableCollateralRatio(uint256 oldRatio, uint256 newRatio);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown then the src token mismatched.\n  error ErrorWrapperSrcMismatch();\n\n  /// @dev Thrown then the dst token mismatched.\n  error ErrorWrapperDstMismatch();\n\n  /// @dev Thrown when the deposited amount is zero.\n  error DepositZeroAmount();\n\n  /// @dev Thrown when the withdrawn amount is zero.\n  error WithdrawZeroAmount();\n\n  /// @dev Thrown the cannot liquidate.\n  error CannotLiquidate();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the address of treasury contract.\n  function treasury() external view returns (address);\n\n  /// @notice Return the address of market contract.\n  function market() external view returns (address);\n\n  /// @notice Return the address of base token.\n  function baseToken() external view returns (address);\n\n  /// @notice Return the address of underlying token of this contract.\n  function asset() external view returns (address);\n\n  /// @notice Return the total amount of asset deposited to this contract.\n  function totalSupply() external view returns (uint256);\n\n  /// @notice Return the amount of deposited asset for some specific user.\n  /// @param account The address of user to query.\n  function balanceOf(address account) external view returns (uint256);\n\n  /// @notice Return the current boost ratio for some specific user.\n  /// @param account The address of user to query, multiplied by 1e18.\n  function getBoostRatio(address account) external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Deposit some asset to this contract.\n  /// @dev Use `amount=uint256(-1)` if you want to deposit all asset held.\n  /// @param amount The amount of asset to deposit.\n  /// @param receiver The address of recipient for the deposited asset.\n  function deposit(uint256 amount, address receiver) external;\n\n  /// @notice Withdraw asset from this contract.\n  function withdraw(uint256 amount, address receiver) external;\n\n  /// @notice Liquidate asset for base token.\n  /// @param maxAmount The maximum amount of asset to liquidate.\n  /// @param minBaseOut The minimum amount of base token should receive.\n  /// @return liquidated The amount of asset liquidated.\n  /// @return baseOut The amount of base token received.\n  function liquidate(uint256 maxAmount, uint256 minBaseOut) external returns (uint256 liquidated, uint256 baseOut);\n}\n"
      },
      "contracts/interfaces/f(x)/IFxMarket.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface IFxMarket {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when fToken or 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 fTokenOut The amount of fToken minted.\n  /// @param xTokenOut The amount of xToken minted.\n  /// @param mintFee The amount of mint fee charged.\n  event Mint(\n    address indexed owner,\n    address indexed recipient,\n    uint256 baseTokenIn,\n    uint256 fTokenOut,\n    uint256 xTokenOut,\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 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 Redeem(\n    address indexed owner,\n    address indexed recipient,\n    uint256 fTokenBurned,\n    uint256 xTokenBurned,\n    uint256 baseTokenOut,\n    uint256 redeemFee\n  );\n\n  /// @notice Emitted when someone add more base token.\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 xTokenMinted The amount of xToken minted.\n  event AddCollateral(address indexed owner, address indexed recipient, uint256 baseTokenIn, uint256 xTokenMinted);\n\n  /// @notice Emitted when someone liquidate with fToken.\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  event UserLiquidate(address indexed owner, address indexed recipient, uint256 fTokenBurned, uint256 baseTokenOut);\n\n  /// @notice Emitted when self liquidate with fToken.\n  /// @param caller The address of caller.\n  /// @param baseSwapAmt The amount of base token used to swap.\n  /// @param baseTokenOut The amount of base token redeemed.\n  /// @param fTokenBurned The amount of fToken liquidated.\n  event SelfLiquidate(address indexed caller, uint256 baseSwapAmt, uint256 baseTokenOut, uint256 fTokenBurned);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint both fToken and xToken with some base token.\n  /// @param baseIn The amount of base token supplied.\n  /// @param recipient The address of receiver for fToken and xToken.\n  /// @param minFTokenMinted The minimum amount of fToken should be received.\n  /// @param minXTokenMinted The minimum amount of xToken should be received.\n  /// @return fTokenMinted The amount of fToken should be received.\n  /// @return xTokenMinted The amount of xToken should be received.\n  function mint(\n    uint256 baseIn,\n    address recipient,\n    uint256 minFTokenMinted,\n    uint256 minXTokenMinted\n  ) external returns (uint256 fTokenMinted, uint256 xTokenMinted);\n\n  /// @notice Mint some fToken with some base token.\n  /// @param baseIn The amount 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 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 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 Mint some xToken by add some base token as collateral.\n  /// @param baseIn The amount 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  function addBaseToken(\n    uint256 baseIn,\n    address recipient,\n    uint256 minXTokenMinted\n  ) external returns (uint256 xTokenMinted);\n\n  /// @notice Redeem base token with fToken and xToken.\n  /// @param fTokenIn the amount of fToken to redeem, use `uint256(-1)` to redeem all fToken.\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 base token should be received.\n  /// @return baseOut The amount of base token should be received.\n  /// @return bonus The amount of base token as bonus.\n  function redeem(\n    uint256 fTokenIn,\n    uint256 xTokenIn,\n    address recipient,\n    uint256 minBaseOut\n  ) external returns (uint256 baseOut, uint256 bonus);\n\n  /// @notice Permissionless liquidate some fToken to increase the collateral ratio.\n  /// @param fTokenIn the amount of fToken to supply, use `uint256(-1)` to liquidate all fToken.\n  /// @param recipient The address of receiver for base token.\n  /// @param minBaseOut The minimum amount of base token should be received.\n  /// @return baseOut The amount of base token should be received.\n  function liquidate(\n    uint256 fTokenIn,\n    address recipient,\n    uint256 minBaseOut\n  ) external returns (uint256 baseOut);\n}\n"
      },
      "contracts/interfaces/f(x)/IFxMarketV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxMarketV2 {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when fToken is minted.\n  /// @param owner The address of base token owner.\n  /// @param recipient The address of receiver for fToken or xToken.\n  /// @param baseTokenIn The amount of base token deposited.\n  /// @param fTokenOut The amount of fToken minted.\n  /// @param mintFee The amount of mint fee charged.\n  event MintFToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 baseTokenIn,\n    uint256 fTokenOut,\n    uint256 mintFee\n  );\n\n  /// @notice Emitted when xToken is minted.\n  /// @param owner The address of base token owner.\n  /// @param recipient The address of receiver for fToken or xToken.\n  /// @param baseTokenIn The amount of base token deposited.\n  /// @param xTokenOut The amount of xToken minted.\n  /// @param bonus The amount of base token as bonus.\n  /// @param mintFee The amount of mint fee charged.\n  event MintXToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 baseTokenIn,\n    uint256 xTokenOut,\n    uint256 bonus,\n    uint256 mintFee\n  );\n\n  /// @notice Emitted when someone redeem base token with fToken or xToken.\n  /// @param owner The address of fToken and xToken owner.\n  /// @param recipient The address of receiver for base token.\n  /// @param fTokenBurned The amount of fToken burned.\n  /// @param baseTokenOut The amount of base token redeemed.\n  /// @param bonus The amount of base token as bonus.\n  /// @param redeemFee The amount of redeem fee charged.\n  event RedeemFToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 fTokenBurned,\n    uint256 baseTokenOut,\n    uint256 bonus,\n    uint256 redeemFee\n  );\n\n  /// @notice Emitted when someone redeem base token with fToken or xToken.\n  /// @param owner The address of fToken and xToken owner.\n  /// @param recipient The address of receiver for base token.\n  /// @param xTokenBurned The amount of xToken burned.\n  /// @param baseTokenOut The amount of base token redeemed.\n  /// @param redeemFee The amount of redeem fee charged.\n  event RedeemXToken(\n    address indexed owner,\n    address indexed recipient,\n    uint256 xTokenBurned,\n    uint256 baseTokenOut,\n    uint256 redeemFee\n  );\n\n  /// @notice Emitted when the fee ratio for minting fToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateMintFeeRatioFToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the fee ratio for minting xToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateMintFeeRatioXToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the fee ratio for redeeming fToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateRedeemFeeRatioFToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the fee ratio for redeeming xToken is updated.\n  /// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.\n  /// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.\n  event UpdateRedeemFeeRatioXToken(uint256 defaultFeeRatio, int256 extraFeeRatio);\n\n  /// @notice Emitted when the stability ratio is updated.\n  /// @param oldRatio The previous collateral ratio to enter stability mode, multiplied by 1e18.\n  /// @param newRatio The current collateral ratio to enter stability mode, multiplied by 1e18.\n  event UpdateStabilityRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the platform contract is updated.\n  /// @param oldPlatform The address of previous platform contract.\n  /// @param newPlatform The address of current platform contract.\n  event UpdatePlatform(address indexed oldPlatform, address indexed newPlatform);\n\n  /// @notice Emitted when the  reserve pool contract is updated.\n  /// @param oldReservePool The address of previous reserve pool contract.\n  /// @param newReservePool The address of current reserve pool contract.\n  event UpdateReservePool(address indexed oldReservePool, address indexed newReservePool);\n\n  /// @notice Emitted when the RebalancePoolRegistry contract is updated.\n  /// @param oldRegistry The address of previous RebalancePoolRegistry contract.\n  /// @param newRegistry The address of current RebalancePoolRegistry contract.\n  event UpdateRebalancePoolRegistry(address indexed oldRegistry, address indexed newRegistry);\n\n  /// @notice Pause or unpause mint.\n  /// @param oldStatus The previous status for mint.\n  /// @param newStatus The current status for mint.\n  event UpdateMintStatus(bool oldStatus, bool newStatus);\n\n  /// @notice Pause or unpause redeem.\n  /// @param oldStatus The previous status for redeem.\n  /// @param newStatus The current status for redeem.\n  event UpdateRedeemStatus(bool oldStatus, bool newStatus);\n\n  /// @notice Pause or unpause fToken mint in stability mode.\n  /// @param oldStatus The previous status for mint.\n  /// @param newStatus The current status for mint.\n  event UpdateFTokenMintStatusInStabilityMode(bool oldStatus, bool newStatus);\n\n  /// @notice Pause or unpause xToken redeem in stability mode.\n  /// @param oldStatus The previous status for redeem.\n  /// @param newStatus The current status for redeem.\n  event UpdateXTokenRedeemStatusInStabilityMode(bool oldStatus, bool newStatus);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when the caller if not fUSD contract.\n  error ErrorCallerNotFUSD();\n\n  /// @dev Thrown when token mint is paused.\n  error ErrorMintPaused();\n\n  /// @dev Thrown when fToken mint is paused in stability mode.\n  error ErrorFTokenMintPausedInStabilityMode();\n\n  /// @dev Thrown when mint with zero amount base token.\n  error ErrorMintZeroAmount();\n\n  /// @dev Thrown when the amount of fToken is not enough.\n  error ErrorInsufficientFTokenOutput();\n\n  /// @dev Thrown when the amount of xToken is not enough.\n  error ErrorInsufficientXTokenOutput();\n\n  /// @dev Thrown when token redeem is paused.\n  error ErrorRedeemPaused();\n\n  /// @dev Thrown when xToken redeem is paused in stability mode.\n  error ErrorXTokenRedeemPausedInStabilityMode();\n\n  /// @dev Thrown when redeem with zero amount fToken or xToken.\n  error ErrorRedeemZeroAmount();\n\n  /// @dev Thrown when the amount of base token is not enough.\n  error ErrorInsufficientBaseOutput();\n\n  /// @dev Thrown when the stability ratio is too large.\n  error ErrorStabilityRatioTooLarge();\n\n  /// @dev Thrown when the default fee is too large.\n  error ErrorDefaultFeeTooLarge();\n\n  /// @dev Thrown when the delta fee is too small.\n  error ErrorDeltaFeeTooSmall();\n\n  /// @dev Thrown when the sum of default fee and delta fee is too large.\n  error ErrorTotalFeeTooLarge();\n\n  /// @dev Thrown when the given address is zero.\n  error ErrorZeroAddress();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of Treasury contract.\n  function treasury() external view returns (address);\n\n  /// @notice Return the address of base token.\n  function baseToken() external view returns (address);\n\n  /// @notice Return the address fractional base token.\n  function fToken() external view returns (address);\n\n  /// @notice Return the address leveraged base token.\n  function xToken() external view returns (address);\n\n  /// @notice Return the collateral ratio to enter stability mode, multiplied by 1e18.\n  function stabilityRatio() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint some fToken with some base token.\n  /// @param baseIn The amount of wrapped value of base token supplied, use `uint256(-1)` to supply all base token.\n  /// @param recipient The address of receiver for fToken.\n  /// @param minFTokenMinted The minimum amount of fToken should be received.\n  /// @return fTokenMinted The amount of fToken should be received.\n  function mintFToken(\n    uint256 baseIn,\n    address recipient,\n    uint256 minFTokenMinted\n  ) external returns (uint256 fTokenMinted);\n\n  /// @notice Mint some xToken with some base token.\n  /// @param baseIn The amount of wrapped value of base token supplied, use `uint256(-1)` to supply all base token.\n  /// @param recipient The address of receiver for xToken.\n  /// @param minXTokenMinted The minimum amount of xToken should be received.\n  /// @return xTokenMinted The amount of xToken should be received.\n  /// @return bonus The amount of wrapped value of base token as bonus.\n  function mintXToken(\n    uint256 baseIn,\n    address recipient,\n    uint256 minXTokenMinted\n  ) external returns (uint256 xTokenMinted, uint256 bonus);\n\n  /// @notice Redeem base token with fToken.\n  /// @param fTokenIn the amount of fToken to redeem, use `uint256(-1)` to redeem all fToken.\n  /// @param recipient The address of receiver for base token.\n  /// @param minBaseOut The minimum amount of wrapped value of base token should be received.\n  /// @return baseOut The amount of wrapped value of base token should be received.\n  /// @return bonus The amount of wrapped value of base token as bonus.\n  function redeemFToken(\n    uint256 fTokenIn,\n    address recipient,\n    uint256 minBaseOut\n  ) external returns (uint256 baseOut, uint256 bonus);\n\n  /// @notice Redeem base token with xToken.\n  /// @param xTokenIn the amount of xToken to redeem, use `uint256(-1)` to redeem all xToken.\n  /// @param recipient The address of receiver for base token.\n  /// @param minBaseOut The minimum amount of wrapped value of base token should be received.\n  /// @return baseOut The amount of wrapped value of base token should be received.\n  function redeemXToken(\n    uint256 xTokenIn,\n    address recipient,\n    uint256 minBaseOut\n  ) external returns (uint256 baseOut);\n}\n"
      },
      "contracts/interfaces/f(x)/IFxShareableRebalancePool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { IFxBoostableRebalancePool } from \"./IFxBoostableRebalancePool.sol\";\n\ninterface IFxShareableRebalancePool is IFxBoostableRebalancePool {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when one user share votes to another user.\n  /// @param owner The address of votes owner.\n  /// @param staker The address of staker to share votes.\n  event ShareVote(address indexed owner, address indexed staker);\n\n  /// @notice Emitted when the owner cancel sharing to some staker.\n  /// @param owner The address of votes owner.\n  /// @param staker The address of staker to cancel votes share.\n  event CancelShareVote(address indexed owner, address indexed staker);\n\n  /// @notice Emitted when staker accept the vote sharing.\n  /// @param staker The address of the staker.\n  /// @param oldOwner The address of the previous vote sharing owner.\n  /// @param newOwner The address of the current vote sharing owner.\n  event AcceptSharedVote(address indexed staker, address indexed oldOwner, address indexed newOwner);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when caller shares votes to self.\n  error ErrorSelfSharingIsNotAllowed();\n\n  /// @dev Thrown when a staker with shared votes try to share its votes to others.\n  error ErrorCascadedSharingIsNotAllowed();\n\n  /// @dev Thrown when staker try to accept non-allowed vote sharing.\n  error ErrorVoteShareNotAllowed();\n\n  /// @dev Thrown when staker try to reject a non-existed vote sharing.\n  error ErrorNoAcceptedSharedVote();\n\n  /// @dev Thrown when the staker has ability to share ve balance.\n  error ErrorVoteOwnerCannotStake();\n\n  /// @dev Thrown when staker try to accept twice.\n  error ErrorRepeatAcceptSharedVote();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the owner of votes of some staker.\n  /// @param account The address of user to query.\n  function getStakerVoteOwner(address account) external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Withdraw asset from this contract on behalf of someone\n  function withdrawFrom(\n    address owner,\n    uint256 amount,\n    address receiver\n  ) external;\n\n  /// @notice Owner changes the vote sharing state for some user.\n  /// @param staker The address of user to change.\n  function toggleVoteSharing(address staker) external;\n\n  /// @notice Staker accepts the vote sharing.\n  /// @param newOwner The address of the owner of the votes.\n  function acceptSharedVote(address newOwner) external;\n\n  /// @notice Staker reject the current vote sharing.\n  function rejectSharedVote() external;\n}\n"
      },
      "contracts/interfaces/f(x)/IFxTokenWrapper.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface IFxTokenWrapper {\n  /// @notice Return the address of source token.\n  function src() external view returns (address);\n\n  /// @notice Return the address of destination token.\n  function dst() external view returns (address);\n\n  /// @notice Wrap some `src` token to `dst` token.\n  ///\n  /// @dev Assume that the token is already transfered to this contract.\n  ///\n  /// @param amount The amount of `src` token to wrap.\n  /// @return uint256 The amount of `dst` token received.\n  function wrap(uint256 amount) external returns (uint256);\n\n  /// @notice Unwrap some `dst` token to `src` token.\n  ///\n  /// @dev Assume that the token is already transfered to this contract.\n  ///\n  /// @param amount The amount of `dst` token to unwrap.\n  /// @return uint256 The amount of `src` token received.\n  function unwrap(uint256 amount) external returns (uint256);\n}\n"
      },
      "contracts/interfaces/f(x)/IFxTreasury.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\ninterface IFxTreasury {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the net asset value is updated.\n  /// @param price The new price of base token.\n  /// @param fNav The new net asset value of fToken.\n  event ProtocolSettle(uint256 price, uint256 fNav);\n\n  /*********\n   * Enums *\n   *********/\n\n  enum MintOption {\n    Both,\n    FToken,\n    XToken\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 Return the address of strategy contract.\n  function strategy() external view returns (address);\n\n  /// @notice The last updated permissioned base token price.\n  function lastPermissionedPrice() external view returns (uint256);\n\n  /// @notice Return the total amount of base token deposited.\n  function totalBaseToken() external view returns (uint256);\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 Convert unwrapped token amount to wrapped token amount.\n  /// @param amount The unwrapped token amount.\n  function convertToWrapped(uint256 amount) external view returns (uint256);\n\n  /// @notice Convert wrapped token amount to unwrapped token amount.\n  /// @param amount The wrapped token amount.\n  function convertToUnwrapped(uint256 amount) external view returns (uint256);\n\n  /// @notice Return current nav for base token, fToken and xToken.\n  /// @return baseNav The nav for base token.\n  /// @return fNav The nav for fToken.\n  /// @return xNav The nav for xToken.\n  function getCurrentNav()\n    external\n    view\n    returns (\n      uint256 baseNav,\n      uint256 fNav,\n      uint256 xNav\n    );\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 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 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 base token needed to reach the new collateral ratio, with incentive.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @param incentiveRatio The extra incentive 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 maxMintableXTokenWithIncentive(uint256 newCollateralRatio, uint256 incentiveRatio)\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 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 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 Compute the maximum amount of fToken can be liquidated.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @param incentiveRatio The extra incentive ratio, multipled by 1e18.\n  /// @return maxBaseOut The maximum amount of base token can liquidate, without incentive.\n  /// @return maxFTokenLiquidatable The maximum amount of fToken can be liquidated.\n  function maxLiquidatable(uint256 newCollateralRatio, uint256 incentiveRatio)\n    external\n    view\n    returns (uint256 maxBaseOut, uint256 maxFTokenLiquidatable);\n\n  /// @notice Return the exponential moving average of the leverage ratio.\n  function leverageRatio() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint fToken and xToken with some base token.\n  /// @param baseIn The amount of base token deposited.\n  /// @param recipient The address of receiver.\n  /// @param option The mint option, xToken or fToken or both.\n  /// @return fTokenOut The amount of fToken minted.\n  /// @return xTokenOut The amount of xToken minted.\n  function mint(\n    uint256 baseIn,\n    address recipient,\n    MintOption option\n  ) external returns (uint256 fTokenOut, 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 base token redeemed.\n  function redeem(\n    uint256 fTokenIn,\n    uint256 xTokenIn,\n    address owner\n  ) external returns (uint256 baseOut);\n\n  /// @notice Add some base token to mint xToken with incentive.\n  /// @param baseIn The amount of base token deposited.\n  /// @param incentiveRatio The incentive ratio.\n  /// @param recipient The address of receiver.\n  /// @return xTokenOut The amount of xToken minted.\n  function addBaseToken(\n    uint256 baseIn,\n    uint256 incentiveRatio,\n    address recipient\n  ) external returns (uint256 xTokenOut);\n\n  /// @notice Liquidate fToken to base token with incentive.\n  /// @param fTokenIn The amount of fToken to liquidate.\n  /// @param incentiveRatio The incentive ratio.\n  /// @param owner The owner of the fToken.\n  /// @param baseOut The amount of base token liquidated.\n  function liquidate(\n    uint256 fTokenIn,\n    uint256 incentiveRatio,\n    address owner\n  ) external returns (uint256 baseOut);\n\n  /// @notice Settle the nav of base token, fToken and xToken.\n  function protocolSettle() 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"
      },
      "contracts/interfaces/f(x)/IFxTreasuryV2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxTreasuryV2 {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the platform contract is updated.\n  /// @param oldPlatform The address of previous platform contract.\n  /// @param newPlatform The address of current platform contract.\n  event UpdatePlatform(address indexed oldPlatform, address indexed newPlatform);\n\n  /// @notice Emitted when the RebalancePoolSplitter contract is updated.\n  /// @param oldRebalancePoolSplitter The address of previous RebalancePoolSplitter contract.\n  /// @param newRebalancePoolSplitter The address of current RebalancePoolSplitter.\n  event UpdateRebalancePoolSplitter(address indexed oldRebalancePoolSplitter, address indexed newRebalancePoolSplitter);\n\n  /// @notice Emitted when the price oracle contract is updated.\n  /// @param oldPriceOracle The address of previous price oracle.\n  /// @param newPriceOracle The address of current price oracle.\n  event UpdatePriceOracle(address indexed oldPriceOracle, address indexed newPriceOracle);\n\n  /// @notice Emitted when the strategy contract is updated.\n  /// @param oldStrategy The address of previous strategy.\n  /// @param newStrategy The address of current strategy.\n  event UpdateStrategy(address indexed oldStrategy, address indexed newStrategy);\n\n  /// @notice Emitted when the base token cap is updated.\n  /// @param oldBaseTokenCap The value of previous base token cap.\n  /// @param newBaseTokenCap The value of current base token cap.\n  event UpdateBaseTokenCap(uint256 oldBaseTokenCap, uint256 newBaseTokenCap);\n\n  /// @notice Emitted when the EMA sample interval is updated.\n  /// @param oldSampleInterval The value of previous EMA sample interval.\n  /// @param newSampleInterval The value of current EMA sample interval.\n  event UpdateEMASampleInterval(uint256 oldSampleInterval, uint256 newSampleInterval);\n\n  /// @notice Emitted when the reference price is updated.\n  /// @param oldPrice The value of previous reference price.\n  /// @param newPrice The value of current reference price.\n  event Settle(uint256 oldPrice, uint256 newPrice);\n\n  /// @notice Emitted when the ratio for rebalance pool is updated.\n  /// @param oldRatio The value of the previous ratio, multipled by 1e9.\n  /// @param newRatio The value of the current ratio, multipled by 1e9.\n  event UpdateRebalancePoolRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the ratio for harvester is updated.\n  /// @param oldRatio The value of the previous ratio, multipled by 1e9.\n  /// @param newRatio The value of the current ratio, multipled by 1e9.\n  event UpdateHarvesterRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when someone harvest pending stETH rewards.\n  /// @param caller The address of caller.\n  /// @param totalRewards The amount of total harvested rewards.\n  /// @param rebalancePoolRewards The amount of harvested rewards distributed to stability pool.\n  /// @param harvestBounty The amount of harvested rewards distributed to caller as harvest bounty.\n  event Harvest(address indexed caller, uint256 totalRewards, uint256 rebalancePoolRewards, uint256 harvestBounty);\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when the collateral ratio is smaller than 100%.\n  error ErrorCollateralRatioTooSmall();\n\n  /// @dev Thrown when mint exceed total capacity.\n  error ErrorExceedTotalCap();\n\n  /// @dev Thrown when the oracle price is invalid.\n  error ErrorInvalidOraclePrice();\n\n  /// @dev Thrown when the twap price is invalid.\n  error ErrorInvalidTwapPrice();\n\n  /// @dev Thrown when initialize protocol twice.\n  error ErrorProtocolInitialized();\n\n  /// @dev Thrown when the initial amount of base token is not enough.\n  error ErrorInsufficientInitialBaseToken();\n\n  /// @dev Thrown when current is under collateral.\n  error ErrorUnderCollateral();\n\n  /// @dev Thrown when the sample internal for EMA is too small.\n  error ErrorEMASampleIntervalTooSmall();\n\n  /// @dev Thrown when the expense ratio exceeds `MAX_REBALANCE_POOL_RATIO`.\n  error ErrorRebalancePoolRatioTooLarge();\n\n  /// @dev Thrown when the harvester ratio exceeds `MAX_HARVESTER_RATIO`.\n  error ErrorHarvesterRatioTooLarge();\n\n  /// @dev Thrown when the given address is zero.\n  error ErrorZeroAddress();\n\n  /*********\n   * Enums *\n   *********/\n\n  enum Action {\n    None,\n    MintFToken,\n    MintXToken,\n    RedeemFToken,\n    RedeemXToken\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the address of base token.\n  function baseToken() external view returns (address);\n\n  /// @notice Return the address fractional base token.\n  function fToken() external view returns (address);\n\n  /// @notice Return the address leveraged base token.\n  function xToken() external view returns (address);\n\n  /// @notice The reference base token price.\n  function referenceBaseTokenPrice() external view returns (uint256);\n\n  /// @notice The current base token price.\n  function currentBaseTokenPrice() external view returns (uint256);\n\n  /// @notice Return whether the price is valid.\n  function isBaseTokenPriceValid() external view returns (bool);\n\n  /// @notice Return the total amount of underlying value of base token deposited.\n  function totalBaseToken() external view returns (uint256);\n\n  /// @notice Return the address of strategy contract.\n  function strategy() external view returns (address);\n\n  /// @notice Return the total amount of base token managed by strategy.\n  function strategyUnderlying() external view returns (uint256);\n\n  /// @notice Return the current collateral ratio of fToken, multipled by 1e18.\n  function collateralRatio() external view returns (uint256);\n\n  /// @notice Return whether the system is under collateral.\n  function isUnderCollateral() external view returns (bool);\n\n  /// @notice Compute the amount of base token needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseIn The amount of underlying value of base token needed.\n  /// @return maxFTokenMintable The amount of fToken can be minted.\n  function maxMintableFToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseIn, uint256 maxFTokenMintable);\n\n  /// @notice Compute the amount of base token needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseIn The amount of underlying value of base token needed.\n  /// @return maxXTokenMintable The amount of xToken can be minted.\n  function maxMintableXToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseIn, uint256 maxXTokenMintable);\n\n  /// @notice Compute the amount of fToken needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseOut The amount of underlying value of base token redeemed.\n  /// @return maxFTokenRedeemable The amount of fToken needed.\n  function maxRedeemableFToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseOut, uint256 maxFTokenRedeemable);\n\n  /// @notice Compute the amount of xToken needed to reach the new collateral ratio.\n  /// @param newCollateralRatio The target collateral ratio, multipled by 1e18.\n  /// @return maxBaseOut The amount of underlying value of base token redeemed.\n  /// @return maxXTokenRedeemable The amount of xToken needed.\n  function maxRedeemableXToken(uint256 newCollateralRatio)\n    external\n    view\n    returns (uint256 maxBaseOut, uint256 maxXTokenRedeemable);\n\n  /// @notice Return the exponential moving average of the leverage ratio.\n  function leverageRatio() external view returns (uint256);\n\n  /// @notice Convert underlying token amount to wrapped token amount.\n  /// @param amount The underlying token amount.\n  function getWrapppedValue(uint256 amount) external view returns (uint256);\n\n  /// @notice Convert wrapped token amount to underlying token amount.\n  /// @param amount The wrapped token amount.\n  function getUnderlyingValue(uint256 amount) external view returns (uint256);\n\n  /// @notice Return the fee ratio distributed to rebalance pool, multipled by 1e9.\n  function getRebalancePoolRatio() external view returns (uint256);\n\n  /// @notice Return the fee ratio distributed to harvester, multipled by 1e9.\n  function getHarvesterRatio() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Initialize the protocol.\n  /// @param baseIn The amount of underlying value of the base token used to initialize.\n  function initializeProtocol(uint256 baseIn) external returns (uint256 fTokenOut, uint256 xTokenOut);\n\n  /// @notice Mint fToken with some base token.\n  /// @param baseIn The amount of underlying value of base token deposited.\n  /// @param recipient The address of receiver.\n  /// @return fTokenOut The amount of fToken minted.\n  function mintFToken(uint256 baseIn, address recipient) external returns (uint256 fTokenOut);\n\n  /// @notice Mint xToken with some base token.\n  /// @param baseIn The amount of underlying value of base token deposited.\n  /// @param recipient The address of receiver.\n  /// @return xTokenOut The amount of xToken minted.\n  function mintXToken(uint256 baseIn, address recipient) external returns (uint256 xTokenOut);\n\n  /// @notice Redeem fToken and xToken to base tokne.\n  /// @param fTokenIn The amount of fToken to redeem.\n  /// @param xTokenIn The amount of xToken to redeem.\n  /// @param owner The owner of the fToken or xToken.\n  /// @param baseOut The amount of underlying value of base token redeemed.\n  function redeem(\n    uint256 fTokenIn,\n    uint256 xTokenIn,\n    address owner\n  ) external returns (uint256 baseOut);\n\n  /// @notice Settle the nav of base token, fToken and xToken.\n  function settle() external;\n\n  /// @notice Transfer some base token to strategy contract.\n  /// @param amount The amount of token to transfer.\n  function transferToStrategy(uint256 amount) external;\n\n  /// @notice Notify base token profit from strategy contract.\n  /// @param amount The amount of base token.\n  function notifyStrategyProfit(uint256 amount) external;\n\n  /// @notice Harvest pending rewards to stability pool.\n  function harvest() external;\n}\n"
      },
      "contracts/interfaces/ICurveTokenMinter.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0 || ^0.8.0;\n\n// solhint-disable func-name-mixedcase\n// solhint-disable var-name-mixedcase\n\ninterface ICurveTokenMinter {\n  function token() external view returns (address);\n\n  function controller() external view returns (address);\n\n  function minted(address _user, address _gauge) external view returns (uint256);\n\n  function allowed_to_mint_for(address _minter, address _user) external view returns (bool);\n\n  function mint(address gauge_addr) external;\n\n  function mint_many(address[8] memory gauge_addrs) external;\n\n  function mint_for(address gauge_addr, address _for) external;\n\n  function toggle_approve_mint(address minting_user) external;\n}\n"
      },
      "contracts/interfaces/voting-escrow/IVotingEscrow.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n// solhint-disable func-name-mixedcase\n\ninterface IVotingEscrow {\n  /***********\n   * Structs *\n   ***********/\n\n  struct Point {\n    int128 bias;\n    int128 slope;\n    uint256 ts;\n    uint256 blk;\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  function token() external view returns (address);\n\n  function epoch() external view returns (uint256);\n\n  function point_history(uint256 epoch) external view returns (Point memory);\n\n  function user_point_epoch(address account) external view returns (uint256);\n\n  function user_point_history(address account, uint256 epoch) external view returns (Point memory);\n\n  /// @notice Get the timestamp for checkpoint `epoch` for `addr`\n  /// @param addr User wallet address\n  /// @param epoch User epoch number\n  /// @return Epoch time of the checkpoint\n  function user_point_history__ts(address addr, uint256 epoch) external view returns (uint256);\n\n  /// @notice Get timestamp when `addr`'s lock finishes\n  /// @param addr User wallet\n  /// @return Epoch time of the lock end\n  function locked__end(address addr) external view returns (uint256);\n\n  /// @notice Calculate total voting power\n  /// @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility\n  /// @return Total voting power\n  function totalSupply() external view returns (uint256);\n\n  /// @notice Get the current voting power for `msg.sender`\n  /// @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility\n  /// @param addr User wallet address\n  /// @return User voting power\n  function balanceOf(address addr) external view returns (uint256);\n\n  /// @notice time -> signed slope change\n  function slope_changes(uint256 week) external view returns (int128);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Deposit `value` tokens for `addr` and add to the lock\n  /// @dev Anyone (even a smart contract) can deposit for someone else, but\n  ///      cannot extend their locktime and deposit for a brand new user\n  /// @param addr User's wallet address\n  /// @param value Amount to add to user's lock\n  function deposit_for(address addr, uint256 value) external;\n\n  /// @notice Deposit `value` tokens for `msg.sender` and lock until `unlock_time`\n  /// @param value Amount to deposit\n  /// @param unlock_time Epoch time when tokens unlock, rounded down to whole weeks\n  function create_lock(uint256 value, uint256 unlock_time) external;\n\n  /// @notice Deposit `value` additional tokens for `msg.sender`\n  ///         without modifying the unlock time\n  /// @param value Amount of tokens to deposit and add to the lock\n  function increase_amount(uint256 value) external;\n\n  /// @notice Extend the unlock time for `msg.sender` to `unlock_time`\n  /// @param unlock_time New epoch time for unlocking\n  function increase_unlock_time(uint256 unlock_time) external;\n\n  /// @notice Withdraw all tokens for `msg.sender`\n  /// @dev Only possible if the lock has expired\n  function withdraw() external;\n\n  /// @notice Record global data to checkpoint\n  function checkpoint() external;\n}\n"
      },
      "contracts/interfaces/voting-escrow/IVotingEscrowHelper.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IVotingEscrowHelper {\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when try to checkpoint a future timestamp.\n  error ErrorCheckpointFutureTime();\n\n  /// @dev Thrown when try to checkpoint a timestamp before start.\n  error ErrorCheckpointInvalidPastTime();\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the ve total supply at some specific time point.\n  /// @param timestamp The time point in second to query.\n  function totalSupply(uint256 timestamp) external view returns (uint256);\n\n  /// @notice Return the ve balance of some user at some specific time point.\n  /// @param account The address of user to query.\n  /// @param timestamp The time point in second to query.\n  function balanceOf(address account, uint256 timestamp) external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Snapshot the state of some user.\n  /// @param account The address of user to checkpoint.\n  function checkpoint(address account) external;\n\n  /// @notice Snapshot the state of some user.\n  /// @param account The address of user to checkpoint.\n  /// @param timestamp The timestamp to checkpoint, should not less than current timestamp.\n  function checkpoint(address account, uint256 timestamp) external;\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "evmVersion": "shanghai",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}