creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts/access/AccessControl.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 \"./IAccessControl.sol\";\nimport {Context} from \"../utils/Context.sol\";\nimport {ERC165} from \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n    struct RoleData {\n        mapping(address account => bool) hasRole;\n        bytes32 adminRole;\n    }\n\n    mapping(bytes32 role => RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with an {AccessControlUnauthorizedAccount} error including the required role.\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual returns (bool) {\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        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        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        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        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/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/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/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/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/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/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/ERC165.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 \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165 is IERC165 {\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/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/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Muldiv operation overflow.\n     */\n    error MathOverflowedMulDiv();\n\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            return a / b;\n        }\n\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            if (denominator <= prod1) {\n                revert MathOverflowedMulDiv();\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"
      },
      "contracts/base/auth/AccessControlDS.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\nimport {AccessControl} from \"@openzeppelin/contracts/access/AccessControl.sol\";\nimport {OwnableReadonlyDS} from \"./OwnableReadonlyDS.sol\";\n\nabstract contract AccessControlDS is AccessControl, OwnableReadonlyDS {\n    function hasRole(bytes32 _role, address _account) public view virtual override returns (bool) {\n        return (isOwnerRole(_role) && _owner() == _account) || super.hasRole(_role, _account);\n    }\n\n    function isOwnerRole(bytes32 _role) private pure returns (bool) {\n        return _role == DEFAULT_ADMIN_ROLE;\n    }\n}\n"
      },
      "contracts/base/auth/OwnableReadonly.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\nimport {UnauthorizedAccount} from \"contracts/interfaces/base/CommonErrors.sol\";\nimport {Address} from \"contracts/libraries/Address.sol\";\n\n/**\n * @dev We intentionally do not expose \"owner()\" publicly\n * due to possible conflicts with \"OwnershipFacet\"\n * https://github.com/mudgen/diamond-3-hardhat/blob/main/contracts/facets/OwnershipFacet.sol\n */\nabstract contract OwnableReadonly {\n    using Address for bytes32;\n\n    modifier onlyOwner() {\n        enforceIsContractOwner();\n        _;\n    }\n\n    function _owner() internal view returns (address) {\n        return _ownerSlot().get();\n    }\n\n    function _ownerSlot() internal pure virtual returns (bytes32);\n\n    function enforceIsContractOwner() private view {\n        if (msg.sender != _owner()) revert UnauthorizedAccount(msg.sender);\n    }\n}\n"
      },
      "contracts/base/auth/OwnableReadonlyDS.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\nimport {DiamondLibrary} from \"contracts/libraries/DiamondLibrary.sol\";\nimport {OwnableReadonly} from \"./OwnableReadonly.sol\";\n\n/**\n * @notice Use DiamondStorage's owner slot for OwnableReadonly\n */\nabstract contract OwnableReadonlyDS is OwnableReadonly {\n    function _ownerSlot() internal pure override returns (bytes32 slot_) {\n        DiamondLibrary.DiamondStorage storage ds = DiamondLibrary.diamondStorage();\n        assembly {\n            // DiamondLib will not change so it's safe to hardcode owner offset here\n            let ownerOffsetInDiamondStorage := 4\n            slot_ := add(ds.slot, ownerOffsetInDiamondStorage)\n        }\n    }\n}\n"
      },
      "contracts/interfaces/base/CommonErrors.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\n/**\n * @notice An error indicating that the amount for the specified token is zero.\n * @param token The address of the token with a zero amount.\n */\nerror AmountMustNotBeZero(address token);\n\n/**\n * @notice An error indicating that an address must not be zero.\n */\nerror AddressMustNotBeZero();\n\n/**\n * @notice An error indicating that an array must not be empty.\n */\nerror ArrayMustNotBeEmpty();\n\n/**\n * @notice An error indicating storage is already up to date and doesn't need further processing.\n * @dev This error is thrown when attempting to update an entity(s) that is(are) already up to date.\n */\nerror AlreadyUpToDate();\n\n/**\n * @notice An error indicating that an action is unauthorized for the specified account.\n * @param account The address of the unauthorized account.\n */\nerror UnauthorizedAccount(address account);\n"
      },
      "contracts/interfaces/liquidityManagement/insuranceFund/Debt.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\n/**\n * @title FundDebt\n * @notice This type of debt is created following an uncovered liquidation due to rapid changes in the market.\n * @notice Authorization for this debt can be granted by the account having `DEBT_AUTHORITY` role in Insurance Fund.\n * Funds to cover such debts are accumulated from all liquidations with a surplus in tokens.\n * @dev `amount` The debt amount allocated to the Pool.\n * @dev `reward` The amount designated as a reward for Liquidity Providers in the Pool.\n */\nstruct FundDebt {\n    uint128 amount;\n    uint128 reward;\n}\n"
      },
      "contracts/interfaces/liquidityManagement/insuranceFund/IFund.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.22;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPool} from \"contracts/interfaces/liquidityManagement/liquidityPool/IPool.sol\";\nimport {FundDebt} from \"./Debt.sol\";\n\ninterface IFund {\n    /**\n     * @notice Emitted when tokens are supplied to the insurance fund.\n     * @dev Emitted from [`supply()`](#supply).\n     * @param amount The amount of tokens supplied.\n     */\n    event Supplied(uint256 indexed amount);\n\n    /**\n     * @notice Emitted when tokens are forwarded to the liquidity pool.\n     * @dev Emitted from [`forward()`](#forward).\n     * @param amount The amount of tokens forwarded.\n     */\n    event Forwarded(uint256 indexed amount);\n\n    /**\n     * @notice Emitted when a debt is successfully authorized and forwarded.\n     * @dev Emitted from [`authorize()`](#authorize).\n     * @param id The identifier of the authorized debt.\n     */\n    event DebtPaid(bytes32 indexed id);\n\n    /**\n     * @notice Error indicating that a debt with the specified ID does not exist.\n     * @dev Fired from [`authorize()`](#authorize).\n     */\n    error DebtDoesNotExists(bytes32 id);\n\n    /**\n     * @notice Error indicating that the sum of the debt amount and rewards exceeds the contract's token balance.\n     * @dev Fired from [`authorize()`](#authorize).\n     */\n    error DebtAmountExceedsBalance(bytes32 id);\n\n    /**\n     * @notice Error indicating that the account sent transaction has zero token balance on the contract.\n     * @dev Fired from [`withdrawAll()`](#withdrawall).\n     */\n    error NothingToWithdraw();\n\n    /**\n     * @notice Allows authorized addresses to supply tokens in Insurance Fund.\n     * @dev Requires `msg.sender` to have the `keccak256('FORWARDER_ROLE')` role within the fund contract,\n     *      otherwise, it throws an `\"AccessControl: account msg.sender is missing role keccak256('FORWARDER_ROLE')\"` error.\n     * @dev Emits a [`Supplied()`](#supplied) event on successful supply.\n     * @param amount of tokens to supply.\n     * @param beneficiary optional address which may receive surplus from the future spending.\n     */\n    function supply(uint256 amount, address beneficiary) external;\n\n    /**\n     * @notice Allows authorized addresses to forward tokens in Liquidity Pool\n     *      (see [`IPool.returnAndDistribute()`](/interfaces/liquidityManagement/liquidityPool/IPool.sol/interface.IPool.html#returnanddistribute)).\n     * @dev Requires `msg.sender` to have the `keccak256('FORWARDER_ROLE')` role within the fund contract,\n     *      otherwise, it throws an `\"AccessControl: account msg.sender is missing role keccak256('FORWARDER_ROLE')\"` error.\n     * @dev Emits a [`Forwarded()`](#forwarded) event on success.\n     * @param amount of token to return to liquidity pool.\n     * @param rewards amount of rewards to add to liquidity pool.\n     */\n    function forward(uint256 amount, uint256 rewards) external;\n\n    /**\n     * @notice Allows authorized addresses to approve a debt and potentially [`forward()`](#forward) it.\n     * @dev Throws a [`DebtDoesNotExists()`](#debtdoesnotexists) error if the corresponding `amount` and `reward` are zero.\n     * @dev Throws a [`DebtAmountExceedsBalance()`](#debtamountexceedsbalance) error if the sum of `amount` and `reward` exceeds the contract's token balance.\n     * @dev Emits a [`DebtPaid()`](#debtpaid) event on success.\n     * @param id Identifier of the debt to authorize.\n     */\n    function authorize(bytes32 id) external;\n\n    /**\n     * @notice Allows account owner to withdraw its whole token balance.\n     * @dev Throws a [`NothingToWithdraw()`](#nothingtowithdraw) error if the account has zero balance.\n     */\n    function withdrawAll() external;\n\n    /**\n     * @notice Returns contract balance.\n     * @return returns The internal token balance of the contract.\n     */\n    function balance() external view returns (uint256);\n\n    /**\n     * @notice Returns account balance.\n     * @param account The address of the account to check the balance of.\n     * @return returns The balance of the account.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @notice Returns the details of a debt.\n     * @param id Identifier of the debt.\n     * @return A [`FundDebt`](../Debt.sol/struct.FundDebt.html) struct containing information about the debt.\n     */\n    function getDebt(bytes32 id) external view returns (FundDebt memory);\n\n    /**\n     * @notice Liquidity pool associated with this insurance fund.\n     */\n    function pool() external view returns (IPool);\n\n    /**\n     * @notice ERC20 token associated with the pool associated with this fund.\n     */\n    function token() external view returns (IERC20);\n}\n"
      },
      "contracts/interfaces/liquidityManagement/insuranceFund/IFundInitializer.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\ninterface IFundInitializer {\n    error NotInitialized();\n\n    function initialize(address liquidityPool, address debtAuthority) external;\n}\n"
      },
      "contracts/interfaces/liquidityManagement/liquidityPool/IPool.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\n/**\n * @title IPool\n * @notice Interface for a liquidity pool.\n */\ninterface IPool {\n    /**\n     * @notice Emitted when tokens are borrowed from the pool.\n     * @param amount The amount of tokens borrowed.\n     * @dev Emitted from [`borrow()`](#borrow).\n     */\n    event Borrowed(uint256 amount);\n\n    /**\n     * @notice Emitted when tokens are claimed.\n     * @param recipient The address of the recipient.\n     * @param amount The amount of rewards claimed.\n     * @dev Emitted from [`claim()`](#claim).\n     */\n    event Claimed(address indexed recipient, uint256 amount);\n\n    /**\n     * @notice Emitted when tokens are deposited into a liquidity pool.\n     * @param depositor The address of the depositor.\n     * @param amount The amount of tokens deposited.\n     * @dev Emitted from [`deposit()`](#deposit).\n     */\n    event Deposited(address indexed depositor, uint256 amount);\n\n    /**\n     * @notice Emitted when tokens are returned to the pool, repaying debts, and triggering an epoch switch.\n     * @param distributed The amount of tokens distributed as rewards in the current epoch.\n     * @param returned The amount of tokens used to repay debts.\n     * @dev Emitted from [`returnAndDistribute()`](#returnanddistribute).\n     */\n    event Returned(uint256 returned, uint256 distributed);\n\n    /**\n     * @notice Emitted when tokens are withdrawn from the pool.\n     * @param amount The amount of tokens withdrawn.\n     * @param recipient The address of the recipient.\n     * @dev Emitted from [`withdraw()`](#withdraw).\n     */\n    event Withdrawn(address indexed recipient, uint256 amount);\n\n    /**\n     * @notice Fired from [`borrow()`](#borrow).\n     * @dev Error indicating that the borrower's requested amount exceeds the available balance in the pool.\n     */\n    error BorrowAmountExceedsBalance();\n\n    /**\n     * @notice Error indicating that the Merkle tree verification failed.\n     * @dev Fired from [`deposit()`](#deposit).\n     */\n    error MerkleTreeVerificationFailed();\n\n    /**\n     * @notice Error indicating that the total deposit threshold has been exceeded by the user's deposit.\n     * @dev Fired from [`deposit()`](#deposit).\n     */\n    error TotalDepositThresholdExceeded();\n\n    /**\n     * @notice Error indicating that there are no pending rewards for the user.\n     * @dev Fired from [`claim()`](#claim).\n     */\n    error NoPendingRewards();\n\n    /**\n     * @notice Error indicating that the user is trying to withdraw an amount greater than their position's value.\n     * @dev Fired from [`withdraw()`](#withdraw).\n     */\n    error WithdrawAmountExceedsBalance();\n\n    /**\n     * @notice Allows whitelisted addresses to deposit tokens into the liquidity pool.\n     * @dev If verification is not disabled (see [`IMerkleTreeWhitelist.setRoot()`](/interfaces/liquidityManagement/liquidityPool/IMerkleTreeWhitelist.sol/interface.IMerkleTreeWhitelist.html#setroot)),\n     *      it requires a valid Merkle Proof for `msg.sender` to confirm deposit authorization.\n     * @dev Throws a [`TotalDepositThresholdExceeded()`](#totaldepositthresholdexceeded) error if `amount` + `token.balanceOf(pool)` exceeds [`thresholdOnTotalDeposit()`](#thresholdontotaldeposit).\n     * @dev Emits a [`Deposited()`](#deposited) event on successful deposit.\n     * @param amount The amount of tokens to deposit.\n     * @param permission Merkle Proof for `msg.sender`, confirming deposit authorization.\n     */\n    function deposit(uint128 amount, bytes32[] calldata permission) external;\n\n    /**\n     * @notice Allows a user to withdraw tokens from the liquidity pool.\n     * @dev If the pool has a sufficient token balance, tokens will be sent immediately to the specified `recipient`.\n     *      Otherwise, the withdrawal amount will be added to the debt queue for processing during [`returnAndDistribute()`](#returnanddistribute).\n     * @dev If `recipient` is `address(0)`, it will be changed to `msg.sender`.\n     * @dev Throws a [`WithdrawAmountExceedsBalance()`](#withdrawamountexceedsbalance) error if the user has an insufficient balance.\n     * @dev Emits a [`Withdrawn()`](#withdrawn) event on successful withdrawal.\n     * @param amount The amount of tokens to withdraw.\n     * @param recipient The address that will receive the withdrawn tokens. If `address(0)` is passed, it will be changed to `msg.sender`.\n     */\n    function withdraw(uint128 amount, address recipient) external;\n\n    /**\n     * @notice Allows a user to claim rewards earned in the liquidity pool.\n     * @dev If the pool has a sufficient token balance, rewards will be sent immediately to the `recipient`.\n     *      Otherwise, the rewards will be added to the debt queue for processing during [`returnAndDistribute()`](#returnanddistribute).\n     * @dev If `recipient` is `address(0)`, it will be changed to `msg.sender`.\n     * @dev Throws a [`NoPendingRewards()`](#nopendingrewards) error if the user has no pending rewards (see [`getPendingRewards()`](#getpendingrewards)).\n     * @dev Emits a [`Claimed()`](#claimed) event on successful claim.\n     * @param recipient The address to receive the claimed rewards. If `address(0)` is passed, it will be changed to `msg.sender`.\n     */\n    function claim(address recipient) external;\n\n    /**\n     * @notice Allows authorized addresses to borrow tokens from the pool.\n     * @dev Requires `msg.sender` to have the `keccak256('BORROWER_ROLE')` role within the pool contract,\n     *      otherwise, it throws an `\"AccessControl: account msg.sender is missing role keccak256('BORROWER_ROLE')\"` error.\n     * @dev Throws a [`BorrowAmountExceedsBalance()`](#borrowamountexceedsbalance) error if the pool's token balance is less than the requested amount.\n     * @dev Emits a [`Borrowed()`](#borrowed) event on successful borrow.\n     * @param amount The amount of tokens to borrow.\n     */\n    function borrow(uint256 amount) external;\n\n    /**\n     * @notice Allows authorized addresses to deposit tokens into the liquidity pool, pay off as many debts as possible,\n     * distribute rewards for the current epoch, and start a new epoch.\n     * @dev Requires `msg.sender` to have the `keccak256('REPAYER_ROLE')` role within the pool contract;\n     *      otherwise, it throws an `\"AccessControl: account msg.sender is missing role keccak256('REPAYER_ROLE')\"` error.\n     * @dev Emits a [`Returned()`](#returned) event upon successful return.\n     * @param amount Amount of tokens used for debt payment.\n     * @param rewards Amount of tokens to distribute as rewards for the current epoch.\n     */\n    function returnAndDistribute(uint256 amount, uint256 rewards) external;\n\n    /**\n     * @notice Returns the token address associated with the pool.\n     * @return Token address.\n     */\n    function token() external view returns (address);\n\n    /**\n     * @notice Returns the current threshold on the total deposit value. The pool's token balance cannot exceed this threshold.\n     * @return Current threshold value.\n     */\n    function thresholdOnTotalDeposit() external view returns (uint256);\n\n    /**\n     * @notice Returns amount of tokens currently deposited into the pool.\n     * A portion of that may be allocated as leverage onto margin accounts.\n     * @return Amount of deposited tokens to the pool.\n     */\n    function totalDeposited() external view returns (uint256);\n\n    /**\n     * @notice Calculates the pending rewards that a user can claim.\n     * @param user address for which to calculate rewards.\n     * @return rewards amount of tokens that the user can claim right now.\n     */\n    function getPendingRewards(address user) external view returns (uint256 rewards);\n\n    /**\n     * @notice Retrieves the amount of tokens owned by a user in the pool.\n     * @param user address.\n     * @return balance amount of tokens.\n     */\n    function getPositionInfo(address user) external view returns (uint256 balance);\n}\n"
      },
      "contracts/libraries/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\nlibrary Address {\n    address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n    function set(bytes32 _slot, address _value) internal {\n        assembly {\n            sstore(_slot, _value)\n        }\n    }\n\n    function get(bytes32 _slot) internal view returns (address result_) {\n        assembly {\n            result_ := sload(_slot)\n        }\n    }\n\n    function isEth(address _token) internal pure returns (bool) {\n        return _token == ETH || _token == address(0);\n    }\n\n    function sort(address _a, address _b) internal pure returns (address, address) {\n        return _a < _b ? (_a, _b) : (_b, _a);\n    }\n\n    function sort(address[4] memory _array) internal pure returns (address[4] memory _sorted) {\n        // Sorting network for the array of length 4\n        (_sorted[0], _sorted[1]) = sort(_array[0], _array[1]);\n        (_sorted[2], _sorted[3]) = sort(_array[2], _array[3]);\n\n        (_sorted[0], _sorted[2]) = sort(_sorted[0], _sorted[2]);\n        (_sorted[1], _sorted[3]) = sort(_sorted[1], _sorted[3]);\n        (_sorted[1], _sorted[2]) = sort(_sorted[1], _sorted[2]);\n    }\n}\n"
      },
      "contracts/libraries/DiamondLibrary.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\nlibrary DiamondLibrary {\n    struct FacetAddressAndPosition {\n        address facetAddress;\n        uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array\n    }\n\n    struct FacetFunctionSelectors {\n        bytes4[] functionSelectors;\n        uint256 facetAddressPosition; // position of facetAddress in facetAddresses array\n    }\n\n    struct DiamondStorage {\n        // maps function selector to the facet address and\n        // the position of the selector in the facetFunctionSelectors.selectors array\n        mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;\n        // maps facet addresses to function selectors\n        mapping(address => FacetFunctionSelectors) facetFunctionSelectors;\n        // facet addresses\n        address[] facetAddresses;\n        // Used to query if a contract implements an interface.\n        // Used to implement ERC-165.\n        mapping(bytes4 => bool) supportedInterfaces;\n        // owner of the contract\n        address contractOwner;\n    }\n\n    bytes32 private constant DIAMOND_STORAGE_POSITION =\n        keccak256(\"diamond.standard.diamond.storage\");\n\n    function diamondStorage() internal pure returns (DiamondStorage storage ds_) {\n        bytes32 position = DIAMOND_STORAGE_POSITION;\n        assembly {\n            ds_.slot := position\n        }\n    }\n}\n"
      },
      "contracts/liquidityManagement/insuranceFund/fund/Fund.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport {IERC20, SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {AddressMustNotBeZero} from \"contracts/interfaces/base/CommonErrors.sol\";\nimport {IFund, IPool} from \"contracts/interfaces/liquidityManagement/insuranceFund/IFund.sol\";\nimport {\n    IFundInitializer\n} from \"contracts/interfaces/liquidityManagement/insuranceFund/IFundInitializer.sol\";\n\nimport {AccessControlDS} from \"contracts/base/auth/AccessControlDS.sol\";\n\nimport {FundDebt, MoneyAccountant} from \"../libraries/MoneyAccountant.sol\";\n\ncontract Fund is IFund, IFundInitializer, AccessControlDS, Initializable {\n    using SafeERC20 for IERC20;\n\n    address private immutable forwarder;\n\n    bytes32 public constant DEBT_ADMIN_ROLE = keccak256(\"DEBT_ADMIN_ROLE\");\n    bytes32 public constant FORWARDER_ROLE = keccak256(\"FORWARDER_ROLE\");\n\n    /// @inheritdoc IFund\n    IPool public pool;\n    /// @inheritdoc IFund\n    IERC20 public token;\n\n    modifier onlyInitialized() {\n        if (Initializable._getInitializedVersion() != 1) revert IFundInitializer.NotInitialized();\n        _;\n    }\n\n    constructor(address _forwarder) {\n        if (_forwarder == address(0)) revert AddressMustNotBeZero();\n        forwarder = _forwarder;\n    }\n\n    function initialize(address _liquidityPool, address debtAdmin) external override initializer {\n        _grantRole(DEFAULT_ADMIN_ROLE, tx.origin);\n        _grantRole(DEBT_ADMIN_ROLE, debtAdmin);\n        _grantRole(FORWARDER_ROLE, forwarder);\n\n        pool = IPool(_liquidityPool);\n        token = IERC20(pool.token());\n\n        token.safeIncreaseAllowance(_liquidityPool, type(uint256).max);\n    }\n\n    /// @inheritdoc IFund\n    function supply(\n        uint256 amount,\n        address beneficiary\n    ) external override onlyInitialized onlyRole(FORWARDER_ROLE) {\n        token.safeTransferFrom(msg.sender, address(this), amount);\n        MoneyAccountant.replenish(amount, beneficiary);\n\n        emit Supplied(amount);\n    }\n\n    /// @inheritdoc IFund\n    function forward(\n        uint256 amount,\n        uint256 reward\n    ) external override onlyInitialized onlyRole(FORWARDER_ROLE) {\n        (amount, reward) = MoneyAccountant.spendMoney(amount, reward);\n        _forward(amount, reward);\n    }\n\n    /// @inheritdoc IFund\n    function authorize(bytes32 id) external override onlyInitialized onlyRole(DEBT_ADMIN_ROLE) {\n        FundDebt memory debt = MoneyAccountant.getDebt(id);\n\n        if (debt.amount == 0 && debt.reward == 0) {\n            revert DebtDoesNotExists(id);\n        }\n        if (MoneyAccountant.balance() < debt.amount + debt.reward) {\n            revert DebtAmountExceedsBalance(id);\n        }\n\n        _forward(debt.amount, debt.reward);\n        MoneyAccountant.deleteDebt(id);\n        emit DebtPaid(id);\n    }\n\n    /// @inheritdoc IFund\n    function withdrawAll() external {\n        uint256 _balance = MoneyAccountant.balanceOf(msg.sender);\n        if (_balance == 0) revert NothingToWithdraw();\n        MoneyAccountant.deleteBalanceOf(msg.sender);\n        token.transfer(msg.sender, _balance);\n    }\n\n    /// @inheritdoc IFund\n    function balance() external view returns (uint) {\n        return MoneyAccountant.balance();\n    }\n\n    /// @inheritdoc IFund\n    function balanceOf(address account) external view returns (uint) {\n        return MoneyAccountant.balanceOf(account);\n    }\n\n    /// @inheritdoc IFund\n    function getDebt(bytes32 id) external view override returns (FundDebt memory) {\n        return MoneyAccountant.getDebt(id);\n    }\n\n    function _forward(uint256 amount, uint256 reward) private {\n        if (amount == 0 && reward == 0) return;\n\n        pool.returnAndDistribute(amount, reward);\n        emit Forwarded(amount);\n    }\n}\n"
      },
      "contracts/liquidityManagement/insuranceFund/libraries/DebtLibrary.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\ntype DebtID is bytes32;\n\nimport {FundDebt} from \"contracts/interfaces/liquidityManagement/insuranceFund/Debt.sol\";\n\nlibrary DebtLibrary {\n    error CannotCastToDebtStructDueToOverflow(uint256 from);\n\n    function createDebt(\n        uint256 amount,\n        uint256 reward,\n        uint256 salt\n    ) internal pure returns (DebtID id, FundDebt memory self) {\n        id = DebtID.wrap(keccak256(abi.encode(salt, amount, reward)));\n        if (amount > type(uint128).max) {\n            revert CannotCastToDebtStructDueToOverflow(amount);\n        }\n        if (reward > type(uint128).max) {\n            revert CannotCastToDebtStructDueToOverflow(reward);\n        }\n        self = FundDebt(uint128(amount), uint128(reward));\n    }\n}\n"
      },
      "contracts/liquidityManagement/insuranceFund/libraries/MoneyAccountant.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.22;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {DebtID, DebtLibrary, FundDebt} from \"./DebtLibrary.sol\";\n\nlibrary MoneyAccountant {\n    struct Storage {\n        uint256 nonce;\n        uint256 balance;\n        address beneficiary;\n        mapping(DebtID => FundDebt) debts;\n        mapping(address => uint) balanceOf;\n    }\n\n    bytes32 private constant STORAGE_SLOT = keccak256(\"MoneyAccountant storage slot V1\");\n\n    event NewDebt(DebtID);\n\n    error BeneficiaryIsAlreadySet();\n\n    function replenish(uint256 amount, address beneficiary) internal {\n        accounting().balance += amount;\n        if (beneficiary != address(0)) {\n            if (accounting().beneficiary == address(0)) accounting().beneficiary = beneficiary;\n            else revert BeneficiaryIsAlreadySet();\n        }\n    }\n\n    function spendMoney(\n        uint256 amount,\n        uint256 reward\n    ) internal returns (uint256 allowedAmount, uint256 allowedReward) {\n        bool haveSurplus;\n        (allowedAmount, allowedReward, haveSurplus) = calculateAcceptableExpenses(amount, reward);\n\n        uint256 allowedTotal = allowedAmount + allowedReward;\n        if (haveSurplus && accounting().beneficiary != address(0)) {\n            uint256 surplus = accounting().balance - allowedTotal;\n            accounting().balance = 0;\n            accounting().balanceOf[accounting().beneficiary] += surplus;\n            accounting().beneficiary = address(0);\n        } else {\n            accounting().balance -= allowedTotal;\n            createDebtIfNecessary(amount - allowedAmount, reward - allowedReward);\n        }\n\n        return (allowedAmount, allowedReward);\n    }\n\n    function deleteDebt(bytes32 id) internal {\n        delete accounting().debts[DebtID.wrap(id)];\n    }\n\n    function deleteBalanceOf(address account) internal {\n        delete accounting().balanceOf[account];\n    }\n\n    function balance() internal view returns (uint256) {\n        return accounting().balance;\n    }\n\n    function balanceOf(address account) internal view returns (uint256) {\n        return accounting().balanceOf[account];\n    }\n\n    function getDebt(bytes32 id) internal view returns (FundDebt memory) {\n        return accounting().debts[DebtID.wrap(id)];\n    }\n\n    function calculateAcceptableExpenses(\n        uint256 wantAmount,\n        uint256 wantReward\n    ) internal view returns (uint256 allowedAmount, uint256 allowedReward, bool haveSurplus) {\n        (bool ok, uint256 wantTotal) = Math.tryAdd(wantAmount, wantReward);\n        if (!ok) wantTotal = type(uint256).max;\n\n        if (accounting().balance >= wantTotal) return (wantAmount, wantReward, true);\n\n        unchecked {\n            /// @dev NOTE: if wantTotal == 0 then condition above is true\n            allowedAmount = Math.mulDiv(accounting().balance, wantAmount, wantTotal);\n            /// @dev NOTE: if surplus == 0 => allowedReward == 0\n            allowedReward = accounting().balance - allowedAmount;\n        }\n    }\n\n    function createDebtIfNecessary(uint256 differenceAmount, uint256 differenceReward) private {\n        if (differenceAmount != 0 || differenceReward != 0) {\n            (DebtID id, FundDebt memory debt) = DebtLibrary.createDebt(\n                differenceAmount,\n                differenceReward,\n                accounting().nonce++\n            );\n            accounting().debts[id] = debt;\n            emit NewDebt(id);\n        }\n    }\n\n    function accounting() private pure returns (Storage storage s) {\n        bytes32 slot = STORAGE_SLOT;\n        assembly {\n            s.slot := slot\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "viaIR": false,
      "optimizer": {
        "enabled": true,
        "runs": 1000000
      },
      "evmVersion": "paris",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "metadata": {
        "useLiteralContent": true
      },
      "libraries": {}
    }
  }}