{"sources":{"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.20;\n\nimport {IAccessControl} from \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {ERC165Upgradeable} from \"../utils/introspection/ERC165Upgradeable.sol\";\nimport {Initializable} from \"../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, IAccessControl, ERC165Upgradeable {\n    struct RoleData {\n        mapping(address account => bool) hasRole;\n        bytes32 adminRole;\n    }\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl\n    struct AccessControlStorage {\n        mapping(bytes32 role => RoleData) _roles;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.AccessControl\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;\n\n    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {\n        assembly {\n            $.slot := AccessControlStorageLocation\n        }\n    }\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with an {AccessControlUnauthorizedAccount} error including the required role.\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    function __AccessControl_init() internal onlyInitializing {\n    }\n\n    function __AccessControl_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(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].hasRole[account];\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`\n     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`\n     * is missing `role`.\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert AccessControlUnauthorizedAccount(account, role);\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 returns (bytes32) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\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 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 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 `callerConfirmation`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) public virtual {\n        if (callerConfirmation != _msgSender()) {\n            revert AccessControlBadConfirmation();\n        }\n\n        _revokeRole(role, callerConfirmation);\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        AccessControlStorage storage $ = _getAccessControlStorage();\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        $._roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (!hasRole(role, account)) {\n            $._roles[role].hasRole[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (hasRole(role, account)) {\n            $._roles[role].hasRole[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\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 Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reininitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\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 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\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        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\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        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._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 _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        assembly {\n            $.slot := INITIALIZABLE_STORAGE\n        }\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../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    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable\n    struct PausableStorage {\n        bool _paused;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Pausable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;\n\n    function _getPausableStorage() private pure returns (PausableStorage storage $) {\n        assembly {\n            $.slot := PausableStorageLocation\n        }\n    }\n\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    /**\n     * @dev The operation failed because the contract is paused.\n     */\n    error EnforcedPause();\n\n    /**\n     * @dev The operation failed because the contract is not paused.\n     */\n    error ExpectedPause();\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    function __Pausable_init() internal onlyInitializing {\n        __Pausable_init_unchained();\n    }\n\n    function __Pausable_init_unchained() internal onlyInitializing {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = false;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        PausableStorage storage $ = _getPausableStorage();\n        return $._paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        if (paused()) {\n            revert EnforcedPause();\n        }\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        if (!paused()) {\n            revert ExpectedPause();\n        }\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = false;\n        emit Unpaused(_msgSender());\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../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    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n    struct ReentrancyGuardStorage {\n        uint256 _status;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n        assembly {\n            $.slot := ReentrancyGuardStorageLocation\n        }\n    }\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\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        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if ($._status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        $._status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\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        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        return $._status == ENTERED;\n    }\n}\n"},"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../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 */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\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 returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},"@openzeppelin/contracts/access/IAccessControl.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev The `account` is missing a role.\n     */\n    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);\n\n    /**\n     * @dev The caller of a function is not the expected one.\n     *\n     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.\n     */\n    error AccessControlBadConfirmation();\n\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    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 `callerConfirmation`.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) external;\n}\n"},"@openzeppelin/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n     * 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 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` 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 value) external returns (bool);\n}\n"},"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\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 *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"},"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC20Permit} from \"../extensions/IERC20Permit.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev An operation with an ERC20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data);\n        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\n    }\n}\n"},"@openzeppelin/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n  /**\n   * @dev The ETH balance of the account is not enough to perform the operation.\n   */\n  error AddressInsufficientBalance(address account);\n\n  /**\n   * @dev There's no code at `target` (it is not a contract).\n   */\n  error AddressEmptyCode(address target);\n\n  /**\n   * @dev A call to an address target failed. The target may have reverted.\n   */\n  error FailedInnerCall();\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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n   */\n  function sendValue(address payable recipient, uint256 amount) internal {\n    if (address(this).balance < amount) {\n      revert AddressInsufficientBalance(address(this));\n    }\n\n    (bool success, ) = recipient.call{ value: amount }(\"\");\n    if (!success) {\n      revert FailedInnerCall();\n    }\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 or custom error, it is bubbled\n   * up by this function (like regular Solidity function calls). However, if\n   * the call reverted with no returned reason, this function reverts with a\n   * {FailedInnerCall} error.\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  function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, 0);\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  function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n    if (address(this).balance < value) {\n      revert AddressInsufficientBalance(address(this));\n    }\n    (bool success, bytes memory returndata) = target.call{ value: value }(data);\n    return verifyCallResultFromTarget(target, success, returndata);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a static call.\n   */\n  function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n    (bool success, bytes memory returndata) = target.staticcall(data);\n    return verifyCallResultFromTarget(target, success, returndata);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a delegate call.\n   */\n  function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n    (bool success, bytes memory returndata) = target.delegatecall(data);\n    return verifyCallResultFromTarget(target, success, returndata);\n  }\n\n  /**\n   * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n   * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n   * unsuccessful call.\n   */\n  function verifyCallResultFromTarget(\n    address target,\n    bool success,\n    bytes memory returndata\n  ) internal view returns (bytes memory) {\n    if (!success) {\n      _revert(returndata);\n    } else {\n      // only check if target is a contract if the call was successful and the return data is empty\n      // otherwise we already know that it was a contract\n      if (returndata.length == 0 && target.code.length == 0) {\n        revert AddressEmptyCode(target);\n      }\n      return returndata;\n    }\n  }\n\n  /**\n   * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n   * revert reason or with a default {FailedInnerCall} error.\n   */\n  function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n    if (!success) {\n      _revert(returndata);\n    } else {\n      return returndata;\n    }\n  }\n\n  /**\n   * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n   */\n  function _revert(bytes memory returndata) 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 FailedInnerCall();\n    }\n  }\n}\n"},"@openzeppelin/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"@openzeppelin/contracts/utils/structs/EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.20;\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 EnumerableSet {\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 is the index of the value in the `values` array plus 1.\n        // Position 0 is used to mean a value is not in the set.\n        mapping(bytes32 value => uint256) _positions;\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._positions[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 cache the value's position to prevent multiple reads from the same storage slot\n        uint256 position = set._positions[value];\n\n        if (position != 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 valueIndex = position - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (valueIndex != lastIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the lastValue to the index where the value to delete is\n                set._values[valueIndex] = lastValue;\n                // Update the tracked position of the lastValue (that was just moved)\n                set._positions[lastValue] = position;\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the tracked position for the deleted slot\n            delete set._positions[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._positions[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/ERC3156/IERC3156FlashBorrower.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IERC3156FlashBorrower {\n  /**\n   * @dev Receive a flash loan.\n   * @param initiator The initiator of the loan.\n   * @param token The loan currency.\n   * @param amount The amount of tokens lent.\n   * @param fee The additional amount of tokens to repay.\n   * @param data Arbitrary data structure, intended to contain user-defined parameters.\n   * @return The keccak256 hash of \"ERC3156FlashBorrower.onFlashLoan\"\n   */\n  function onFlashLoan(\n    address initiator,\n    address token,\n    uint256 amount,\n    uint256 fee,\n    bytes calldata data\n  ) external returns (bytes32);\n}\n"},"contracts/common/ERC3156/IERC3156FlashLender.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { IERC3156FlashBorrower } from \"./IERC3156FlashBorrower.sol\";\n\ninterface IERC3156FlashLender {\n  /**\n   * @dev The amount of currency available to be lent.\n   * @param token The loan currency.\n   * @return The amount of `token` that can be borrowed.\n   */\n  function maxFlashLoan(address token) external view returns (uint256);\n\n  /**\n   * @dev The fee to be charged for a given loan.\n   * @param token The loan currency.\n   * @param amount The amount of tokens lent.\n   * @return The amount of `token` to be charged for the loan, on top of the returned principal.\n   */\n  function flashFee(address token, uint256 amount) external view returns (uint256);\n\n  /**\n   * @dev Initiate a flash loan.\n   * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.\n   * @param token The loan currency.\n   * @param amount The amount of tokens lent.\n   * @param data Arbitrary data structure, intended to contain user-defined parameters.\n   */\n  function flashLoan(\n    IERC3156FlashBorrower receiver,\n    address token,\n    uint256 amount,\n    bytes calldata data\n  ) external returns (bool);\n}\n"},"contracts/common/codec/WordCodec.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n// solhint-disable no-inline-assembly\n\n/// @dev A subset copied from the following contracts:\n///\n/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol`\n/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodecHelpers.sol`\nlibrary WordCodec {\n  /// @dev Inserts an unsigned integer of bitLength, shifted by an offset, into a 256 bit word,\n  /// replacing the old value. Returns the new word.\n  function insertUint(\n    bytes32 word,\n    uint256 value,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32 result) {\n    // Equivalent to:\n    // uint256 mask = (1 << bitLength) - 1;\n    // bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));\n    // result = clearedWord | bytes32(value << offset);\n    assembly {\n      let mask := sub(shl(bitLength, 1), 1)\n      let clearedWord := and(word, not(shl(offset, mask)))\n      result := or(clearedWord, shl(offset, value))\n    }\n  }\n\n  /// @dev Decodes and returns an unsigned integer with `bitLength` bits, shifted by an offset, from a 256 bit word.\n  function decodeUint(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (uint256 result) {\n    // Equivalent to:\n    // result = uint256(word >> offset) & ((1 << bitLength) - 1);\n    assembly {\n      result := and(shr(offset, word), sub(shl(bitLength, 1), 1))\n    }\n  }\n\n  /// @dev Inserts a signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns\n  /// the new word.\n  ///\n  /// Assumes `value` can be represented using `bitLength` bits.\n  function insertInt(\n    bytes32 word,\n    int256 value,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32) {\n    unchecked {\n      uint256 mask = (1 << bitLength) - 1;\n      bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));\n      // Integer values need masking to remove the upper bits of negative values.\n      return clearedWord | bytes32((uint256(value) & mask) << offset);\n    }\n  }\n\n  /// @dev Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word.\n  function decodeInt(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (int256 result) {\n    unchecked {\n      int256 maxInt = int256((1 << (bitLength - 1)) - 1);\n      uint256 mask = (1 << bitLength) - 1;\n\n      int256 value = int256(uint256(word >> offset) & mask);\n      // In case the decoded value is greater than the max positive integer that can be represented with bitLength\n      // bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit\n      // representation.\n      //\n      // Equivalent to:\n      // result = value > maxInt ? (value | int256(~mask)) : value;\n      assembly {\n        result := or(mul(gt(value, maxInt), not(mask)), value)\n      }\n    }\n  }\n\n  /// @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.\n  function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool result) {\n    // Equivalent to:\n    // result = (uint256(word >> offset) & 1) == 1;\n    assembly {\n      result := and(shr(offset, word), 1)\n    }\n  }\n\n  /// @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new\n  /// word.\n  function insertBool(\n    bytes32 word,\n    bool value,\n    uint256 offset\n  ) internal pure returns (bytes32 result) {\n    // Equivalent to:\n    // bytes32 clearedWord = bytes32(uint256(word) & ~(1 << offset));\n    // bytes32 referenceInsertBool = clearedWord | bytes32(uint256(value ? 1 : 0) << offset);\n    assembly {\n      let clearedWord := and(word, not(shl(offset, 1)))\n      result := or(clearedWord, shl(offset, value))\n    }\n  }\n\n  function clearWordAtPosition(\n    bytes32 word,\n    uint256 offset,\n    uint256 bitLength\n  ) internal pure returns (bytes32 clearedWord) {\n    unchecked {\n      uint256 mask = (1 << bitLength) - 1;\n      clearedWord = bytes32(uint256(word) & ~(mask << offset));\n    }\n  }\n}\n"},"contracts/core/FlashLoans.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.25;\n\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\n\nimport { IERC3156FlashBorrower } from \"../common/ERC3156/IERC3156FlashBorrower.sol\";\nimport { IERC3156FlashLender } from \"../common/ERC3156/IERC3156FlashLender.sol\";\n\nimport { ProtocolFees } from \"./ProtocolFees.sol\";\n\ncontract FlashLoans is ProtocolFees, ReentrancyGuardUpgradeable, IERC3156FlashLender {\n  using SafeERC20 for IERC20;\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when the returned balance after flash loan is not enough.\n  error ErrorInsufficientFlashLoanReturn();\n\n  /// @dev Thrown when the returned value of `ERC3156Callback` is wrong.\n  error ErrorERC3156CallbackFailed();\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The correct value of the return value of `ERC3156FlashBorrower.onFlashLoan`.\n  bytes32 private constant CALLBACK_SUCCESS = keccak256(\"ERC3156FlashBorrower.onFlashLoan\");\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @dev Slots for future use.\n  uint256[50] private _gap;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  function __FlashLoans_init() internal onlyInitializing {}\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc IERC3156FlashLender\n  function maxFlashLoan(address token) external view override returns (uint256) {\n    return IERC20(token).balanceOf(address(this));\n  }\n\n  /// @inheritdoc IERC3156FlashLender\n  function flashFee(address /*token*/, uint256 amount) public view returns (uint256) {\n    return (amount * getFlashLoanFeeRatio()) / FEE_PRECISION;\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IERC3156FlashLender\n  function flashLoan(\n    IERC3156FlashBorrower,\n    address,\n    uint256,\n    bytes calldata\n  ) external nonReentrant whenNotPaused returns (bool) {\n    revert(\"not supported\");\n  }\n}\n"},"contracts/core/PoolManager.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { IERC20Metadata } from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nimport { ICreditNote } from \"../interfaces/ICreditNote.sol\";\nimport { IFxUSDRegeneracy } from \"../interfaces/IFxUSDRegeneracy.sol\";\nimport { ILongPoolManager } from \"../interfaces/ILongPoolManager.sol\";\nimport { ILongPool } from \"../interfaces/ILongPool.sol\";\nimport { IPoolConfiguration } from \"../interfaces/IPoolConfiguration.sol\";\nimport { IPoolManager } from \"../interfaces/IPoolManager.sol\";\nimport { IShortPool } from \"../interfaces/IShortPool.sol\";\nimport { IReservePool } from \"../interfaces/IReservePool.sol\";\nimport { IFxUSDBasePool } from \"../interfaces/IFxUSDBasePool.sol\";\nimport { IRateProvider } from \"../rate-provider/interfaces/IRateProvider.sol\";\nimport { ISmartWalletChecker } from \"../voting-escrow/interfaces/ISmartWalletChecker.sol\";\nimport { WordCodec } from \"../common/codec/WordCodec.sol\";\nimport { AssetManagement } from \"../fund/AssetManagement.sol\";\nimport { FlashLoans } from \"./FlashLoans.sol\";\nimport { ProtocolFees } from \"./ProtocolFees.sol\";\n\ncontract PoolManager is ProtocolFees, FlashLoans, AssetManagement, ILongPoolManager {\n  using EnumerableSet for EnumerableSet.AddressSet;\n  using SafeERC20 for IERC20;\n  using WordCodec for bytes32;\n\n  /**********\n   * Errors *\n   **********/\n\n  error ErrorCollateralExceedCapacity();\n\n  error ErrorDebtExceedCapacity();\n\n  error ErrorPoolNotRegistered();\n\n  error ErrorInvalidPool();\n\n  error ErrorCallerNotFxUSDSave();\n\n  error ErrorRedeemExceedBalance();\n\n  error ErrorInsufficientRedeemedCollateral();\n\n  error ErrorBorrowExceedCapacity();\n\n  error ErrorCallerNotCounterparty();\n\n  error ErrorInvalidLongShortPair();\n\n  error ErrorStableRepayNotAllowed();\n\n  error ErrorInvalidOperation();\n\n  error ErrorRedeemDebtsTooSmall();\n\n  error ErrorRebalanceDebtsTooSmall();\n\n  error ErrorRedeemNotAllowed();\n\n  error ErrorLiquidateDebtsTooSmall();\n\n  error ErrorTopLevelCall();\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The role for emergency operations.\n  bytes32 public constant EMERGENCY_ROLE = keccak256(\"EMERGENCY_ROLE\");\n\n  /// @dev The role for debt reducer.\n  bytes32 public constant DEBT_REDUCER_ROLE = keccak256(\"DEBT_REDUCER_ROLE\");\n\n  /// @dev The role for harvester\n  bytes32 public constant HARVESTER_ROLE = keccak256(\"HARVESTER_ROLE\");\n\n  /// @dev The role for soft/hard liquidation (SP).\n  bytes32 public constant SP_ROLE = keccak256(\"SP_ROLE\");\n\n  /// @dev The key for pool rewards treasury.\n  bytes32 private constant POOL_REWARDS_TREASURY_KEY = keccak256(\"PoolRewardsTreasury\");\n\n  /// @dev The key for pool funding treasury.\n  bytes32 private constant POOL_FUNDING_TREASURY_KEY = keccak256(\"PoolFundingTreasury\");\n\n  /// @dev The precision for token rate.\n  uint256 internal constant PRECISION = 1e18;\n\n  /// @dev The precision for token rate.\n  int256 internal constant PRECISION_I256 = 1e18;\n\n  uint256 private constant COLLATERAL_CAPACITY_OFFSET = 0;\n  uint256 private constant COLLATERAL_BALANCE_OFFSET = 85;\n  uint256 private constant RAW_COLLATERAL_BALANCE_OFFSET = 170;\n  uint256 private constant COLLATERAL_DATA_BITS = 85;\n  uint256 private constant RAW_COLLATERAL_DATA_BITS = 86;\n\n  uint256 private constant DEBT_CAPACITY_OFFSET = 0;\n  uint256 private constant DEBT_BALANCE_OFFSET = 96;\n  uint256 private constant DEBT_DATA_BITS = 96;\n\n  uint256 private constant MIN_REDEEM_DEBTS = 100 ether;\n\n  uint256 private constant MIN_REBALANCE_DEBTS = 1 ether;\n\n  uint256 private constant MIN_LIQUIDATE_DEBTS = 1 ether;\n\n  /***********************\n   * Immutable Variables *\n   ***********************/\n\n  /// @inheritdoc IPoolManager\n  address public immutable fxUSD;\n\n  /// @inheritdoc IPoolManager\n  address public immutable counterparty;\n\n  /// @inheritdoc IPoolManager\n  address public immutable configuration;\n\n  /// @inheritdoc ILongPoolManager\n  address public immutable fxBASE;\n\n  /// @notice The address of smart wallet whitelist.\n  address public immutable whitelist;\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev The struct for pool information.\n  /// @param collateralData The data for collateral.\n  ///   ```text\n  ///   * Field                     Bits    Index       Comments\n  ///   * collateral capacity       85      0           The maximum allowed amount of collateral tokens.\n  ///   * collateral balance        85      85          The amount of collateral tokens deposited.\n  ///   * raw collateral balance    86      170         The amount of raw collateral tokens (without token rate) managed in pool.\n  ///   ```\n  /// @param debtData The data for debt.\n  ///   ```text\n  ///   * Field             Bits    Index       Comments\n  ///   * debt capacity     96      0           The maximum allowed amount of debt tokens.\n  ///   * debt balance      96      96          The amount of debt tokens borrowed.\n  ///   * reserved          64      192         Reserved data.\n  ///   ```\n  struct PoolStruct {\n    bytes32 collateralData;\n    bytes32 debtData;\n  }\n\n  /// @dev The struct for token rate information.\n  /// @param scalar The token scalar to reach 18 decimals.\n  /// @param rateProvider The address of token rate provider.\n  struct TokenRate {\n    uint96 scalar;\n    address rateProvider;\n  }\n\n  /// @dev Memory variables for liquidate or rebalance.\n  /// @param stablePrice The USD price of stable token (with scalar).\n  /// @param scalingFactor The scaling factor for collateral token.\n  /// @param collateralToken The address of collateral token.\n  /// @param rawColls The amount of raw collateral tokens liquidated or rebalanced, including bonus.\n  /// @param bonusRawColls The amount of raw collateral tokens used as bonus.\n  /// @param rawDebts The amount of raw debt tokens liquidated or rebalanced.\n  struct LiquidateOrRebalanceMemoryVar {\n    uint256 stablePrice;\n    uint256 scalingFactor;\n    address collateralToken;\n    uint256 rawColls;\n    uint256 bonusRawColls;\n    uint256 rawDebts;\n  }\n\n  struct OperationMemoryVar {\n    uint256 stablePrice;\n    uint256 poolSupplyFeeRatio;\n    uint256 poolWithdrawFeeRatio;\n    uint256 poolBorrowFeeRatio;\n    uint256 poolRepayFeeRatio;\n    address referral;\n    uint256 referralSupplyFeeRatio;\n    uint256 referralWithdrawFeeRatio;\n    uint256 referralBorrowFeeRatio;\n    uint256 referralRepayFeeRatio;\n  }\n\n  /*********************\n   * Storage Variables *\n   *********************/\n\n  /// @dev The list of registered pools.\n  EnumerableSet.AddressSet private pools;\n\n  /// @notice Mapping to pool address to pool struct.\n  mapping(address => PoolStruct) private poolInfo;\n\n  /// @notice Mapping from pool address to rewards splitter.\n  /// @custom:deprecated This field is no longer used.\n  mapping(address => address) public rewardSplitter;\n\n  /// @notice Mapping from token address to token rate struct.\n  mapping(address => TokenRate) public tokenRates;\n\n  /// @notice The threshold for permissioned liquidate or rebalance.\n  uint256 public permissionedLiquidationThreshold;\n\n  /// @notice Mapping from pool address to corresponding short allocation.\n  mapping(address => uint256) public shortBorrowCapacityRatio;\n\n  /*************\n   * Modifiers *\n   *************/\n\n  modifier onlyRegisteredPool(address pool) {\n    if (!pools.contains(pool)) revert ErrorPoolNotRegistered();\n    _;\n  }\n\n  modifier onlyCounterparty() {\n    if (counterparty != _msgSender()) {\n      revert ErrorCallerNotCounterparty();\n    }\n    _;\n  }\n\n  modifier onlyTopLevelCall() {\n    uint256 codesize = msg.sender.code.length;\n    if (whitelist != address(0) && (codesize > 0 || msg.sender != tx.origin)) {\n      if (!ISmartWalletChecker(whitelist).check(msg.sender)) {\n        revert ErrorTopLevelCall();\n      }\n    }\n    _;\n  }\n\n  modifier lock() {\n    IPoolConfiguration(configuration).lock(address(this), msg.sig);\n    _;\n  }\n\n  /***************\n   * Constructor *\n   ***************/\n\n  constructor(address _fxUSD, address _fxBASE, address _counterparty, address _configuration, address _whitelist) {\n    fxUSD = _fxUSD;\n    fxBASE = _fxBASE;\n    counterparty = _counterparty;\n    configuration = _configuration;\n    whitelist = _whitelist;\n  }\n\n  function initialize(\n    address admin,\n    uint256 _expenseRatio,\n    uint256 _harvesterRatio,\n    uint256 _flashLoanFeeRatio,\n    address _treasury,\n    address _revenuePool,\n    address _reservePool\n  ) external initializer {\n    // comment out to reduce code size, since these functions are no-op for now.\n    // __Context_init();\n    // __AccessControl_init();\n    // __ERC165_init();\n\n    _grantRole(DEFAULT_ADMIN_ROLE, admin);\n\n    __ProtocolFees_init(_expenseRatio, _harvesterRatio, _flashLoanFeeRatio, _treasury, _revenuePool, _reservePool);\n    __FlashLoans_init();\n\n    // default 10000 fxUSD\n    // _updateThreshold(10000 ether);\n  }\n\n  /*\n  function initializeV2(address pool) external onlyRegisteredPool(pool) reinitializer(2) {\n    // fix state of pool\n    address collateralToken = ILongPool(pool).collateralToken();\n    uint256 scalingFactor = _getTokenScalingFactor(collateralToken);\n    uint256 rawCollaterals = ILongPool(pool).getTotalRawCollaterals();\n    uint256 collaterals = _scaleDown(rawCollaterals, scalingFactor);\n    bytes32 data = poolInfo[pool].collateralData;\n    data = data.insertUint(collaterals, COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);\n    poolInfo[pool].collateralData = data.insertUint(\n      rawCollaterals,\n      RAW_COLLATERAL_BALANCE_OFFSET,\n      RAW_COLLATERAL_DATA_BITS\n    );\n  }\n  */\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the pool information.\n  /// @param pool The address of pool to query.\n  /// @return collateralCapacity The maximum allowed amount of collateral tokens.\n  /// @return collateralBalance The amount of collateral tokens deposited.\n  /// @return rawCollateral The amount of raw collateral tokens deposited.\n  /// @return debtCapacity The maximum allowed amount of debt tokens.\n  /// @return debtBalance The amount of debt tokens borrowed.\n  function getPoolInfo(\n    address pool\n  )\n    external\n    view\n    returns (\n      uint256 collateralCapacity,\n      uint256 collateralBalance,\n      uint256 rawCollateral,\n      uint256 debtCapacity,\n      uint256 debtBalance\n    )\n  {\n    bytes32 data = poolInfo[pool].collateralData;\n    collateralCapacity = data.decodeUint(COLLATERAL_CAPACITY_OFFSET, COLLATERAL_DATA_BITS);\n    collateralBalance = data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);\n    rawCollateral = data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);\n    data = poolInfo[pool].debtData;\n    debtCapacity = data.decodeUint(DEBT_CAPACITY_OFFSET, DEBT_DATA_BITS);\n    debtBalance = data.decodeUint(DEBT_BALANCE_OFFSET, DEBT_DATA_BITS);\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IPoolManager\n  function operate(address pool, uint256 positionId, int256 newColl, int256 newDebt) external returns (uint256) {\n    return operate(pool, positionId, newColl, newDebt, false);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function operate(\n    address pool,\n    uint256 positionId,\n    int256 newColl,\n    int256 newDebt,\n    bool useStable\n  ) public onlyRegisteredPool(pool) nonReentrant whenNotPaused onlyTopLevelCall lock returns (uint256) {\n    OperationMemoryVar memory vars;\n\n    if (useStable) {\n      if (!IPoolConfiguration(configuration).isStableRepayAllowed()) revert ErrorStableRepayNotAllowed();\n      if (newColl > 0 || newDebt >= 0 || positionId == 0) revert ErrorInvalidOperation();\n      vars.stablePrice = IFxUSDBasePool(fxBASE).getStableTokenPriceWithScale();\n    }\n\n    address collateralToken = ILongPool(pool).collateralToken();\n    uint256 scalingFactor = _getTokenScalingFactor(collateralToken);\n\n    (\n      vars.poolSupplyFeeRatio,\n      vars.poolWithdrawFeeRatio,\n      vars.poolBorrowFeeRatio,\n      vars.poolRepayFeeRatio\n    ) = IPoolConfiguration(configuration).getPoolFeeRatio(pool, _msgSender());\n\n    // in case of supply, we deduct the fee here first and transfer the collateral to pool.\n    if (newColl > 0) {\n      newColl = int256(_handleSupply(pool, collateralToken, uint256(newColl), vars.poolSupplyFeeRatio));\n    }\n\n    int256 newRawColl = newColl;\n    int256 newRawDebt = newDebt;\n    if (newRawColl != type(int256).min) {\n      newRawColl = _scaleUp(newRawColl, scalingFactor);\n    }\n    if (useStable && newRawDebt != type(int256).min) {\n      newRawDebt = _scaleUp(newRawDebt, vars.stablePrice);\n    }\n\n    // @dev the `protocolFees` is deprecated, it is always zero now.\n    (positionId, newRawColl, newRawDebt, ) = ILongPool(pool).operate(positionId, newRawColl, newRawDebt, _msgSender());\n\n    newColl = _scaleDown(newRawColl, scalingFactor);\n    _changePoolDebts(pool, newRawDebt);\n    if (newRawColl > 0) {\n      _changePoolCollateral(pool, newColl, newRawColl);\n    } else if (newRawColl < 0) {\n      _handleWithdraw(pool, collateralToken, uint256(-newColl), uint256(-newRawColl), vars.poolWithdrawFeeRatio);\n    }\n\n    if (newRawDebt > 0) {\n      _handleBorrow(uint256(newRawDebt), vars.poolBorrowFeeRatio);\n    } else if (newRawDebt < 0) {\n      _handleRepay(uint256(-newRawDebt), vars.poolRepayFeeRatio, vars.stablePrice);\n    }\n\n    emit Operate(pool, positionId, newColl, newRawDebt, 0);\n\n    return positionId;\n  }\n\n  /// @inheritdoc IPoolManager\n  function redeem(\n    address pool,\n    uint256 debts,\n    uint256 minColls\n  ) external onlyRegisteredPool(pool) nonReentrant whenNotPaused lock returns (uint256 actualDebts, uint256 colls) {\n    if (debts > IERC20(fxUSD).balanceOf(_msgSender())) {\n      revert ErrorRedeemExceedBalance();\n    }\n    if (debts < MIN_REDEEM_DEBTS) {\n      revert ErrorRedeemDebtsTooSmall();\n    }\n    if (!IPoolConfiguration(configuration).isRedeemAllowed()) {\n      revert ErrorRedeemNotAllowed();\n    }\n\n    uint256 rawColls;\n    (actualDebts, rawColls) = ILongPool(pool).redeem(debts);\n    debts = actualDebts;\n\n    address collateralToken = ILongPool(pool).collateralToken();\n    uint256 scalingFactor = _getTokenScalingFactor(collateralToken);\n    colls = _scaleDown(rawColls, scalingFactor);\n\n    _changePoolCollateral(pool, -int256(colls), -int256(rawColls));\n    _changePoolDebts(pool, -int256(debts));\n\n    // @dev use unchecked to reduce code size and gas\n    uint256 protocolFees;\n    unchecked {\n      protocolFees = (colls * getRedeemFeeRatio()) / FEE_PRECISION;\n      _accumulatePoolMiscFee(pool, protocolFees);\n      colls -= protocolFees;\n    }\n    if (colls < minColls) revert ErrorInsufficientRedeemedCollateral();\n\n    _transferCollateralOut(pool, collateralToken, colls, _msgSender());\n    IFxUSDRegeneracy(fxUSD).burn(_msgSender(), debts);\n\n    emit Redeem(pool, colls, debts, protocolFees);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function rebalance(\n    address pool,\n    address receiver,\n    int16 tick,\n    uint256 maxFxUSD,\n    uint256 maxStable\n  )\n    external\n    onlyRegisteredPool(pool)\n    nonReentrant\n    whenNotPaused\n    onlyRole(SP_ROLE)\n    returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed)\n  {\n    LiquidateOrRebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(pool);\n    // @dev use unchecked to reduce code size and gas\n    unchecked {\n      uint256 maxRawDebts = maxFxUSD + _scaleUp(maxStable, op.stablePrice);\n      if (maxRawDebts < MIN_REBALANCE_DEBTS) {\n        revert ErrorRebalanceDebtsTooSmall();\n      }\n      ILongPool.RebalanceResult memory result = ILongPool(pool).rebalance(tick, maxRawDebts);\n      op.rawColls = result.rawColls + result.bonusRawColls;\n      op.bonusRawColls = result.bonusRawColls;\n      op.rawDebts = result.rawDebts;\n    }\n    (colls, fxUSDUsed, stableUsed) = _afterRebalanceOrLiquidate(pool, maxFxUSD, op, receiver);\n\n    emit RebalanceTick(pool, tick, colls, fxUSDUsed, stableUsed);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function rebalance(\n    address pool,\n    address receiver,\n    uint256 maxFxUSD,\n    uint256 maxStable\n  )\n    external\n    onlyRegisteredPool(pool)\n    nonReentrant\n    whenNotPaused\n    onlyRole(SP_ROLE)\n    lock\n    returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed)\n  {\n    LiquidateOrRebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(pool);\n    // @dev use unchecked to reduce code size and gas\n    unchecked {\n      uint256 maxRawDebts = maxFxUSD + _scaleUp(maxStable, op.stablePrice);\n      if (maxRawDebts < MIN_REBALANCE_DEBTS) {\n        revert ErrorRebalanceDebtsTooSmall();\n      }\n      ILongPool.RebalanceResult memory result = ILongPool(pool).rebalance(maxRawDebts);\n      op.rawColls = result.rawColls + result.bonusRawColls;\n      op.bonusRawColls = result.bonusRawColls;\n      op.rawDebts = result.rawDebts;\n    }\n    (colls, fxUSDUsed, stableUsed) = _afterRebalanceOrLiquidate(pool, maxFxUSD, op, receiver);\n\n    emit Rebalance(pool, colls, fxUSDUsed, stableUsed);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function liquidate(\n    address pool,\n    address receiver,\n    uint256 maxFxUSD,\n    uint256 maxStable\n  )\n    external\n    onlyRegisteredPool(pool)\n    nonReentrant\n    whenNotPaused\n    onlyRole(SP_ROLE)\n    lock\n    returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed)\n  {\n    LiquidateOrRebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(pool);\n    uint256 maxRawDebts = maxFxUSD + _scaleUp(maxStable, op.stablePrice);\n    if (maxRawDebts < MIN_LIQUIDATE_DEBTS) {\n      revert ErrorLiquidateDebtsTooSmall();\n    }\n    {\n      ILongPool.LiquidateResult memory result;\n      uint256 reservedRawColls = IReservePool(reservePool).getBalance(op.collateralToken);\n      reservedRawColls = _scaleUp(reservedRawColls, op.scalingFactor);\n\n      // @dev use unchecked to reduce code size and gas\n      unchecked {\n        result = ILongPool(pool).liquidate(maxRawDebts, reservedRawColls);\n        op.rawColls = result.rawColls + result.bonusRawColls;\n        op.bonusRawColls = result.bonusRawColls;\n        op.rawDebts = result.rawDebts;\n      }\n\n      // take bonus or shortfall from reserve pool\n      uint256 bonusFromReserve = result.bonusFromReserve;\n      if (bonusFromReserve > 0) {\n        bonusFromReserve = _scaleDown(result.bonusFromReserve, op.scalingFactor);\n        IReservePool(reservePool).requestBonus(ILongPool(pool).collateralToken(), address(this), bonusFromReserve);\n\n        // increase pool reserve first\n        _changePoolCollateral(pool, int256(bonusFromReserve), int256(result.bonusFromReserve));\n      }\n    }\n\n    (colls, fxUSDUsed, stableUsed) = _afterRebalanceOrLiquidate(pool, maxFxUSD, op, receiver);\n\n    emit Liquidate(pool, colls, fxUSDUsed, stableUsed);\n  }\n\n  /// @inheritdoc IPoolManager\n  function harvest(\n    address pool\n  )\n    external\n    onlyRegisteredPool(pool)\n    onlyRole(HARVESTER_ROLE)\n    nonReentrant\n    returns (uint256 amountRewards, uint256 amountFunding)\n  {\n    address collateralToken = ILongPool(pool).collateralToken();\n    uint256 scalingFactor = _getTokenScalingFactor(collateralToken);\n\n    uint256 collateralRecorded;\n    uint256 rawCollateralRecorded;\n    {\n      bytes32 data = poolInfo[pool].collateralData;\n      collateralRecorded = data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);\n      rawCollateralRecorded = data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);\n    }\n    uint256 performanceFee;\n    uint256 harvestBounty;\n    // compute funding\n    uint256 rawCollateral = ILongPool(pool).getTotalRawCollaterals();\n    if (rawCollateralRecorded > rawCollateral) {\n      unchecked {\n        amountFunding = _scaleDown(rawCollateralRecorded - rawCollateral, scalingFactor);\n        _changePoolCollateral(pool, -int256(amountFunding), -int256(rawCollateralRecorded - rawCollateral));\n\n        performanceFee = (getFundingExpenseRatio() * amountFunding) / FEE_PRECISION;\n        harvestBounty = (getHarvesterRatio() * amountFunding) / FEE_PRECISION;\n        amountFunding -= harvestBounty + performanceFee;\n      }\n      _transferCollateralOut(\n        pool,\n        collateralToken,\n        amountFunding,\n        IPoolConfiguration(configuration).registry(POOL_FUNDING_TREASURY_KEY)\n      );\n\n      // recorded data changed, update local cache\n      {\n        bytes32 data = poolInfo[pool].collateralData;\n        collateralRecorded = data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);\n        rawCollateralRecorded = data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);\n      }\n    }\n    // compute rewards\n    rawCollateral = _scaleUp(collateralRecorded, scalingFactor);\n    if (rawCollateral > rawCollateralRecorded) {\n      unchecked {\n        amountRewards = _scaleDown(rawCollateral - rawCollateralRecorded, scalingFactor);\n        _changePoolCollateral(pool, -int256(amountRewards), 0);\n\n        {\n          uint256 performanceFeeRewards = (getRewardsExpenseRatio() * amountRewards) / FEE_PRECISION;\n          uint256 harvestBountyRewards = (getHarvesterRatio() * amountRewards) / FEE_PRECISION;\n          amountRewards -= harvestBountyRewards + performanceFeeRewards;\n          performanceFee += performanceFeeRewards;\n          harvestBounty += harvestBountyRewards;\n        }\n\n        _transferCollateralOut(\n          pool,\n          collateralToken,\n          amountRewards,\n          IPoolConfiguration(configuration).registry(POOL_REWARDS_TREASURY_KEY)\n        );\n      }\n    }\n\n    // transfer performance fee to treasury\n    if (performanceFee > 0) {\n      _transferCollateralOut(pool, collateralToken, performanceFee, treasury);\n    }\n    // transfer various fees to revenue pool\n    _takeAccumulatedPoolFee(pool);\n    // transfer harvest bounty\n    if (harvestBounty > 0) {\n      _transferCollateralOut(pool, collateralToken, harvestBounty, _msgSender());\n    }\n    emit Harvest(_msgSender(), pool, amountRewards, amountFunding, performanceFee, harvestBounty);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function borrow(\n    address longPool,\n    address shortPool,\n    uint256 amount\n  ) external onlyCounterparty onlyRegisteredPool(longPool) nonReentrant {\n    address creditNote = IShortPool(shortPool).creditNote();\n    address collateralToken = ILongPool(longPool).collateralToken();\n    uint256 scalingFactor = _getTokenScalingFactor(collateralToken);\n    {\n      uint256 rawCollateral = ILongPool(longPool).getTotalRawCollaterals();\n      uint256 collateral = _scaleDown(rawCollateral, scalingFactor);\n      uint256 borrowed = IERC20(creditNote).totalSupply();\n      if ((collateral * shortBorrowCapacityRatio[longPool]) / PRECISION < borrowed + amount) {\n        revert ErrorBorrowExceedCapacity();\n      }\n    }\n\n    _transferOut(collateralToken, amount, counterparty);\n    ICreditNote(creditNote).mint(address(this), amount);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function repay(\n    address longPool,\n    address shortPool,\n    uint256 amount\n  ) external onlyCounterparty onlyRegisteredPool(longPool) nonReentrant {\n    address collateralToken = ILongPool(longPool).collateralToken();\n    _transferFrom(collateralToken, counterparty, address(this), amount);\n    ICreditNote(IShortPool(shortPool).creditNote()).burn(address(this), amount);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function repayByCreditNote(\n    address longPool,\n    address shortPool,\n    uint256 amount\n  ) external onlyCounterparty onlyRegisteredPool(longPool) nonReentrant {\n    ICreditNote(IShortPool(shortPool).creditNote()).burn(counterparty, amount);\n  }\n\n  /// @inheritdoc ILongPoolManager\n  function liquidateShortPool(\n    address longPool,\n    address shortPool,\n    uint256 amountFxUSD,\n    uint256 totalBorrowed\n  ) external onlyCounterparty onlyRegisteredPool(longPool) nonReentrant returns (uint256 shortfall) {\n    address collateralToken = ILongPool(longPool).collateralToken();\n    uint256 scalingFactor = _getTokenScalingFactor(collateralToken);\n\n    (, uint256 redeemedRawColls) = ILongPool(longPool).redeem(amountFxUSD);\n    uint256 redeemedColls = _scaleDown(redeemedRawColls, scalingFactor);\n\n    shortfall = totalBorrowed - redeemedColls;\n    uint256 rawShortfall = _scaleUp(shortfall, scalingFactor);\n\n    // reduce collateral in long pool\n    ILongPool(longPool).reduceCollateral(rawShortfall);\n    _changePoolCollateral(longPool, -int256(shortfall), -int256(rawShortfall));\n\n    // burn fxUSD in short pool pool manager\n    IFxUSDRegeneracy(fxUSD).burn(counterparty, amountFxUSD);\n\n    // burn all credit note tokens in pool manager.\n    // for tokens outside of pool manager, the short pool is killed, the tokens are useless.\n    address creditNote = IShortPool(shortPool).creditNote();\n    uint256 creditNoteAmount = IERC20(creditNote).balanceOf(address(this));\n    if (creditNoteAmount > 0) {\n      ICreditNote(creditNote).burn(address(this), creditNoteAmount);\n    }\n  }\n\n  /// @inheritdoc IPoolManager\n  /// @dev This is a risky operation, only allowed by whitelisted caller.\n  function reduceDebt(\n    address pool,\n    uint256 amount\n  ) external onlyRegisteredPool(pool) onlyRole(DEBT_REDUCER_ROLE) nonReentrant {\n    IFxUSDRegeneracy(fxUSD).burn(_msgSender(), amount);\n    ILongPool(pool).reduceDebt(amount);\n\n    _changePoolDebts(pool, -int256(amount));\n\n    emit ReduceDebt(pool, amount);\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Pause or unpause the system.\n  /// @param status The pause status to update.\n  function setPause(bool status) external onlyRole(EMERGENCY_ROLE) {\n    if (status) _pause();\n    else _unpause();\n  }\n\n  /// @notice Register a new pool with reward splitter.\n  /// @param pool The address of pool.\n  /// @param collateralCapacity The capacity for collateral token.\n  /// @param debtCapacity The capacity for debt token.\n  function registerPool(address pool, uint96 collateralCapacity, uint96 debtCapacity) external onlyRole(OPERATOR_ROLE) {\n    // @dev remove this line to reduce codesize, caller should make sure the pool is correct.\n    // if (fxUSD != ILongPool(pool).fxUSD()) revert ErrorInvalidPool();\n\n    if (pools.add(pool)) {\n      emit RegisterPool(pool);\n\n      _updatePoolCapacity(pool, collateralCapacity, debtCapacity);\n    }\n  }\n\n  /// @notice Update rate provider for the given token.\n  /// @param token The address of the token.\n  /// @param provider The address of corresponding rate provider.\n  function updateRateProvider(address token, address provider) external onlyRole(OPERATOR_ROLE) {\n    uint256 scale = 10 ** (18 - IERC20Metadata(token).decimals());\n    tokenRates[token] = TokenRate(uint96(scale), provider);\n\n    emit UpdateTokenRate(token, scale, provider);\n  }\n\n  /// @notice Update the pool capacity.\n  /// @param pool The address of fx pool.\n  /// @param collateralCapacity The capacity for collateral token.\n  /// @param debtCapacity The capacity for debt token.\n  function updatePoolCapacity(\n    address pool,\n    uint96 collateralCapacity,\n    uint96 debtCapacity\n  ) external onlyRole(OPERATOR_ROLE) onlyRegisteredPool(pool) {\n    _updatePoolCapacity(pool, collateralCapacity, debtCapacity);\n  }\n\n  /// @notice Update threshold for permissionless liquidation.\n  /// @param newThreshold The value of new threshold.\n  function updateThreshold(uint256 newThreshold) external onlyRole(OPERATOR_ROLE) {\n    _updateThreshold(newThreshold);\n  }\n\n  /// @notice Update the short borrow capacity ratio for the given long pool.\n  /// @param longPool The address of the long pool.\n  /// @param newRatio The new short borrow capacity ratio.\n  function updateShortBorrowCapacityRatio(address longPool, uint256 newRatio) external onlyRole(OPERATOR_ROLE) {\n    uint256 oldRatio = shortBorrowCapacityRatio[longPool];\n    shortBorrowCapacityRatio[longPool] = newRatio;\n\n    emit UpdateShortBorrowCapacityRatio(longPool, oldRatio, newRatio);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @inheritdoc ProtocolFees\n  function _takeAccumulatedPoolFee(address pool) internal virtual override {\n    address collateralToken = ILongPool(pool).collateralToken();\n    uint256 fees = accumulatedPoolOpenFees[pool];\n    if (fees > 0) {\n      _transferCollateralOut(pool, collateralToken, fees, openRevenuePool);\n      accumulatedPoolOpenFees[pool] = 0;\n    }\n    fees = accumulatedPoolCloseFees[pool];\n    if (fees > 0) {\n      _transferCollateralOut(pool, collateralToken, fees, closeRevenuePool);\n      accumulatedPoolCloseFees[pool] = 0;\n    }\n    fees = accumulatedPoolMiscFees[pool];\n    if (fees > 0) {\n      _transferCollateralOut(pool, collateralToken, fees, miscRevenuePool);\n      accumulatedPoolMiscFees[pool] = 0;\n    }\n  }\n\n  /// @dev Internal function to update the pool capacity.\n  /// @param pool The address of fx pool.\n  /// @param collateralCapacity The capacity for collateral token.\n  /// @param debtCapacity The capacity for debt token.\n  function _updatePoolCapacity(address pool, uint96 collateralCapacity, uint96 debtCapacity) internal {\n    poolInfo[pool].collateralData = poolInfo[pool].collateralData.insertUint(\n      collateralCapacity,\n      COLLATERAL_CAPACITY_OFFSET,\n      COLLATERAL_DATA_BITS\n    );\n    poolInfo[pool].debtData = poolInfo[pool].debtData.insertUint(debtCapacity, DEBT_CAPACITY_OFFSET, DEBT_DATA_BITS);\n\n    emit UpdatePoolCapacity(pool, collateralCapacity, debtCapacity);\n  }\n\n  /// @dev Internal function to update threshold for permissionless liquidation.\n  /// @param newThreshold The value of new threshold.\n  function _updateThreshold(uint256 newThreshold) internal {\n    uint256 oldThreshold = permissionedLiquidationThreshold;\n    permissionedLiquidationThreshold = newThreshold;\n\n    emit UpdatePermissionedLiquidationThreshold(oldThreshold, newThreshold);\n  }\n\n  /// @dev Internal function to scaler up for `uint256`.\n  function _scaleUp(uint256 value, uint256 scale) internal pure returns (uint256) {\n    return (value * scale) / PRECISION;\n  }\n\n  /// @dev Internal function to scaler up for `int256`.\n  function _scaleUp(int256 value, uint256 scale) internal pure returns (int256) {\n    return (value * int256(scale)) / PRECISION_I256;\n  }\n\n  /// @dev Internal function to scaler down for `uint256`, rounding down.\n  function _scaleDown(uint256 value, uint256 scale) internal pure returns (uint256) {\n    return (value * PRECISION) / scale;\n  }\n\n  /// @dev Internal function to scaler down for `uint256`, rounding up.\n  function _scaleDownRoundingUp(uint256 value, uint256 scale) internal pure returns (uint256) {\n    return (value * PRECISION + scale - 1) / scale;\n  }\n\n  /// @dev Internal function to scaler down for `int256`.\n  function _scaleDown(int256 value, uint256 scale) internal pure returns (int256) {\n    return (value * PRECISION_I256) / int256(scale);\n  }\n\n  /// @dev Internal function to handle supply.\n  /// @param pool The address of pool.\n  /// @param collateralToken The address of collateral token.\n  /// @param newColl The amount of collateral token supplied.\n  /// @param poolFeeRatio The pool supply fee ratio, multiplied by 10^9.\n  /// @return newColl The amount of collateral token supplied after fees.\n  function _handleSupply(\n    address pool,\n    address collateralToken,\n    uint256 newColl,\n    uint256 poolFeeRatio\n  ) internal returns (uint256) {\n    // handle supply fee for protocol and referral, it is safe to use unchecked here\n    unchecked {\n      uint256 poolFee = (newColl * poolFeeRatio) / FEE_PRECISION;\n      _accumulatePoolOpenFee(pool, poolFee);\n      _transferFrom(collateralToken, _msgSender(), address(this), newColl);\n      return newColl - poolFee;\n    }\n  }\n\n  /// @dev Internal function to handle withdraw.\n  /// @param pool The address of pool.\n  /// @param collateralToken The address of collateral token.\n  /// @param newColl The amount of collateral token withdrawn.\n  /// @param newRawColl The amount of raw collateral token withdrawn.\n  /// @param poolFeeRatio The pool withdraw fee ratio, multiplied by 10^9.\n  function _handleWithdraw(\n    address pool,\n    address collateralToken,\n    uint256 newColl,\n    uint256 newRawColl,\n    uint256 poolFeeRatio\n  ) internal {\n    _changePoolCollateral(pool, -int256(newColl), -int256(newRawColl));\n\n    // handle withdraw fee for protocol and referral, it is safe to use unchecked here\n    unchecked {\n      uint256 poolFee = (newColl * poolFeeRatio) / FEE_PRECISION;\n      if (poolFee > 0) {\n        _accumulatePoolCloseFee(pool, poolFee);\n      }\n      _transferCollateralOut(pool, collateralToken, newColl - poolFee, _msgSender());\n    }\n  }\n\n  /// @dev Internal function to handle borrow.\n  /// @param newDebt The amount of fxUSD borrowed.\n  /// @param poolFeeRatio The pool borrow fee ratio, multiplied by 10^9.\n  function _handleBorrow(uint256 newDebt, uint256 poolFeeRatio) internal {\n    // handle borrow fee for protocol and referral, it is safe to use unchecked here\n    unchecked {\n      uint256 poolFee = (newDebt * poolFeeRatio) / FEE_PRECISION;\n      if (poolFee > 0) {\n        IFxUSDRegeneracy(fxUSD).mint(openRevenuePool, poolFee);\n      }\n      IFxUSDRegeneracy(fxUSD).mint(_msgSender(), newDebt - poolFee);\n    }\n  }\n\n  /// @dev Internal function to handle repay.\n  /// @param newRawDebt The amount of fxUSD repaid.\n  /// @param poolFeeRatio The pool repay fee ratio, multiplied by 10^9.\n  function _handleRepay(uint256 newRawDebt, uint256 poolFeeRatio, uint256 stablePrice) internal {\n    uint256 newDebt = newRawDebt;\n    if (stablePrice != 0) {\n      newDebt = _scaleDown(newRawDebt, stablePrice);\n    }\n    // handle repay fee for protocol and referral, it is safe to use unchecked here\n    unchecked {\n      uint256 poolFee = (newDebt * poolFeeRatio) / FEE_PRECISION;\n      if (stablePrice == 0) {\n        if (poolFee > 0) {\n          IFxUSDRegeneracy(fxUSD).mint(closeRevenuePool, poolFee);\n        }\n        IFxUSDRegeneracy(fxUSD).burn(_msgSender(), newDebt + poolFee);\n      } else {\n        address stableToken = IFxUSDBasePool(fxBASE).stableToken();\n        _transferFrom(stableToken, _msgSender(), closeRevenuePool, poolFee);\n        _transferFrom(stableToken, _msgSender(), fxUSD, newDebt);\n        IFxUSDRegeneracy(fxUSD).onRebalanceWithStable(newDebt, newRawDebt);\n      }\n    }\n  }\n\n  /// @dev Internal function to prepare variables before rebalance or liquidate.\n  /// @param pool The address of pool to liquidate or rebalance.\n  function _beforeRebalanceOrLiquidate(address pool) internal view returns (LiquidateOrRebalanceMemoryVar memory op) {\n    op.stablePrice = IFxUSDBasePool(fxBASE).getStableTokenPriceWithScale();\n    op.collateralToken = ILongPool(pool).collateralToken();\n    op.scalingFactor = _getTokenScalingFactor(op.collateralToken);\n  }\n\n  /// @dev Internal function to do actions after rebalance or liquidate.\n  /// @param pool The address of pool to liquidate or rebalance.\n  /// @param maxFxUSD The maximum amount of fxUSD can be used.\n  /// @param op The memory helper variable.\n  /// @param receiver The address collateral token receiver.\n  /// @return colls The actual amount of collateral token rebalanced or liquidated.\n  /// @return fxUSDUsed The amount of fxUSD used.\n  /// @return stableUsed The amount of stable token (a.k.a USDC) used.\n  function _afterRebalanceOrLiquidate(\n    address pool,\n    uint256 maxFxUSD,\n    LiquidateOrRebalanceMemoryVar memory op,\n    address receiver\n  ) internal returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed) {\n    colls = _scaleDown(op.rawColls, op.scalingFactor);\n    _changePoolCollateral(pool, -int256(colls), -int256(op.rawColls));\n    _changePoolDebts(pool, -int256(op.rawDebts));\n\n    // burn fxUSD or transfer USDC\n    fxUSDUsed = op.rawDebts;\n    if (fxUSDUsed > maxFxUSD) {\n      // rounding up here\n      stableUsed = _scaleDownRoundingUp(fxUSDUsed - maxFxUSD, op.stablePrice);\n      fxUSDUsed = maxFxUSD;\n    }\n    if (fxUSDUsed > 0) {\n      IFxUSDRegeneracy(fxUSD).burn(_msgSender(), fxUSDUsed);\n    }\n    if (stableUsed > 0) {\n      if (!IPoolConfiguration(configuration).isStableRepayAllowed()) revert ErrorStableRepayNotAllowed();\n      _transferFrom(IFxUSDBasePool(fxBASE).stableToken(), _msgSender(), fxUSD, stableUsed);\n      IFxUSDRegeneracy(fxUSD).onRebalanceWithStable(stableUsed, op.rawDebts - maxFxUSD);\n    }\n\n    // transfer collateral\n    uint256 protocolRevenue = (_scaleDown(op.bonusRawColls, op.scalingFactor) * getLiquidationExpenseRatio()) /\n      FEE_PRECISION;\n    _accumulatePoolMiscFee(pool, protocolRevenue);\n    unchecked {\n      colls -= protocolRevenue;\n    }\n    _transferCollateralOut(pool, op.collateralToken, colls, receiver);\n  }\n\n  /// @dev Internal function to update collateral balance.\n  function _changePoolCollateral(address pool, int256 delta, int256 rawDelta) internal {\n    bytes32 data = poolInfo[pool].collateralData;\n    uint256 capacity = data.decodeUint(COLLATERAL_CAPACITY_OFFSET, COLLATERAL_DATA_BITS);\n    uint256 balance = uint256(int256(data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS)) + delta);\n    if (balance > capacity) revert ErrorCollateralExceedCapacity();\n    data = data.insertUint(balance, COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);\n    balance = uint256(int256(data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS)) + rawDelta);\n    poolInfo[pool].collateralData = data.insertUint(balance, RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);\n  }\n\n  /// @dev Internal function to update debt balance.\n  function _changePoolDebts(address pool, int256 delta) internal {\n    bytes32 data = poolInfo[pool].debtData;\n    uint256 capacity = data.decodeUint(DEBT_CAPACITY_OFFSET, DEBT_DATA_BITS);\n    uint256 balance = uint256(int256(data.decodeUint(DEBT_BALANCE_OFFSET, DEBT_DATA_BITS)) + delta);\n    if (balance > capacity) revert ErrorDebtExceedCapacity();\n    poolInfo[pool].debtData = data.insertUint(balance, DEBT_BALANCE_OFFSET, DEBT_DATA_BITS);\n  }\n\n  /// @dev Internal function to get token scaling factor.\n  function _getTokenScalingFactor(address token) internal view returns (uint256 value) {\n    address rateProvider = tokenRates[token].rateProvider;\n    value = tokenRates[token].scalar;\n    unchecked {\n      if (rateProvider != address(0)) {\n        value *= IRateProvider(rateProvider).getRate();\n      } else {\n        value *= PRECISION;\n      }\n    }\n  }\n\n  /// @dev Internal function to get pool collateral info.\n  /// @param pool The address of pool.\n  /// @return collateralCapacity The capacity for collateral token.\n  /// @return collateralBalance The balance for collateral token.\n  /// @return rawCollateral The raw collateral balance for collateral token.\n  function _getPoolCollateralInfo(\n    address pool\n  ) internal view returns (uint256 collateralCapacity, uint256 collateralBalance, uint256 rawCollateral) {\n    bytes32 data = poolInfo[pool].collateralData;\n    collateralCapacity = data.decodeUint(COLLATERAL_CAPACITY_OFFSET, COLLATERAL_DATA_BITS);\n    collateralBalance = data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);\n    rawCollateral = data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);\n  }\n\n  /// @dev Internal function to transfer collateral out.\n  /// @param pool The address of pool.\n  /// @param collateralToken The address of collateral token.\n  /// @param scaledAmount The scaled amount of collateral token.\n  /// @param receiver The address of receiver.\n  function _transferCollateralOut(\n    address pool,\n    address collateralToken,\n    uint256 scaledAmount,\n    address receiver\n  ) internal {\n    address shortPool = ILongPool(pool).counterparty();\n    // check if current collateral is enough, if not use debt token to cover\n    if (shortPool != address(0)) {\n      uint256 balance = _balanceOf(collateralToken);\n      if (scaledAmount <= balance) {\n        _transferOut(collateralToken, scaledAmount, receiver);\n      } else {\n        address creditNote = IShortPool(shortPool).creditNote();\n        uint256 shortfall = scaledAmount - balance;\n        IERC20(creditNote).safeTransfer(receiver, shortfall);\n        _transferOut(collateralToken, balance, receiver);\n      }\n    } else {\n      _transferOut(collateralToken, scaledAmount, receiver);\n    }\n  }\n\n  /// @dev Internal function to transfer token from `msg.sender` to receiver.\n  /// @param token The address of token.\n  /// @param sender The address of sender.\n  /// @param receiver The address of receiver.\n  /// @param amount The amount of token.\n  function _transferFrom(address token, address sender, address receiver, uint256 amount) internal {\n    if (amount > 0) {\n      IERC20(token).safeTransferFrom(sender, receiver, amount);\n    }\n  }\n}\n"},"contracts/core/ProtocolFees.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport { AccessControlUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol\";\nimport { PausableUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\n\nimport { IPool } from \"../interfaces/IPool.sol\";\nimport { IProtocolFees } from \"../interfaces/IProtocolFees.sol\";\n\nimport { WordCodec } from \"../common/codec/WordCodec.sol\";\n\nabstract contract ProtocolFees is AccessControlUpgradeable, PausableUpgradeable, IProtocolFees {\n  using SafeERC20 for IERC20;\n  using WordCodec for bytes32;\n\n  /**********\n   * Errors *\n   **********/\n\n  /// @dev Thrown when the given address is zero.\n  error ErrorZeroAddress();\n\n  /// @dev Thrown when the given value exceeds maximum value.\n  error ErrorValueTooLarge();\n\n  /*************\n   * Constants *\n   *************/\n\n  /// @dev The role for opreator.\n  bytes32 public constant OPERATOR_ROLE = keccak256(\"OPERATOR_ROLE\");\n\n  /// @dev The maximum expense ratio.\n  uint256 private constant MAX_EXPENSE_RATIO = 5e8; // 50%\n\n  /// @dev The maximum harvester ratio.\n  uint256 private constant MAX_HARVESTER_RATIO = 2e8; // 20%\n\n  /// @dev The maximum flash loan fee ratio.\n  uint256 private constant MAX_FLASH_LOAN_FEE_RATIO = 1e8; // 10%\n\n  /// @dev The maximum redeem fee ratio.\n  uint256 private constant MAX_REDEEM_FEE_RATIO = 1e8; // 10%\n\n  /// @dev The offset of general expense ratio in `_miscData`.\n  uint256 private constant REWARDS_EXPENSE_RATIO_OFFSET = 0;\n\n  /// @dev The offset of harvester ratio in `_miscData`.\n  uint256 private constant HARVESTER_RATIO_OFFSET = 30;\n\n  /// @dev The offset of flash loan ratio in `_miscData`.\n  uint256 private constant FLASH_LOAN_RATIO_OFFSET = 60;\n\n  /// @dev The offset of redeem fee ratio in `_miscData`.\n  uint256 private constant REDEEM_FEE_RATIO_OFFSET = 90;\n\n  /// @dev The offset of funding expense ratio in `_miscData`.\n  uint256 private constant FUNDING_EXPENSE_RATIO_OFFSET = 120;\n\n  /// @dev The offset of liquidation expense ratio in `_miscData`.\n  uint256 private constant LIQUIDATION_EXPENSE_RATIO_OFFSET = 150;\n\n  /// @dev The precision used to compute fees.\n  uint256 internal constant FEE_PRECISION = 1e9;\n\n  /*************\n   * Variables *\n   *************/\n\n  /// @dev `_miscData` is a storage slot that can be used to store unrelated pieces of information.\n  /// All pools store the *expense ratio*, *harvester ratio* and *withdraw fee percentage*, but\n  /// the `miscData`can be extended to store more pieces of information.\n  ///\n  /// The *expense ratio* is stored in the first most significant 32 bits, and the *harvester ratio* is\n  /// stored in the next most significant 32 bits, and the *withdraw fee percentage* is stored in the\n  /// next most significant 32 bits, leaving the remaining 160 bits free to store any other information\n  /// derived pools might need.\n  ///\n  /// - The *expense ratio* and *harvester ratio* are charged each time when harvester harvest the pool revenue.\n  /// - The *withdraw fee percentage* is charged each time when user try to withdraw assets from the pool.\n  ///\n  /// [ rewards expense ratio | harvester ratio | flash loan ratio | redeem ratio | funding expense ratio | liquidation expense ratio | available ]\n  /// [        30 bits        |     30 bits     |     30  bits     |   30  bits   |        30 bits        |          30 bits          |  76 bits  ]\n  /// [ MSB                                                                                                                                   LSB ]\n  bytes32 internal _miscData;\n\n  /// @inheritdoc IProtocolFees\n  address public treasury;\n\n  /// @inheritdoc IProtocolFees\n  /// @dev Hold fees including open.\n  address public openRevenuePool;\n\n  /// @inheritdoc IProtocolFees\n  address public reservePool;\n\n  /// @inheritdoc IProtocolFees\n  mapping(address => uint256) public accumulatedPoolOpenFees;\n\n  /// @inheritdoc IProtocolFees\n  /// @dev Hold fees including close\n  address public closeRevenuePool;\n\n  /// @inheritdoc IProtocolFees\n  mapping(address => uint256) public accumulatedPoolCloseFees;\n\n  /// @inheritdoc IProtocolFees\n  /// @dev Hold fees including redeem, liquidation and rebalance.\n  address public miscRevenuePool;\n\n  /// @inheritdoc IProtocolFees\n  mapping(address => uint256) public accumulatedPoolMiscFees;\n\n  /***************\n   * Constructor *\n   ***************/\n\n  function __ProtocolFees_init(\n    uint256 _expenseRatio,\n    uint256 _harvesterRatio,\n    uint256 _flashLoanFeeRatio,\n    address _treasury,\n    address _revenuePool,\n    address _reservePool\n  ) internal onlyInitializing {\n    _updateFundingExpenseRatio(_expenseRatio);\n    _updateRewardsExpenseRatio(_expenseRatio);\n    _updateLiquidationExpenseRatio(_expenseRatio);\n    _updateHarvesterRatio(_harvesterRatio);\n    _updateFlashLoanFeeRatio(_flashLoanFeeRatio);\n    _updateTreasury(_treasury);\n    _updateOpenRevenuePool(_revenuePool);\n    _updateCloseRevenuePool(_revenuePool);\n    _updateMiscRevenuePool(_revenuePool);\n    _updateReservePool(_reservePool);\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @inheritdoc IProtocolFees\n  function getFundingExpenseRatio() public view returns (uint256) {\n    return _miscData.decodeUint(FUNDING_EXPENSE_RATIO_OFFSET, 30);\n  }\n\n  /// @inheritdoc IProtocolFees\n  function getRewardsExpenseRatio() public view returns (uint256) {\n    return _miscData.decodeUint(REWARDS_EXPENSE_RATIO_OFFSET, 30);\n  }\n\n  /// @inheritdoc IProtocolFees\n  function getLiquidationExpenseRatio() public view returns (uint256) {\n    return _miscData.decodeUint(LIQUIDATION_EXPENSE_RATIO_OFFSET, 30);\n  }\n\n  /// @inheritdoc IProtocolFees\n  function getHarvesterRatio() public view returns (uint256) {\n    return _miscData.decodeUint(HARVESTER_RATIO_OFFSET, 30);\n  }\n\n  /* @dev removed to reduce codesize, since it is not used.\n  /// @inheritdoc IProtocolFees\n  function getFundingFxSaveRatio() external view returns (uint256) {\n    return FEE_PRECISION - getFundingExpenseRatio() - getHarvesterRatio();\n  }\n  */\n\n  /* @dev removed to reduce codesize, since it is not used.\n  /// @inheritdoc IProtocolFees\n  function getRewardsFxSaveRatio() external view returns (uint256) {\n    unchecked {\n      return FEE_PRECISION - getRewardsExpenseRatio() - getHarvesterRatio();\n    }\n  }\n  */\n\n  /// @inheritdoc IProtocolFees\n  function getFlashLoanFeeRatio() public view returns (uint256) {\n    return _miscData.decodeUint(FLASH_LOAN_RATIO_OFFSET, 30);\n  }\n\n  /// @inheritdoc IProtocolFees\n  function getRedeemFeeRatio() public view returns (uint256) {\n    return _miscData.decodeUint(REDEEM_FEE_RATIO_OFFSET, 30);\n  }\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @inheritdoc IProtocolFees\n  function withdrawAccumulatedPoolFee(address[] memory pools) external {\n    for (uint256 i = 0; i < pools.length; ++i) {\n      _takeAccumulatedPoolFee(pools[i]);\n    }\n  }\n\n  /************************\n   * Restricted Functions *\n   ************************/\n\n  /// @notice Change address of reserve pool contract.\n  /// @param _newReservePool The new address of reserve pool contract.\n  function updateReservePool(address _newReservePool) external onlyRole(OPERATOR_ROLE) {\n    _updateReservePool(_newReservePool);\n  }\n\n  /// @notice Change address of treasury contract.\n  /// @param _newTreasury The new address of treasury contract.\n  function updateTreasury(address _newTreasury) external onlyRole(OPERATOR_ROLE) {\n    _updateTreasury(_newTreasury);\n  }\n\n  /// @notice Change address of open revenue pool contract.\n  /// @param _newPool The new address of revenue pool contract.\n  function updateOpenRevenuePool(address _newPool) external onlyRole(OPERATOR_ROLE) {\n    _updateOpenRevenuePool(_newPool);\n  }\n\n  /// @notice Change address of close revenue pool contract.\n  /// @param _newPool The new address of revenue pool contract.\n  function updateCloseRevenuePool(address _newPool) external onlyRole(OPERATOR_ROLE) {\n    _updateCloseRevenuePool(_newPool);\n  }\n\n  /// @notice Change address of misc revenue pool contract.\n  /// @param _newPool The new address of revenue pool contract.\n  function updateMiscRevenuePool(address _newPool) external onlyRole(OPERATOR_ROLE) {\n    _updateMiscRevenuePool(_newPool);\n  }\n\n  /// @notice Update the fee ratio distributed to treasury.\n  /// @param newRewardsRatio The new ratio for rewards to update, multiplied by 1e9.\n  /// @param newFundingRatio The new ratio for funding to update, multiplied by 1e9.\n  /// @param newLiquidationRatio The new ratio for liquidation/rebalance to update, multiplied by 1e9.\n  function updateExpenseRatio(\n    uint32 newRewardsRatio,\n    uint32 newFundingRatio,\n    uint32 newLiquidationRatio\n  ) external onlyRole(OPERATOR_ROLE) {\n    _updateRewardsExpenseRatio(newRewardsRatio);\n    _updateFundingExpenseRatio(newFundingRatio);\n    _updateLiquidationExpenseRatio(newLiquidationRatio);\n  }\n\n  /// @notice Update the fee ratio distributed to harvester.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function updateHarvesterRatio(uint32 newRatio) external onlyRole(OPERATOR_ROLE) {\n    _updateHarvesterRatio(newRatio);\n  }\n\n  /// @notice Update the flash loan fee ratio.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function updateFlashLoanFeeRatio(uint32 newRatio) external onlyRole(OPERATOR_ROLE) {\n    _updateFlashLoanFeeRatio(newRatio);\n  }\n\n  /// @notice Update the redeem fee ratio.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function updateRedeemFeeRatio(uint32 newRatio) external onlyRole(OPERATOR_ROLE) {\n    _updateRedeemFeeRatio(newRatio);\n  }\n\n  /**********************\n   * Internal Functions *\n   **********************/\n\n  /// @dev Internal function to change address of treasury contract.\n  /// @param _newTreasury The new address of treasury contract.\n  function _updateTreasury(address _newTreasury) private {\n    _checkAddressNotZero(_newTreasury);\n\n    address _oldTreasury = treasury;\n    treasury = _newTreasury;\n\n    emit UpdateTreasury(_oldTreasury, _newTreasury);\n  }\n\n  /// @dev Internal function to change address of revenue pool contract.\n  /// @param _newPool The new address of revenue pool contract.\n  function _updateOpenRevenuePool(address _newPool) private {\n    _checkAddressNotZero(_newPool);\n\n    address _oldPool = openRevenuePool;\n    openRevenuePool = _newPool;\n\n    emit UpdateOpenRevenuePool(_oldPool, _newPool);\n  }\n\n  /// @dev Internal function to change address of revenue pool contract.\n  /// @param _newPool The new address of revenue pool contract.\n  function _updateCloseRevenuePool(address _newPool) private {\n    _checkAddressNotZero(_newPool);\n\n    address _oldPool = closeRevenuePool;\n    closeRevenuePool = _newPool;\n\n    emit UpdateCloseRevenuePool(_oldPool, _newPool);\n  }\n\n  /// @dev Internal function to change address of revenue pool contract.\n  /// @param _newPool The new address of revenue pool contract.\n  function _updateMiscRevenuePool(address _newPool) private {\n    _checkAddressNotZero(_newPool);\n\n    address _oldPool = miscRevenuePool;\n    miscRevenuePool = _newPool;\n\n    emit UpdateMiscRevenuePool(_oldPool, _newPool);\n  }\n\n  /// @dev Internal function to change the address of reserve pool contract.\n  /// @param newReservePool The new address of reserve pool contract.\n  function _updateReservePool(address newReservePool) private {\n    _checkAddressNotZero(newReservePool);\n\n    address oldReservePool = reservePool;\n    reservePool = newReservePool;\n\n    emit UpdateReservePool(oldReservePool, newReservePool);\n  }\n\n  /// @dev Internal function to update the misc data.\n  /// @param newValue The new value to update.\n  /// @param offset The offset of the value to update.\n  /// @param length The length of the value to update.\n  /// @return oldValue The old value.\n  function _updateMiscData(uint256 newValue, uint256 offset, uint256 length) private returns (uint256 oldValue) {\n    bytes32 _data = _miscData;\n    oldValue = _miscData.decodeUint(offset, length);\n    _miscData = _data.insertUint(newValue, offset, length);\n\n    return oldValue;\n  }\n\n  /// @dev Internal function to update the fee ratio distributed to treasury.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function _updateRewardsExpenseRatio(uint256 newRatio) private {\n    _checkValueTooLarge(newRatio, MAX_EXPENSE_RATIO);\n    uint256 oldRatio = _updateMiscData(newRatio, REWARDS_EXPENSE_RATIO_OFFSET, 30);\n    emit UpdateRewardsExpenseRatio(oldRatio, newRatio);\n  }\n\n  /// @dev Internal function to update the fee ratio distributed to treasury.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function _updateLiquidationExpenseRatio(uint256 newRatio) private {\n    _checkValueTooLarge(newRatio, MAX_EXPENSE_RATIO);\n    uint256 oldRatio = _updateMiscData(newRatio, LIQUIDATION_EXPENSE_RATIO_OFFSET, 30);\n    emit UpdateLiquidationExpenseRatio(oldRatio, newRatio);\n  }\n\n  /// @dev Internal function to update the fee ratio distributed to treasury.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function _updateFundingExpenseRatio(uint256 newRatio) private {\n    _checkValueTooLarge(newRatio, MAX_EXPENSE_RATIO);\n    uint256 oldRatio = _updateMiscData(newRatio, FUNDING_EXPENSE_RATIO_OFFSET, 30);\n    emit UpdateFundingExpenseRatio(oldRatio, newRatio);\n  }\n\n  /// @dev Internal function to update the fee ratio distributed to harvester.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function _updateHarvesterRatio(uint256 newRatio) private {\n    _checkValueTooLarge(newRatio, MAX_HARVESTER_RATIO);\n    uint256 oldRatio = _updateMiscData(newRatio, HARVESTER_RATIO_OFFSET, 30);\n    emit UpdateHarvesterRatio(oldRatio, newRatio);\n  }\n\n  /// @dev Internal function to update the flash loan fee ratio.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function _updateFlashLoanFeeRatio(uint256 newRatio) private {\n    _checkValueTooLarge(newRatio, MAX_FLASH_LOAN_FEE_RATIO);\n    uint256 oldRatio = _updateMiscData(newRatio, FLASH_LOAN_RATIO_OFFSET, 30);\n    emit UpdateFlashLoanFeeRatio(oldRatio, newRatio);\n  }\n\n  /// @dev Internal function to update the redeem fee ratio.\n  /// @param newRatio The new ratio to update, multiplied by 1e9.\n  function _updateRedeemFeeRatio(uint256 newRatio) private {\n    _checkValueTooLarge(newRatio, MAX_REDEEM_FEE_RATIO);\n    uint256 oldRatio = _updateMiscData(newRatio, REDEEM_FEE_RATIO_OFFSET, 30);\n    emit UpdateRedeemFeeRatio(oldRatio, newRatio);\n  }\n\n  /// @dev Internal function to accumulate protocol fee for the given pool.\n  /// @param pool The address of pool.\n  /// @param amount The amount of protocol fee.\n  function _accumulatePoolOpenFee(address pool, uint256 amount) internal {\n    unchecked {\n      accumulatedPoolOpenFees[pool] += amount;\n    }\n  }\n\n  /// @dev Internal function to accumulate protocol fee for the given pool.\n  /// @param pool The address of pool.\n  /// @param amount The amount of protocol fee.\n  function _accumulatePoolCloseFee(address pool, uint256 amount) internal {\n    unchecked {\n      accumulatedPoolCloseFees[pool] += amount;\n    }\n  }\n\n  /// @dev Internal function to accumulate protocol fee for the given pool.\n  /// @param pool The address of pool.\n  /// @param amount The amount of protocol fee.\n  function _accumulatePoolMiscFee(address pool, uint256 amount) internal {\n    unchecked {\n      accumulatedPoolMiscFees[pool] += amount;\n    }\n  }\n\n  /// @dev Internal function to withdraw accumulated protocol fee for the given pool.\n  /// @param pool The address of pool.\n  function _takeAccumulatedPoolFee(address pool) internal virtual {\n    address collateralToken = IPool(pool).collateralToken();\n    uint256 fees = accumulatedPoolOpenFees[pool];\n    if (fees > 0) {\n      IERC20(collateralToken).safeTransfer(openRevenuePool, fees);\n      accumulatedPoolOpenFees[pool] = 0;\n    }\n    fees = accumulatedPoolCloseFees[pool];\n    if (fees > 0) {\n      IERC20(collateralToken).safeTransfer(closeRevenuePool, fees);\n      accumulatedPoolCloseFees[pool] = 0;\n    }\n    fees = accumulatedPoolMiscFees[pool];\n    if (fees > 0) {\n      IERC20(collateralToken).safeTransfer(miscRevenuePool, fees);\n      accumulatedPoolMiscFees[pool] = 0;\n    }\n  }\n\n  /// @dev Internal function to check value not too large.\n  /// @param value The value to check.\n  /// @param upperBound The upper bound for the given value.\n  function _checkValueTooLarge(uint256 value, uint256 upperBound) internal pure {\n    if (value > upperBound) revert ErrorValueTooLarge();\n  }\n\n  /// @dev Internal function to check address is nonzero\n  function _checkAddressNotZero(address value) internal pure {\n    if (value == address(0)) revert ErrorZeroAddress();\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   */\n  uint256[41] private __gap;\n}\n"},"contracts/fund/AssetManagement.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport { AccessControlUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol\";\n\nimport { IStrategy } from \"./IStrategy.sol\";\n\nabstract contract AssetManagement is AccessControlUpgradeable {\n  using SafeERC20 for IERC20;\n\n  bytes32 public constant ASSET_MANAGER_ROLE = keccak256(\"ASSET_MANAGER_ROLE\");\n\n  struct Allocation {\n    address strategy;\n    uint96 capacity;\n  }\n\n  mapping(address => Allocation) public allocations;\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   */\n  uint256[49] private __gap;\n\n  function kill(address asset) public onlyRole(DEFAULT_ADMIN_ROLE) {\n    Allocation memory curAlloc = allocations[asset];\n    if (curAlloc.strategy != address(0)) {\n      IStrategy(curAlloc.strategy).kill();\n      curAlloc.strategy = address(0);\n      curAlloc.capacity = 0;\n      allocations[asset] = curAlloc;\n    }\n  }\n\n  function alloc(address asset, address strategy, uint96 capacity) external onlyRole(DEFAULT_ADMIN_ROLE) {\n    Allocation memory oldAlloc = allocations[asset];\n    if (oldAlloc.strategy != address(0)) kill(asset);\n    allocations[asset] = Allocation({ strategy: strategy, capacity: capacity });\n  }\n\n  function manage(address asset, uint256 amount) external onlyRole(ASSET_MANAGER_ROLE) {\n    Allocation memory curAlloc = allocations[asset];\n    uint256 managed = IStrategy(curAlloc.strategy).totalSupply();\n    if (managed + amount > curAlloc.capacity) revert();\n    IERC20(asset).safeTransfer(curAlloc.strategy, amount);\n    IStrategy(curAlloc.strategy).deposit(amount);\n  }\n\n  function _transferOut(address asset, uint256 amount, address receiver) internal {\n    uint256 balance = IERC20(asset).balanceOf(address(this));\n    if (balance >= amount) {\n      IERC20(asset).safeTransfer(receiver, amount);\n    } else {\n      if (balance > 0) {\n        IERC20(asset).safeTransfer(receiver, balance);\n      }\n      unchecked {\n        uint256 diff = amount - balance;\n        Allocation memory curAlloc = allocations[asset];\n        if (curAlloc.strategy == address(0)) revert();\n        IStrategy(curAlloc.strategy).withdraw(diff, receiver);\n      }\n    }\n  }\n\n  function _balanceOf(address asset) internal view returns (uint256) {\n    uint256 balance = IERC20(asset).balanceOf(address(this));\n    address strategy = allocations[asset].strategy;\n    if (strategy == address(0)) return balance;\n    return balance + IStrategy(strategy).principal();\n  }\n}\n"},"contracts/fund/IStrategy.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IStrategy {\n  function principal() external view returns (uint256);\n\n  function totalSupply() external view returns (uint256);\n\n  function deposit(uint256 amount) external;\n\n  function withdraw(uint256 amount, address recipient) external;\n\n  function kill() external;\n\n  function harvest(address receiver) external;\n}\n"},"contracts/interfaces/ICreditNote.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ICreditNote {\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint the credit note to the given address.\n  /// @param to The address to mint the credit note to.\n  /// @param amount The amount of credit note to mint.\n  function mint(address to, uint256 amount) external;\n\n  /// @notice Burn the credit note from the given address.\n  /// @param from The address to burn the credit note from.\n  /// @param amount The amount of credit note to burn.\n  function burn(address from, uint256 amount) external;\n}\n"},"contracts/interfaces/IFxUSDBasePool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxUSDBasePool {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the stable depeg price is updated.\n  /// @param oldPrice The value of previous depeg price, multiplied by 1e18.\n  /// @param newPrice The value of current depeg price, multiplied by 1e18.\n  event UpdateStableDepegPrice(uint256 oldPrice, uint256 newPrice);\n\n  /// @notice Emitted when the redeem cool down period is updated.\n  /// @param oldPeriod The value of previous redeem cool down period.\n  /// @param newPeriod The value of current redeem cool down period.\n  event UpdateRedeemCoolDownPeriod(uint256 oldPeriod, uint256 newPeriod);\n\n  /// @notice Emitted when the instant redeem fee ratio is updated.\n  /// @param oldRatio The value of previous instant redeem fee ratio, multiplied by 1e18.\n  /// @param newRatio The value of current instant redeem fee ratio, multiplied by 1e18.\n  event UpdateInstantRedeemFeeRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when deposit tokens.\n  /// @param caller The address of caller.\n  /// @param receiver The address of pool share recipient.\n  /// @param tokenIn The address of input token.\n  /// @param amountDeposited The amount of input tokens.\n  /// @param amountSharesOut The amount of pool shares minted.\n  event Deposit(\n    address indexed caller,\n    address indexed receiver,\n    address indexed tokenIn,\n    uint256 amountDeposited,\n    uint256 amountSharesOut\n  );\n  \n  /// @notice Emitted when users request redeem.\n  /// @param caller The address of caller.\n  /// @param shares The amount of shares to redeem.\n  /// @param unlockAt The timestamp when this share can be redeemed.\n  event RequestRedeem(address indexed caller, uint256 shares, uint256 unlockAt);\n\n  /// @notice Emitted when redeem pool shares.\n  /// @param caller The address of caller.\n  /// @param receiver The address of pool share recipient.\n  /// @param amountSharesToRedeem The amount of pool shares burned.\n  /// @param amountYieldTokenOut The amount of yield tokens redeemed.\n  /// @param amountStableTokenOut The amount of stable tokens redeemed.\n  event Redeem(\n    address indexed caller,\n    address indexed receiver,\n    uint256 amountSharesToRedeem,\n    uint256 amountYieldTokenOut,\n    uint256 amountStableTokenOut\n  );\n\n  /// @notice Emitted when instant redeem pool shares.\n  /// @param caller The address of caller.\n  /// @param receiver The address of pool share recipient.\n  /// @param amountSharesToRedeem The amount of pool shares burned.\n  /// @param amountYieldTokenOut The amount of yield tokens redeemed.\n  /// @param amountStableTokenOut The amount of stable tokens redeemed.\n  event InstantRedeem(\n    address indexed caller,\n    address indexed receiver,\n    uint256 amountSharesToRedeem,\n    uint256 amountYieldTokenOut,\n    uint256 amountStableTokenOut\n  );\n\n  /// @notice Emitted when rebalance or liquidate.\n  /// @param caller The address of caller.\n  /// @param tokenIn The address of input token.\n  /// @param amountTokenIn The amount of input token used.\n  /// @param amountCollateral The amount of collateral token rebalanced.\n  /// @param amountYieldToken The amount of yield token used.\n  /// @param amountStableToken The amount of stable token used.\n  event Rebalance(\n    address indexed caller,\n    address indexed tokenIn,\n    uint256 amountTokenIn,\n    uint256 amountCollateral,\n    uint256 amountYieldToken,\n    uint256 amountStableToken\n  );\n\n  /// @notice Emitted when arbitrage in curve pool.\n  /// @param caller The address of caller.\n  /// @param tokenIn The address of input token.\n  /// @param amountIn The amount of input token used.\n  /// @param amountOut The amount of output token swapped.\n  /// @param bonusOut The amount of bonus token.\n  event Arbitrage(\n    address indexed caller,\n    address indexed tokenIn,\n    uint256 amountIn,\n    uint256 amountOut,\n    uint256 bonusOut\n  );\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of yield token.\n  function yieldToken() external view returns (address);\n\n  /// @notice The address of stable token.\n  function stableToken() external view returns (address);\n\n  /// @notice The total amount of yield token managed in this contract\n  function totalYieldToken() external view returns (uint256);\n\n  /// @notice The total amount of stable token managed in this contract\n  function totalStableToken() external view returns (uint256);\n\n  /// @notice The net asset value, multiplied by 1e18.\n  function nav() external view returns (uint256);\n\n  /// @notice Return the stable token price, multiplied by 1e18.\n  function getStableTokenPrice() external view returns (uint256);\n\n  /// @notice Return the stable token price with scaling to 18 decimals, multiplied by 1e18.\n  function getStableTokenPriceWithScale() external view returns (uint256);\n\n  /// @notice Preview the result of deposit.\n  /// @param tokenIn The address of input token.\n  /// @param amount The amount of input tokens to deposit.\n  /// @return amountSharesOut The amount of pool shares should receive.\n  function previewDeposit(address tokenIn, uint256 amount) external view returns (uint256 amountSharesOut);\n\n  /// @notice Preview the result of redeem.\n  /// @param amountSharesToRedeem The amount of pool shares to redeem.\n  /// @return amountYieldOut The amount of yield token should receive.\n  /// @return amountStableOut The amount of stable token should receive.\n  function previewRedeem(\n    uint256 amountSharesToRedeem\n  ) external view returns (uint256 amountYieldOut, uint256 amountStableOut);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Deposit token.\n  /// @param receiver The address of pool shares recipient.\n  /// @param tokenIn The address of input token.\n  /// @param amountTokenToDeposit The amount of input tokens to deposit.\n  /// @param minSharesOut The minimum amount of pool shares should receive.\n  /// @return amountSharesOut The amount of pool shares received.\n  function deposit(\n    address receiver,\n    address tokenIn,\n    uint256 amountTokenToDeposit,\n    uint256 minSharesOut\n  ) external returns (uint256 amountSharesOut);\n\n  /// @notice Request redeem.\n  /// @param shares The amount of shares to request.\n  function requestRedeem(uint256 shares) external;\n\n  /// @notice Redeem pool shares.\n  /// @param receiver The address of token recipient.\n  /// @param shares The amount of pool shares to redeem.\n  /// @return amountYieldOut The amount of yield token should received.\n  /// @return amountStableOut The amount of stable token should received.\n  function redeem(address receiver, uint256 shares) external returns (uint256 amountYieldOut, uint256 amountStableOut);\n\n  /// @notice Redeem pool shares instantly with withdraw fee.\n  /// @param receiver The address of token recipient.\n  /// @param shares The amount of pool shares to redeem.\n  /// @return amountYieldOut The amount of yield token should received.\n  /// @return amountStableOut The amount of stable token should received.\n  function instantRedeem(address receiver, uint256 shares) external returns (uint256 amountYieldOut, uint256 amountStableOut);\n\n  /// @notice Rebalance all positions in the given tick.\n  /// @param pool The address of pool to rebalance.\n  /// @param tick The index of tick to rebalance.\n  /// @param tokenIn The address of token to rebalance.\n  /// @param maxAmount The maximum amount of input token to rebalance.\n  /// @param minBaseOut The minimum amount of collateral tokens should receive.\n  /// @return tokenUsed The amount of input token used to rebalance.\n  /// @return baseOut The amount of collateral tokens rebalanced.\n  function rebalance(\n    address pool,\n    int16 tick,\n    address tokenIn,\n    uint256 maxAmount,\n    uint256 minBaseOut\n  ) external returns (uint256 tokenUsed, uint256 baseOut);\n\n  /// @notice Rebalance all possible ticks.\n  /// @param pool The address of pool to rebalance.\n  /// @param tokenIn The address of token to rebalance.\n  /// @param maxAmount The maximum amount of input token to rebalance.\n  /// @param minBaseOut The minimum amount of collateral tokens should receive.\n  /// @return tokenUsed The amount of input token used to rebalance.\n  /// @return baseOut The amount of collateral tokens rebalanced.\n  function rebalance(\n    address pool,\n    address tokenIn,\n    uint256 maxAmount,\n    uint256 minBaseOut\n  ) external returns (uint256 tokenUsed, uint256 baseOut);\n\n  /// @notice Liquidate all possible ticks.\n  /// @param pool The address of pool to rebalance.\n  /// @param tokenIn The address of token to rebalance.\n  /// @param maxAmount The maximum amount of input token to rebalance.\n  /// @param minBaseOut The minimum amount of collateral tokens should receive.\n  /// @return tokenUsed The amount of input token used to rebalance.\n  /// @return baseOut The amount of collateral tokens rebalanced.\n  function liquidate(\n    address pool,\n    address tokenIn,\n    uint256 maxAmount,\n    uint256 minBaseOut\n  ) external returns (uint256 tokenUsed, uint256 baseOut);\n\n  /// @notice Arbitrage between yield token and stable token.\n  /// @param srcToken The address of source token.\n  /// @param amountIn The amount of source token to use.\n  /// @param receiver The address of bonus receiver.\n  /// @param data The hook data to `onSwap`.\n  /// @return amountOut The amount of target token swapped.\n  /// @return bonusOut The amount of bonus token.\n  function arbitrage(\n    address srcToken,\n    uint256 amountIn,\n    address receiver,\n    bytes calldata data\n  ) external returns (uint256 amountOut, uint256 bonusOut);\n}\n"},"contracts/interfaces/IFxUSDRegeneracy.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IFxUSDRegeneracy {\n  /**********\n   * Events *\n   **********/\n  \n  /// @notice Emitted when rebalance/liquidate with stable token.\n  /// @param amountStable The amount of stable token used.\n  /// @param amountFxUSD The corresponding amount of fxUSD.\n  event RebalanceWithStable(uint256 amountStable, uint256 amountFxUSD);\n  \n  /// @notice Emitted when buyback fxUSD with stable reserve.\n  /// @param amountStable the amount of stable token used.\n  /// @param amountFxUSD The amount of fxUSD bought.\n  /// @param bonusFxUSD The amount of fxUSD as bonus for caller.\n  event Buyback(uint256 amountStable, uint256 amountFxUSD, uint256 bonusFxUSD);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of `PoolManager` contract.\n  function poolManager() external view returns (address);\n\n  /// @notice The address of stable token.\n  function stableToken() external view returns (address);\n\n  /// @notice The address of `PegKeeper` contract.\n  function pegKeeper() external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Mint fxUSD token someone.\n  function mint(address to, uint256 amount) external;\n\n  /// @notice Burn fxUSD from someone.\n  function burn(address from, uint256 amount) external;\n\n  /// @notice Hook for rebalance/liquidate with stable token.\n  /// @param amountStableToken The amount of stable token.\n  /// @param amountFxUSD The amount of fxUSD.\n  function onRebalanceWithStable(uint256 amountStableToken, uint256 amountFxUSD) external;\n\n  /// @notice Buyback fxUSD with stable token.\n  /// @param amountIn the amount of stable token to use.\n  /// @param receiver The address of bonus receiver.\n  /// @param data The hook data to PegKeeper.\n  /// @return amountOut The amount of fxUSD swapped.\n  /// @return bonusOut The amount of bonus fxUSD.\n  function buyback(\n    uint256 amountIn,\n    address receiver,\n    bytes calldata data\n  ) external returns (uint256 amountOut, uint256 bonusOut);\n}\n"},"contracts/interfaces/ILongPool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { IPool } from \"./IPool.sol\";\n\ninterface ILongPool is IPool {\n  /// @notice Reduce the collateral of the pool.\n  /// @param rawAmount The amount of raw collateral to reduce.\n  function reduceCollateral(uint256 rawAmount) external;\n}\n"},"contracts/interfaces/ILongPoolManager.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { IPoolManager } from \"./IPoolManager.sol\";\n\ninterface ILongPoolManager is IPoolManager {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the threshold for permissionless liquidate/rebalance is updated.\n  /// @param oldThreshold The value of previous threshold.\n  /// @param newThreshold The value of current threshold.\n  event UpdatePermissionedLiquidationThreshold(uint256 oldThreshold, uint256 newThreshold);\n\n  /// @notice Emitted when rebalance for a tick happened.\n  /// @param pool The address of pool rebalanced.\n  /// @param tick The index of tick rebalanced.\n  /// @param colls The amount of collateral tokens rebalanced.\n  /// @param fxUSDDebts The amount of fxUSD rebalanced.\n  /// @param stableDebts The amount of stable token (a.k.a USDC) rebalanced.\n  event RebalanceTick(address indexed pool, int16 indexed tick, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);\n\n  /// @notice Emitted when rebalance happened.\n  /// @param pool The address of pool rebalanced.\n  /// @param colls The amount of collateral tokens rebalanced.\n  /// @param fxUSDDebts The amount of fxUSD rebalanced.\n  /// @param stableDebts The amount of stable token (a.k.a USDC) rebalanced.\n  event Rebalance(address indexed pool, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);\n\n  /// @notice Emitted when liquidate happened.\n  /// @param pool The address of pool liquidated.\n  /// @param colls The amount of collateral tokens liquidated.\n  /// @param fxUSDDebts The amount of fxUSD liquidated.\n  /// @param stableDebts The amount of stable token (a.k.a USDC) liquidated.\n  event Liquidate(address indexed pool, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);\n\n  /// @notice Emitted when the short borrow capacity ratio for the given long pool is updated.\n  /// @param longPool The address of the long pool.\n  /// @param oldRatio The old short borrow capacity ratio.\n  /// @param newRatio The new short borrow capacity ratio.\n  event UpdateShortBorrowCapacityRatio(address indexed longPool, uint256 oldRatio, uint256 newRatio);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of FxUSDSave.\n  function fxBASE() external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Open a new position or operate on an old position.\n  /// @param pool The address of pool to operate.\n  /// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.\n  /// @param newColl The amount of collateral token to supply (positive value) or withdraw (negative value).\n  /// @param newDebt The amount of debt token to borrow (positive value) or repay (negative value).\n  /// @param useStable Whether to use stable token for repay.\n  /// @return actualPositionId The id of this position.\n  function operate(\n    address pool,\n    uint256 positionId,\n    int256 newColl,\n    int256 newDebt,\n    bool useStable\n  ) external returns (uint256 actualPositionId);\n\n  /// @notice Rebalance all positions in the given tick.\n  /// @param pool The address of pool to rebalance.\n  /// @param receiver The address of recipient for rebalanced tokens.\n  /// @param tick The index of tick to rebalance.\n  /// @param maxFxUSD The maximum amount of fxUSD to rebalance.\n  /// @param maxStable The maximum amount of stable token (a.k.a USDC) to rebalance.\n  /// @return colls The amount of collateral tokens rebalanced.\n  /// @return fxUSDUsed The amount of fxUSD used to rebalance.\n  /// @return stableUsed The amount of stable token used to rebalance.\n  function rebalance(\n    address pool,\n    address receiver,\n    int16 tick,\n    uint256 maxFxUSD,\n    uint256 maxStable\n  ) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);\n\n  /// @notice Rebalance all positions in the given tick.\n  /// @param pool The address of pool to rebalance.\n  /// @param receiver The address of recipient for rebalanced tokens.\n  /// @param maxFxUSD The maximum amount of fxUSD to rebalance.\n  /// @param maxStable The maximum amount of stable token (a.k.a USDC) to rebalance.\n  /// @return colls The amount of collateral tokens rebalanced.\n  /// @return fxUSDUsed The amount of fxUSD used to rebalance.\n  /// @return stableUsed The amount of stable token used to rebalance.\n  function rebalance(\n    address pool,\n    address receiver,\n    uint256 maxFxUSD,\n    uint256 maxStable\n  ) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);\n\n  /// @notice Liquidate a given position.\n  /// @param pool The address of pool to liquidate.\n  /// @param receiver The address of recipient for liquidated tokens.\n  /// @param maxFxUSD The maximum amount of fxUSD to liquidate.\n  /// @param maxStable The maximum amount of stable token (a.k.a USDC) to liquidate.\n  /// @return colls The amount of collateral tokens liquidated.\n  /// @return fxUSDUsed The amount of fxUSD used to liquidate.\n  /// @return stableUsed The amount of stable token used to liquidate.\n  function liquidate(\n    address pool,\n    address receiver,\n    uint256 maxFxUSD,\n    uint256 maxStable\n  ) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);\n\n  /// @notice Borrow collateral token from long pool.\n  /// @param longPool The address of long pool.\n  /// @param shortPool The address of short pool.\n  /// @param amount The amount of collateral token to borrow.\n  function borrow(address longPool, address shortPool, uint256 amount) external;\n\n  /// @notice Repay collateral token to long pool.\n  /// @param longPool The address of long pool.\n  /// @param shortPool The address of short pool.\n  /// @param amount The amount of collateral token to repay.\n  function repay(address longPool, address shortPool, uint256 amount) external;\n\n  /// @notice Repay collateral token to long pool by credit note.\n  /// @param longPool The address of long pool.\n  /// @param shortPool The address of short pool.\n  /// @param amount The amount of credit note token to repay.\n  function repayByCreditNote(address longPool, address shortPool, uint256 amount) external;\n\n  /// @notice Liquidate short pool.\n  /// @param longPool The address of long pool.\n  /// @param shortPool The address of short pool.\n  /// @param amountFxUSD The amount of fxUSD to liquidate.\n  /// @param totalBorrowed The total amount of collateral tokens borrowed from long pool.\n  /// @return shortfall The amount of shortfall collateral token.\n  function liquidateShortPool(\n    address longPool,\n    address shortPool,\n    uint256 amountFxUSD,\n    uint256 totalBorrowed\n  ) external returns (uint256 shortfall);\n}\n"},"contracts/interfaces/IPool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPool {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when price oracle is updated.\n  /// @param oldOracle The previous address of price oracle.\n  /// @param newOracle The current address of price oracle.\n  event UpdatePriceOracle(address oldOracle, address newOracle);\n\n  /// @notice Emitted when borrow status is updated.\n  /// @param status The updated borrow status.\n  event UpdateBorrowStatus(bool status);\n\n  /// @notice Emitted when redeem status is updated.\n  /// @param status The updated redeem status.\n  event UpdateRedeemStatus(bool status);\n\n  /// @notice Emitted when debt ratio range is updated.\n  /// @param minDebtRatio The current value of minimum debt ratio, multiplied by 1e18.\n  /// @param maxDebtRatio The current value of maximum debt ratio, multiplied by 1e18.\n  event UpdateDebtRatioRange(uint256 minDebtRatio, uint256 maxDebtRatio);\n\n  /// @notice Emitted when max redeem ratio per tick is updated.\n  /// @param ratio The current value of max redeem ratio per tick, multiplied by 1e9.\n  event UpdateMaxRedeemRatioPerTick(uint256 ratio);\n\n  /// @notice Emitted when the rebalance ratio is updated.\n  /// @param debtRatio The current value of rebalance debt ratio, multiplied by 1e18.\n  /// @param bonusRatio The current value of rebalance bonus ratio, multiplied by 1e9.\n  event UpdateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Emitted when the liquidate ratio is updated.\n  /// @param debtRatio The current value of liquidate debt ratio, multiplied by 1e18.\n  /// @param bonusRatio The current value of liquidate bonus ratio, multiplied by 1e9.\n  event UpdateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Emitted when position is updated.\n  /// @param position The index of this position.\n  /// @param tick The index of tick, this position belongs to.\n  /// @param collShares The amount of collateral shares in this position.\n  /// @param debtShares The amount of debt shares in this position.\n  /// @param price The price used for this operation.\n  event PositionSnapshot(uint256 position, int16 tick, uint256 collShares, uint256 debtShares, uint256 price);\n\n  /// @notice Emitted when tick moved due to rebalance, liquidate or redeem.\n  /// @param oldTick The index of the previous tick.\n  /// @param newTick The index of the current tick.\n  /// @param collShares The amount of collateral shares added to new tick.\n  /// @param debtShares The amount of debt shares added to new tick.\n  /// @param price The price used for this operation.\n  event TickMovement(int16 oldTick, int16 newTick, uint256 collShares, uint256 debtShares, uint256 price);\n\n  /// @notice Emitted when debt index increase.\n  event DebtIndexSnapshot(uint256 index);\n\n  /// @notice Emitted when collateral index increase.\n  event CollateralIndexSnapshot(uint256 index);\n\n  /// @notice Emitted when counterparty is updated.\n  /// @param oldCounterparty The previous address of counterparty.\n  /// @param newCounterparty The new address of counterparty.\n  event UpdateCounterparty(address oldCounterparty, address newCounterparty);\n\n  /***********\n   * Structs *\n   ***********/\n\n  /// @dev The result for liquidation.\n  /// @param rawColls The amount of collateral tokens liquidated.\n  /// @param rawDebts The amount of debt tokens liquidated.\n  /// @param bonusRawColls The amount of bonus collateral tokens given.\n  /// @param bonusFromReserve The amount of bonus collateral tokens coming from reserve pool.\n  struct LiquidateResult {\n    uint256 rawColls;\n    uint256 rawDebts;\n    uint256 bonusRawColls;\n    uint256 bonusFromReserve;\n  }\n\n  /// @dev The result for rebalance.\n  /// @param rawColls The amount of collateral tokens rebalanced.\n  /// @param rawDebts The amount of debt tokens rebalanced.\n  /// @param bonusRawColls The amount of bonus collateral tokens given.\n  struct RebalanceResult {\n    uint256 rawColls;\n    uint256 rawDebts;\n    uint256 bonusRawColls;\n  }\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of counterparty.\n  function counterparty() external view returns (address);\n\n  /// @notice The address of fxUSD.\n  function fxUSD() external view returns (address);\n\n  /// @notice The address of `PoolManager` contract.\n  function poolManager() external view returns (address);\n\n  /// @notice The address of `PoolConfiguration` contract.\n  function configuration() external view returns (address);\n\n  /// @notice The address of collateral token.\n  function collateralToken() external view returns (address);\n\n  /// @notice The address of price oracle.\n  function priceOracle() external view returns (address);\n\n  /// @notice Return whether borrow is paused.\n  function isBorrowPaused() external view returns (bool);\n\n  /// @notice Return whether redeem is paused.\n  function isRedeemPaused() external view returns (bool);\n\n  /// @notice Return the current top tick with debts.\n  function getTopTick() external view returns (int16);\n\n  /// @notice Return the next position id.\n  function getNextPositionId() external view returns (uint32);\n\n  /// @notice Return the next tick tree node id.\n  function getNextTreeNodeId() external view returns (uint48);\n\n  /// @notice Return the debt ratio range.\n  /// @param minDebtRatio The minimum required debt ratio, multiplied by 1e18.\n  /// @param maxDebtRatio The minimum allowed debt ratio, multiplied by 1e18.\n  function getDebtRatioRange() external view returns (uint256 minDebtRatio, uint256 maxDebtRatio);\n\n  /// @notice Return the maximum redeem percentage per tick, multiplied by 1e9.\n  function getMaxRedeemRatioPerTick() external view returns (uint256);\n\n  /// @notice Get `debtRatio` and `bonusRatio` for rebalance.\n  /// @return debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.\n  /// @return bonusRatio The bonus ratio during rebalance, multiplied by 1e9.\n  function getRebalanceRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Get `debtRatio` and `bonusRatio` for liquidate.\n  /// @return debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.\n  /// @return bonusRatio The bonus ratio during liquidate, multiplied by 1e9.\n  function getLiquidateRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);\n\n  /// @notice Get debt and collateral index.\n  /// @return debtIndex The index for debt shares.\n  /// @return collIndex The index for collateral shares.\n  function getDebtAndCollateralIndex() external view returns (uint256 debtIndex, uint256 collIndex);\n\n  /// @notice Get debt and collateral shares.\n  /// @return debtShares The total number of debt shares.\n  /// @return collShares The total number of collateral shares.\n  function getDebtAndCollateralShares() external view returns (uint256 debtShares, uint256 collShares);\n\n  /// @notice Return the details of the given position.\n  /// @param tokenId The id of position to query.\n  /// @return rawColls The amount of collateral tokens supplied in this position.\n  /// @return rawDebts The amount of debt tokens borrowed in this position.\n  function getPosition(uint256 tokenId) external view returns (uint256 rawColls, uint256 rawDebts);\n\n  /// @notice Return the debt ratio of the given position.\n  /// @param tokenId The id of position to query.\n  /// @return debtRatio The debt ratio of this position.\n  function getPositionDebtRatio(uint256 tokenId) external view returns (uint256 debtRatio);\n\n  /// @notice The total amount of raw collateral tokens.\n  function getTotalRawCollaterals() external view returns (uint256);\n\n  /// @notice The total amount of raw debt tokens.\n  function getTotalRawDebts() external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Open a new position or operate on an old position.\n  /// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.\n  /// @param newRawColl The amount of collateral token to supply (positive value) or withdraw (negative value).\n  /// @param newRawColl The amount of debt token to borrow (positive value) or repay (negative value).\n  /// @param owner The address of position owner.\n  /// @return actualPositionId The id of this position.\n  /// @return actualRawColl The actual amount of collateral tokens supplied (positive value) or withdrawn (negative value).\n  /// @return actualRawDebt The actual amount of debt tokens borrowed (positive value) or repay (negative value).\n  function operate(\n    uint256 positionId,\n    int256 newRawColl,\n    int256 newRawDebt,\n    address owner\n  ) external returns (uint256 actualPositionId, int256 actualRawColl, int256 actualRawDebt, uint256 protocolFees);\n\n  /// @notice Redeem debt tokens to get collateral tokens.\n  /// @param rawDebts The amount of debt tokens to redeem.\n  /// @return actualRawDebts The actual amount of debt tokens used.\n  /// @return rawColls The amount of collateral tokens to redeemed.\n  function redeem(uint256 rawDebts) external returns (uint256 actualRawDebts, uint256 rawColls);\n\n  /// @notice Rebalance all positions in the given tick.\n  /// @param tick The id of tick to rebalance.\n  /// @param maxRawDebts The maximum amount of debt tokens to rebalance.\n  /// @return result The result of rebalance.\n  function rebalance(int16 tick, uint256 maxRawDebts) external returns (RebalanceResult memory result);\n\n  /// @notice Rebalance all ticks in the decreasing order of LTV.\n  /// @param maxRawDebts The maximum amount of debt tokens to rebalance.\n  /// @return result The result of rebalance.\n  function rebalance(uint256 maxRawDebts) external returns (RebalanceResult memory result);\n\n  /// @notice Liquidate all ticks in the decreasing order of LTV.\n  /// @param maxRawDebts The maximum amount of debt tokens to liquidate.\n  /// @param reservedRawColls The amount of collateral tokens in reserve pool.\n  /// @return result The result of liquidate.\n  function liquidate(uint256 maxRawDebts, uint256 reservedRawColls) external returns (LiquidateResult memory result);\n\n  /// @notice Reduce debt.\n  /// @param rawAmount The amount of debt tokens to reduce.\n  function reduceDebt(uint256 rawAmount) external;\n}\n"},"contracts/interfaces/IPoolConfiguration.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.26;\n\ninterface IPoolConfiguration {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the oracle is updated.\n  /// @param oldOracle The old oracle address.\n  /// @param newOracle The new oracle address.\n  event UpdateOracle(address indexed oldOracle, address indexed newOracle);\n\n  /// @notice Emitted when the pool fee ratio is updated.\n  /// @param pool The address of pool.\n  /// @param recipient The address of recipient.\n  /// @param supplyRatio The supply ratio, multiplied by 1e9.\n  /// @param supplyRatioStep The supply ratio step, multiplied by 1e18.\n  /// @param withdrawFeeRatio The withdraw fee ratio, multiplied by 1e9.\n  /// @param borrowFeeRatio The borrow fee ratio, multiplied by 1e9.\n  /// @param repayFeeRatio The repay fee ratio, multiplied by 1e9.\n  event UpdatePoolFeeRatio(\n    address indexed pool,\n    address indexed recipient,\n    uint256 supplyRatio,\n    uint256 supplyRatioStep,\n    uint256 withdrawFeeRatio,\n    uint256 borrowFeeRatio,\n    uint256 repayFeeRatio\n  );\n\n  /// @notice Emitted when the long funding ratio parameter is updated.\n  /// @param scalarA The scalar A.\n  /// @param scalarB The scalar B.\n  /// @param maxFxUSDRatio The max fxUSD ratio.\n  event UpdateLongFundingRatioParameter(uint64 scalarA, uint64 scalarB, uint64 maxFxUSDRatio);\n\n  /// @notice Emitted when the short funding ratio parameter is updated.\n  /// @param scalarC The scalar C.\n  /// @param maxBorrowRatio The max borrow ratio.\n  event UpdateShortFundingRatioParameter(uint64 scalarC, uint64 maxBorrowRatio);\n\n  /// @notice Emitted when the snapshot is taken.\n  /// @param borrowIndex The borrow index.\n  /// @param lastInterestRate The last interest rate.\n  /// @param timestamp The timestamp of the snapshot.\n  event Snapshot(uint256 borrowIndex, uint256 lastInterestRate, uint256 timestamp);\n\n  /// @notice Emitted when the stable depeg price is updated.\n  /// @param oldStableDepegPrice The old stable depeg price.\n  /// @param newStableDepegPrice The new stable depeg price.\n  event UpdateStableDepegPrice(uint256 oldStableDepegPrice, uint256 newStableDepegPrice);\n\n  /// @notice Emitted when an address is registered.\n  /// @param key The key of the registered address.\n  /// @param addr The registered address.\n  event Register(bytes32 key, address addr);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return whether borrow for fxUSD is allowed.\n  function isBorrowAllowed() external view returns (bool);\n\n  /// @notice Return whether redeem for fxUSD is allowed.\n  function isRedeemAllowed() external view returns (bool);\n\n  /// @notice Return whether funding costs is enabled.\n  function isFundingEnabled() external view returns (bool);\n\n  /// @notice Return whether repay with stable coin is allowed.\n  function isStableRepayAllowed() external view returns (bool);\n\n  /// @notice Get the pool fee ratio.\n  /// @param pool The address of pool.\n  /// @param recipient The address of recipient.\n  /// @return supplyFeeRatio The supply fee ratio, multiplied by 1e9.\n  /// @return withdrawFeeRatio The withdraw fee ratio, multiplied by 1e9.\n  /// @return borrowFeeRatio The borrow fee ratio, multiplied by 1e9.\n  /// @return repayFeeRatio The repay fee ratio, multiplied by 1e9.\n  function getPoolFeeRatio(\n    address pool,\n    address recipient\n  )\n    external\n    view\n    returns (uint256 supplyFeeRatio, uint256 withdrawFeeRatio, uint256 borrowFeeRatio, uint256 repayFeeRatio);\n\n  /// @notice Get the long pool funding ratio.\n  /// @param pool The address of pool.\n  /// @return fundingRatio The funding ratio, multiplied by 1e18.\n  function getLongPoolFundingRatio(address pool) external view returns (uint256 fundingRatio);\n\n  /// @notice Get the short pool funding ratio.\n  /// @param pool The address of pool.\n  /// @return fundingRatio The funding ratio, multiplied by 1e18.\n  function getShortPoolFundingRatio(address pool) external view returns (uint256 fundingRatio);\n\n  /// @notice Get the registered address.\n  /// @param key The key of the registered address.\n  /// @return address The registered address.\n  function registry(bytes32 key) external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Checkpoint the lending pool snapshot.\n  /// @param pool The address of pool.\n  function checkpoint(address pool) external;\n\n  /// @notice Lock the pool manager.\n  /// @param manager The address of pool manager.\n  /// @param selector The selector of the function to lock.\n  function lock(address manager, bytes4 selector) external;\n}\n"},"contracts/interfaces/IPoolManager.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPoolManager {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Register a new pool.\n  /// @param pool The address of fx pool.\n  event RegisterPool(address indexed pool);\n\n  /// @notice Emitted when the reward splitter contract is updated.\n  /// @param pool The address of fx pool.\n  /// @param oldSplitter The address of previous reward splitter contract.\n  /// @param newSplitter The address of current reward splitter contract.\n  event UpdateRewardSplitter(address indexed pool, address indexed oldSplitter, address indexed newSplitter);\n\n  /// @notice Emitted when token rate is updated.\n  /// @param scalar The token scalar to reach 18 decimals.\n  /// @param provider The address of token rate provider.\n  event UpdateTokenRate(address indexed token, uint256 scalar, address provider);\n\n  /// @notice Emitted when pool capacity is updated.\n  /// @param pool The address of fx pool.\n  /// @param collateralCapacity The capacity for collateral token.\n  /// @param debtCapacity The capacity for debt token.\n  event UpdatePoolCapacity(address indexed pool, uint256 collateralCapacity, uint256 debtCapacity);\n\n  /// @notice Emitted when position is updated.\n  /// @param pool The address of pool where the position belongs to.\n  /// @param position The id of the position.\n  /// @param deltaColls The amount of collateral token changes.\n  /// @param deltaDebts The amount of debt token changes.\n  /// @param protocolFees The amount of protocol fees charges.\n  event Operate(\n    address indexed pool,\n    uint256 indexed position,\n    int256 deltaColls,\n    int256 deltaDebts,\n    uint256 protocolFees\n  );\n\n  /// @notice Emitted when redeem happened.\n  /// @param pool The address of pool redeemed.\n  /// @param colls The amount of collateral tokens redeemed.\n  /// @param debts The amount of debt tokens redeemed.\n  /// @param protocolFees The amount of protocol fees charges.\n  event Redeem(address indexed pool, uint256 colls, uint256 debts, uint256 protocolFees);\n\n  /// @notice Emitted when someone harvest pending rewards.\n  /// @param caller The address of caller.\n  /// @param amountRewards The amount of total harvested rewards.\n  /// @param amountFunding The amount of total harvested funding.\n  /// @param performanceFee The amount of harvested rewards distributed to protocol revenue.\n  /// @param harvestBounty The amount of harvested rewards distributed to caller as harvest bounty.\n  event Harvest(\n    address indexed caller,\n    address indexed pool,\n    uint256 amountRewards,\n    uint256 amountFunding,\n    uint256 performanceFee,\n    uint256 harvestBounty\n  );\n\n  /// @notice Emitted when debt is reduced by someone.\n  /// @param pool The address of pool reduced.\n  /// @param amount The amount of debt token reduced.\n  event ReduceDebt(address indexed pool, uint256 amount);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of fxUSD.\n  function fxUSD() external view returns (address);\n\n  /// @notice The address of counterparty PoolManager.\n  function counterparty() external view returns (address);\n\n  /// @notice The address of `PoolConfiguration` contract.\n  function configuration() external view returns (address);\n\n  /// @notice The address of reward splitter.\n  function rewardSplitter(address pool) external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Open a new position or operate on an old position.\n  /// @param pool The address of pool to operate.\n  /// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.\n  /// @param newColl The amount of collateral token to supply (positive value) or withdraw (negative value).\n  /// @param newDebt The amount of debt token to borrow (positive value) or repay (negative value).\n  /// @return actualPositionId The id of this position.\n  function operate(\n    address pool,\n    uint256 positionId,\n    int256 newColl,\n    int256 newDebt\n  ) external returns (uint256 actualPositionId);\n\n  /// @notice Redeem debt tokens to get collateral tokens.\n  /// @param pool The address of pool to redeem.\n  /// @param debts The amount of debt tokens to redeem.\n  /// @param minColls The minimum amount of collateral tokens should redeem.\n  /// @return actualDebts The actual amount of debt tokens used.\n  /// @return colls The amount of collateral tokens redeemed.\n  function redeem(address pool, uint256 debts, uint256 minColls) external returns (uint256 actualDebts, uint256 colls);\n\n  /// @notice Harvest pending rewards of the given pool.\n  /// @param pool The address of pool to harvest.\n  /// @return amountRewards The amount of rewards harvested.\n  /// @return amountFunding The amount of funding harvested.\n  function harvest(address pool) external returns (uint256 amountRewards, uint256 amountFunding);\n\n  /// @notice Reduce the debt of a pool. This function is only callable by whitelisted addresses.\n  /// @param pool The address of the pool to reduce debt for.\n  /// @param amount The amount of debt token to reduce.\n  function reduceDebt(address pool, uint256 amount) external;\n}\n"},"contracts/interfaces/IProtocolFees.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IProtocolFees {\n  /**********\n   * Events *\n   **********/\n\n  /// @notice Emitted when the reserve pool contract is updated.\n  /// @param oldReservePool The address of previous reserve pool.\n  /// @param newReservePool The address of current reserve pool.\n  event UpdateReservePool(address indexed oldReservePool, address indexed newReservePool);\n\n  /// @notice Emitted when the treasury contract is updated.\n  /// @param oldTreasury The address of previous treasury contract.\n  /// @param newTreasury The address of current treasury contract.\n  event UpdateTreasury(address indexed oldTreasury, address indexed newTreasury);\n\n  /// @notice Emitted when the open revenue pool contract is updated.\n  /// @param oldPool The address of previous revenue pool contract.\n  /// @param newPool The address of current revenue pool contract.\n  event UpdateOpenRevenuePool(address indexed oldPool, address indexed newPool);\n\n  /// @notice Emitted when the close revenue pool contract is updated.\n  /// @param oldPool The address of previous revenue pool contract.\n  /// @param newPool The address of current revenue pool contract.\n  event UpdateCloseRevenuePool(address indexed oldPool, address indexed newPool);\n\n  /// @notice Emitted when the misc revenue pool contract is updated.\n  /// @param oldPool The address of previous revenue pool contract.\n  /// @param newPool The address of current revenue pool contract.\n  event UpdateMiscRevenuePool(address indexed oldPool, address indexed newPool);\n\n  /// @notice Emitted when the ratio for treasury is updated.\n  /// @param oldRatio The value of the previous ratio, multiplied by 1e9.\n  /// @param newRatio The value of the current ratio, multiplied by 1e9.\n  event UpdateRewardsExpenseRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the ratio for treasury is updated.\n  /// @param oldRatio The value of the previous ratio, multiplied by 1e9.\n  /// @param newRatio The value of the current ratio, multiplied by 1e9.\n  event UpdateFundingExpenseRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the ratio for treasury is updated.\n  /// @param oldRatio The value of the previous ratio, multiplied by 1e9.\n  /// @param newRatio The value of the current ratio, multiplied by 1e9.\n  event UpdateLiquidationExpenseRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the ratio for harvester is updated.\n  /// @param oldRatio The value of the previous ratio, multiplied by 1e9.\n  /// @param newRatio The value of the current ratio, multiplied by 1e9.\n  event UpdateHarvesterRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the flash loan fee ratio is updated.\n  /// @param oldRatio The value of the previous ratio, multiplied by 1e9.\n  /// @param newRatio The value of the current ratio, multiplied by 1e9.\n  event UpdateFlashLoanFeeRatio(uint256 oldRatio, uint256 newRatio);\n\n  /// @notice Emitted when the redeem fee ratio is updated.\n  /// @param oldRatio The value of the previous ratio, multiplied by 1e9.\n  /// @param newRatio The value of the current ratio, multiplied by 1e9.\n  event UpdateRedeemFeeRatio(uint256 oldRatio, uint256 newRatio);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the fee ratio distributed as protocol revenue in funding costs, multiplied by 1e9.\n  function getFundingExpenseRatio() external view returns (uint256);\n\n  /// @notice Return the fee ratio distributed as protocol revenue in general rewards, multiplied by 1e9.\n  function getRewardsExpenseRatio() external view returns (uint256);\n\n  /// @notice Return the fee ratio distributed as protocol revenue in liquidation/rebalance, multiplied by 1e9.\n  function getLiquidationExpenseRatio() external view returns (uint256);\n\n  /* @dev removed to reduce codesize, since it is not used.\n  /// @notice Return the fee ratio distributed to fxBASE in funding costs, multiplied by 1e9.\n  function getFundingFxSaveRatio() external view returns (uint256);\n  */\n\n  /* @dev removed to reduce codesize, since it is not used.\n  /// @notice Return the fee ratio distributed to fxBASE in general rewards, multiplied by 1e9.\n  function getRewardsFxSaveRatio() external view returns (uint256);\n  */\n\n  /// @notice Return the fee ratio distributed ad harvester bounty, multiplied by 1e9.\n  function getHarvesterRatio() external view returns (uint256);\n\n  /// @notice Return the flash loan fee ratio, multiplied by 1e9.\n  function getFlashLoanFeeRatio() external view returns (uint256);\n\n  /// @notice Return the redeem fee ratio, multiplied by 1e9.\n  function getRedeemFeeRatio() external view returns (uint256);\n\n  /// @notice Return the address of reserve pool.\n  function reservePool() external view returns (address);\n\n  /// @notice Return the address of protocol treasury.\n  function treasury() external view returns (address);\n\n  /// @notice Return the address of protocol revenue pool.\n  function openRevenuePool() external view returns (address);\n\n  /// @notice Return the address of protocol revenue pool.\n  function closeRevenuePool() external view returns (address);\n\n  /// @notice Return the address of protocol revenue pool.\n  function miscRevenuePool() external view returns (address);\n\n  /// @notice Return the amount of protocol open fees accumulated by the given pool.\n  function accumulatedPoolOpenFees(address pool) external view returns (uint256);\n\n  /// @notice Return the amount of protocol close fees accumulated by the given pool.\n  function accumulatedPoolCloseFees(address pool) external view returns (uint256);\n\n  /// @notice Return the amount of protocol misc fees accumulated by the given pool.\n  function accumulatedPoolMiscFees(address pool) external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Withdraw accumulated pool fee for the given pool lists.\n  /// @param pools The list of pool addresses to withdraw.\n  function withdrawAccumulatedPoolFee(address[] memory pools) external;\n}\n"},"contracts/interfaces/IReservePool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IReservePool {\n  /// @notice Emitted when the market request bonus.\n  /// @param token The address of the token requested.\n  /// @param receiver The address of token receiver.\n  /// @param bonus The amount of bonus token.\n  event RequestBonus(address indexed token, address indexed receiver, uint256 bonus);\n\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice Return the balance of token in this contract.\n  function getBalance(address token) external view returns (uint256);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Request bonus token from Reserve Pool.\n  /// @param token The address of token to request.\n  /// @param receiver The address recipient for the bonus token.\n  /// @param bonus The amount of bonus token to send.\n  function requestBonus(address token, address receiver, uint256 bonus) external;\n\n  /// @notice Withdraw dust assets in this contract.\n  /// @param token The address of token to withdraw.\n  /// @param amount The amount of token to withdraw.\n  /// @param recipient The address of token receiver.\n  function withdrawFund(address token, uint256 amount, address recipient) external;\n}\n"},"contracts/interfaces/IShortPool.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport { IPool } from \"./IPool.sol\";\n\ninterface IShortPool is IPool {\n  /*************************\n   * Public View Functions *\n   *************************/\n\n  /// @notice The address of the debt token.\n  function debtToken() external view returns (address);\n\n  /// @notice The address of the credit note token.\n  function creditNote() external view returns (address);\n\n  /****************************\n   * Public Mutated Functions *\n   ****************************/\n\n  /// @notice Whether the pool is under collateral.\n  /// @return underCollateral Whether the pool is under collateral.\n  /// @return shortfall The amount of shortfall raw debt token.\n  function isUnderCollateral() external returns (bool underCollateral, uint256 shortfall);\n\n  /// @notice Kill the pool.\n  function kill() external;\n\n  /// @notice Redeem credit note to get collateral tokens.\n  /// @param creditNoteAmount The amount of credit note to redeem.\n  /// @return rawColls The amount of collateral tokens to redeemed.\n  function redeemByCreditNote(uint256 creditNoteAmount) external returns (uint256 rawColls);\n}\n"},"contracts/rate-provider/interfaces/IRateProvider.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IRateProvider {\n  /// @notice Return the exchange rate from wrapped token to underlying rate,\n  /// multiplied by 1e18.\n  function getRate() external view returns (uint256);\n}\n"},"contracts/voting-escrow/interfaces/ISmartWalletChecker.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ISmartWalletChecker {\n  function check(address) external view returns (bool);\n}"}},"matchId":"29769746","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2026-05-26T00:21:34Z","match":"exact_match","chainId":"56","address":"0xA9Cab826B5b471bdcaE7186cfE988327fE873929"}