creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlUpgradeable.sol\";\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../utils/StringsUpgradeable.sol\";\nimport \"../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {\n    function __AccessControl_init() internal onlyInitializing {\n    }\n\n    function __AccessControl_init_unchained() internal onlyInitializing {\n    }\n    struct RoleData {\n        mapping(address => bool) members;\n        bytes32 adminRole;\n    }\n\n    mapping(bytes32 => RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with a standardized message including the required role.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     *\n     * _Available since v4.1._\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n        return _roles[role].members[account];\n    }\n\n    /**\n     * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n     * Overriding this function changes the behavior of the {onlyRole} modifier.\n     *\n     * Format of the revert message is described in {_checkRole}.\n     *\n     * _Available since v4.6._\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Revert with a standard message if `account` is missing `role`.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert(\n                string(\n                    abi.encodePacked(\n                        \"AccessControl: account \",\n                        StringsUpgradeable.toHexString(account),\n                        \" is missing role \",\n                        StringsUpgradeable.toHexString(uint256(role), 32)\n                    )\n                )\n            );\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n        return _roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address account) public virtual override {\n        require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event. Note that unlike {grantRole}, this function doesn't perform any\n     * checks on the calling account.\n     *\n     * May emit a {RoleGranted} event.\n     *\n     * [WARNING]\n     * ====\n     * This function should only be called from the constructor when setting\n     * up the initial roles for the system.\n     *\n     * Using this function in any other way is effectively circumventing the admin\n     * system imposed by {AccessControl}.\n     * ====\n     *\n     * NOTE: This function is deprecated in favor of {_grantRole}.\n     */\n    function _setupRole(bytes32 role, address account) internal virtual {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        _roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual {\n        if (!hasRole(role, account)) {\n            _roles[role].members[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n        }\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual {\n        if (hasRole(role, account)) {\n            _roles[role].members[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n        }\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControlUpgradeable {\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     *\n     * _Available since v3.1._\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {AccessControl-_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(bytes32 role, address account) external;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized != type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155ReceiverUpgradeable is IERC165Upgradeable {\n    /**\n     * @dev Handles the receipt of a single ERC1155 token type. This function is\n     * called at the end of a `safeTransferFrom` after the balance has been updated.\n     *\n     * NOTE: To accept the transfer, this must return\n     * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n     * (i.e. 0xf23a6e61, or its own function selector).\n     *\n     * @param operator The address which initiated the transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param id The ID of the token being transferred\n     * @param value The amount of tokens being transferred\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n     */\n    function onERC1155Received(\n        address operator,\n        address from,\n        uint256 id,\n        uint256 value,\n        bytes calldata data\n    ) external returns (bytes4);\n\n    /**\n     * @dev Handles the receipt of a multiple ERC1155 token types. This function\n     * is called at the end of a `safeBatchTransferFrom` after the balances have\n     * been updated.\n     *\n     * NOTE: To accept the transfer(s), this must return\n     * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n     * (i.e. 0xbc197c81, or its own function selector).\n     *\n     * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param ids An array containing ids of each token being transferred (order and length must match values array)\n     * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n     */\n    function onERC1155BatchReceived(\n        address operator,\n        address from,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155Upgradeable is IERC165Upgradeable {\n    /**\n     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n     */\n    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n    /**\n     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n     * transfers.\n     */\n    event TransferBatch(\n        address indexed operator,\n        address indexed from,\n        address indexed to,\n        uint256[] ids,\n        uint256[] values\n    );\n\n    /**\n     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n     * `approved`.\n     */\n    event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n    /**\n     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n     *\n     * If an {URI} event was emitted for `id`, the standard\n     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n     * returned by {IERC1155MetadataURI-uri}.\n     */\n    event URI(string value, uint256 indexed id);\n\n    /**\n     * @dev Returns the amount of tokens of token type `id` owned by `account`.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function balanceOf(address account, uint256 id) external view returns (uint256);\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n     *\n     * Requirements:\n     *\n     * - `accounts` and `ids` must have the same length.\n     */\n    function balanceOfBatch(\n        address[] calldata accounts,\n        uint256[] calldata ids\n    ) external view returns (uint256[] memory);\n\n    /**\n     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n     *\n     * Emits an {ApprovalForAll} event.\n     *\n     * Requirements:\n     *\n     * - `operator` cannot be the caller.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n     *\n     * See {setApprovalForAll}.\n     */\n    function isApprovedForAll(address account, address operator) external view returns (bool);\n\n    /**\n     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n     *\n     * Emits a {TransferSingle} event.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n     * - `from` must have a balance of tokens of type `id` of at least `amount`.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n     * acceptance magic value.\n     */\n    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;\n\n    /**\n     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n     *\n     * Emits a {TransferBatch} event.\n     *\n     * Requirements:\n     *\n     * - `ids` and `amounts` must have the same length.\n     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n     * acceptance magic value.\n     */\n    function safeBatchTransferFrom(\n        address from,\n        address to,\n        uint256[] calldata ids,\n        uint256[] calldata amounts,\n        bytes calldata data\n    ) external;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20PermitUpgradeable {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../extensions/IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n    using AddressUpgradeable for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to\n     * 0 before setting it to a non-zero value.\n     */\n    function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20PermitUpgradeable token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165Upgradeable).interfaceId;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMathUpgradeable {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/MathUpgradeable.sol\";\nimport \"./math/SignedMathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = MathUpgradeable.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toString(int256 value) internal pure returns (string memory) {\n        return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMathUpgradeable.abs(value))));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, MathUpgradeable.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSetUpgradeable {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "contracts/interfaces/IChainlinkV3Aggregator.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.17;\n\ninterface IChainlinkV3Aggregator {\n    function decimals() external view returns (uint8);\n\n    function latestRoundData()\n        external\n        view\n        returns (\n            uint80 roundId,\n            int256 answer,\n            uint256 startedAt,\n            uint256 updatedAt,\n            uint80 answeredInRound\n        );\n}\n"
      },
      "contracts/interfaces/IStabilityPool.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface IStabilityPool {\n    function borrowForLiquidation(uint256 amount) external;\n\n    function repayFromLiquidation(uint256 borrowed, uint256 repaid) external;\n}\n"
      },
      "contracts/interfaces/IStableCoin.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';\n\ninterface IStableCoin is IERC20Upgradeable {\n    function mint(address _to, uint256 _value) external;\n\n    function burn(uint256 _value) external;\n\n    function burnFrom(address _from, uint256 _value) external;\n}\n"
      },
      "contracts/oasis/liquidations/ERC1155/ERC1155Liquidator.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';\n\nimport {IChainlinkV3Aggregator} from '../../../interfaces/IChainlinkV3Aggregator.sol';\nimport {IStabilityPool} from '../../../interfaces/IStabilityPool.sol';\nimport {ERC1155Vault} from '../../usd/ERC1155Vault.sol';\nimport {ERC1155ShezmuAuction} from './ERC1155ShezmuAuction.sol';\n\n/// @title Liquidator escrow contract\n/// @notice Liquidator contract that allows liquidator bots to liquidate positions without holding any stablecoins/NFTs.\n/// It's only meant to be used by DAO bots.\n/// The liquidated NFTs are auctioned.\ncontract ERC1155Liquidator is OwnableUpgradeable, IERC1155ReceiverUpgradeable {\n    using AddressUpgradeable for address;\n\n    error ZeroAddress();\n    error InvalidLength();\n    error UnknownVault(ERC1155Vault vault);\n    error InsufficientBalance(IERC20Upgradeable stablecoin);\n\n    struct OracleInfo {\n        IChainlinkV3Aggregator oracle;\n        uint8 decimals;\n    }\n\n    struct VaultInfo {\n        IERC20Upgradeable stablecoin;\n        IStabilityPool stabilityPool;\n        address nft;\n        uint256 tokenIndex;\n    }\n\n    ERC1155ShezmuAuction public auction;\n\n    mapping(IERC20Upgradeable => OracleInfo) public stablecoinOracle;\n    mapping(ERC1155Vault => VaultInfo) public vaultInfo;\n\n    // vault => auctionIndex => debtAmount\n    mapping(ERC1155Vault => mapping(uint256 => uint256))\n        public debtFromStabilityPool;\n    uint256 public totalDebtFromStabilityPool;\n\n    function initialize(address _auction) external initializer {\n        __Ownable_init();\n\n        if (_auction == address(0)) revert ZeroAddress();\n\n        auction = ERC1155ShezmuAuction(_auction);\n    }\n\n    /// @notice Allows any address to liquidate multiple positions at once.\n    /// It assumes enough stablecoin is in the contract.\n    /// The liquidated NFTs are sent to the DAO.\n    /// This function can be called by anyone, however the address calling it doesn't get any stablecoins/NFTs.\n    /// @dev This function doesn't revert if one of the positions is not liquidatable.\n    /// This is done to prevent situations in which multiple positions can't be liquidated\n    /// because of one not liquidatable position.\n    /// It reverts on insufficient balance.\n    /// @param _toLiquidate The user addresses to liquidate\n    /// @param _nftVault The address of the NFTVault\n    function liquidate(\n        address[] memory _toLiquidate,\n        ERC1155Vault _nftVault\n    ) external {\n        VaultInfo memory _vaultInfo = vaultInfo[_nftVault];\n        if (_vaultInfo.nft == address(0)) revert UnknownVault(_nftVault);\n\n        uint256 _length = _toLiquidate.length;\n        if (_length == 0) revert InvalidLength();\n\n        for (uint256 i; i < _length; ++i) {\n            address _user = _toLiquidate[i];\n\n            (uint256 collateral, uint256 debtPrincipal, ) = _nftVault.positions(\n                _user\n            );\n            uint256 _interest = _nftVault.getDebtInterest(_user);\n            uint256 debtAmount = debtPrincipal + _interest;\n\n            // borrow from stability pool\n            _vaultInfo.stabilityPool.borrowForLiquidation(debtAmount);\n\n            uint256 _balance = _vaultInfo.stablecoin.balanceOf(address(this));\n            _vaultInfo.stablecoin.approve(address(_nftVault), _balance);\n\n            _nftVault.liquidate(_user, address(this));\n            uint256 _normalizedDebt = _convertDebtAmount(\n                debtAmount,\n                stablecoinOracle[_vaultInfo.stablecoin]\n            );\n\n            IERC1155Upgradeable(_vaultInfo.nft).setApprovalForAll(\n                address(auction),\n                true\n            );\n\n            uint256 auctionIndex = auction.newAuction(\n                address(this),\n                IERC1155Upgradeable(_vaultInfo.nft),\n                _vaultInfo.tokenIndex,\n                collateral,\n                _normalizedDebt\n            );\n\n            totalDebtFromStabilityPool += debtAmount;\n            debtFromStabilityPool[_nftVault][auctionIndex] += debtAmount;\n\n            IERC1155Upgradeable(_vaultInfo.nft).setApprovalForAll(\n                address(auction),\n                false\n            );\n\n            //reset appoval\n            _vaultInfo.stablecoin.approve(address(_nftVault), 0);\n        }\n    }\n\n    /// @notice Allows the owner to repay for stability pool\n    /// @dev This will happen after auction close and sell it on market\n    function repayFromLiquidation(\n        ERC1155Vault _nftVault,\n        uint256 _auctionIndex,\n        uint256 _repayAmount\n    ) external onlyOwner {\n        VaultInfo memory _vaultInfo = vaultInfo[_nftVault];\n        if (_vaultInfo.nft == address(0)) {\n            revert UnknownVault(_nftVault);\n        }\n\n        uint256 debtAmount = debtFromStabilityPool[_nftVault][_auctionIndex];\n        debtFromStabilityPool[_nftVault][_auctionIndex] = 0;\n        totalDebtFromStabilityPool -= debtAmount;\n\n        _vaultInfo.stablecoin.approve(\n            address(_vaultInfo.stabilityPool),\n            _repayAmount\n        );\n        _vaultInfo.stabilityPool.repayFromLiquidation(debtAmount, _repayAmount);\n    }\n\n    /// @notice Allows the owner to add information about a NFTVault\n    function addNFTVault(\n        ERC1155Vault _nftVault,\n        IStabilityPool _stabilityPool\n    ) external onlyOwner {\n        if (address(_nftVault) == address(0)) revert ZeroAddress();\n\n        vaultInfo[_nftVault] = VaultInfo(\n            IERC20Upgradeable(_nftVault.stablecoin()),\n            _stabilityPool,\n            address(_nftVault.tokenContract()),\n            _nftVault.tokenIndex()\n        );\n    }\n\n    /// @notice Allows the owner to remove a NFTVault\n    function removeNFTVault(ERC1155Vault _nftVault) external onlyOwner {\n        delete vaultInfo[_nftVault];\n    }\n\n    /// @notice Allows the owner to set the oracle address for a specific stablecoin.\n    function setOracle(\n        IERC20Upgradeable _stablecoin,\n        IChainlinkV3Aggregator _oracle\n    ) external onlyOwner {\n        if (\n            address(_stablecoin) == address(0) || address(_oracle) == address(0)\n        ) revert ZeroAddress();\n\n        stablecoinOracle[_stablecoin] = OracleInfo(_oracle, _oracle.decimals());\n    }\n\n    /// @notice Allows the DAO to perform multiple calls using this contract (recovering funds/NFTs stuck in this contract)\n    /// @param _targets The target addresses\n    /// @param _calldatas The data to pass in each call\n    /// @param _values The ETH value for each call\n    function doCalls(\n        address[] memory _targets,\n        bytes[] memory _calldatas,\n        uint256[] memory _values\n    ) external payable onlyOwner {\n        for (uint256 i = 0; i < _targets.length; i++) {\n            _targets[i].functionCallWithValue(_calldatas[i], _values[i]);\n        }\n    }\n\n    function _convertDebtAmount(\n        uint256 _debt,\n        OracleInfo memory _info\n    ) internal view returns (uint256) {\n        if (address(_info.oracle) == address(0)) return _debt;\n        else {\n            //not checking for stale prices because we have no fallback oracle\n            //and stale/wrong prices are not an issue since they are only needed\n            //to set the minimum bid for the auction\n            (, int256 _answer, , , ) = _info.oracle.latestRoundData();\n\n            return (_debt * 10 ** _info.decimals) / uint256(_answer);\n        }\n    }\n\n    function onERC1155Received(\n        address operator,\n        address from,\n        uint256 id,\n        uint256 value,\n        bytes calldata data\n    ) external pure override returns (bytes4) {\n        return\n            bytes4(\n                keccak256(\n                    'onERC1155Received(address,address,uint256,uint256,bytes)'\n                )\n            );\n    }\n\n    function onERC1155BatchReceived(\n        address operator,\n        address from,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external pure override returns (bytes4) {\n        return\n            bytes4(\n                keccak256(\n                    'onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)'\n                )\n            );\n    }\n\n    function supportsInterface(\n        bytes4 interfaceId\n    ) external view returns (bool) {\n        return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId;\n    }\n}\n"
      },
      "contracts/oasis/liquidations/ERC1155/ERC1155ShezmuAuction.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';\n\nimport {RateLib} from '../../../utils/RateLib.sol';\n\ncontract ERC1155ShezmuAuction is\n    AccessControlUpgradeable,\n    ReentrancyGuardUpgradeable,\n    IERC1155ReceiverUpgradeable\n{\n    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;\n    using RateLib for RateLib.Rate;\n\n    error InvalidAmount();\n    error ZeroAddress();\n    error Unauthorized();\n    error InvalidBid(uint256 bidAmount);\n    error InvalidAuction(uint256 index);\n\n    event NewAuction(\n        uint256 indexed auctionId,\n        IERC1155Upgradeable indexed nft,\n        uint256 indexed index,\n        uint256 amount,\n        uint256 startTime\n    );\n    event NewBid(\n        uint256 indexed auctionId,\n        address indexed bidder,\n        uint256 bidValue\n    );\n    event AuctionCanceled(uint256 indexed auctionId);\n    event AuctionFailed(uint256 indexed auctionId);\n    event NFTClaimed(uint256 indexed auctionId);\n    event ETHClaimed(uint256 indexed auctionId);\n    event BidWithdrawn(\n        uint256 indexed auctionId,\n        address indexed account,\n        uint256 bidValue\n    );\n    event BidTimeIncrementChanged(uint256 newTime, uint256 oldTime);\n    event MinimumIncrementRateChanged(\n        RateLib.Rate newIncrementRate,\n        RateLib.Rate oldIncrementRate\n    );\n    event DurationChanged(uint256 newDuration, uint256 oldDuration);\n\n    struct Auction {\n        address creator;\n        IERC1155Upgradeable nftAddress;\n        uint256 nftIndex;\n        uint256 amount;\n        uint256 startTime;\n        uint256 endTime;\n        uint256 minBid;\n        address highestBidOwner;\n        bool ownerClaimed;\n        mapping(address => uint256) bids;\n    }\n\n    bytes32 public constant WHITELISTED_ROLE = keccak256('WHITELISTED_ROLE');\n\n    uint256 public auctionDuration;\n    uint256 public bidTimeIncrement;\n    uint256 public auctionsLength;\n\n    RateLib.Rate public minIncrementRate;\n\n    mapping(address => EnumerableSetUpgradeable.UintSet) internal userAuctions;\n    mapping(uint256 => Auction) public auctions;\n\n    function initialize(\n        uint256 _auctionDuration,\n        uint256 _bidTimeIncrement,\n        RateLib.Rate memory _incrementRate\n    ) external initializer {\n        __AccessControl_init();\n        __ReentrancyGuard_init();\n\n        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);\n\n        setAuctionDuration(_auctionDuration);\n        setBidTimeIncrement(_bidTimeIncrement);\n        setMinimumIncrementRate(_incrementRate);\n    }\n\n    /// @notice Allows whitelisted addresses to create a new auction in the next slot.\n    /// @param _nft The address of the NFT to sell\n    /// @param _idx The index of the NFT to sell\n    /// @param _minBid The minimum bid value\n    function newAuction(\n        address _owner,\n        IERC1155Upgradeable _nft,\n        uint256 _idx,\n        uint256 _amount,\n        uint256 _minBid\n    ) external onlyRole(WHITELISTED_ROLE) returns (uint256) {\n        uint256 _startTime = _getNextSlotStart();\n        return\n            _newAuction(\n                _owner,\n                _nft,\n                _idx,\n                _amount,\n                _startTime,\n                _startTime + auctionDuration,\n                _minBid\n            );\n    }\n\n    /// @notice Allows the admin to create a new auction\n    /// @param _nft The address of the NFT to sell\n    /// @param _idx The index of the NFT to sell\n    /// @param _startTime The time at which the auction starts\n    /// @param _endTime The time at which the auction ends\n    /// @param _minBid The minimum bid value\n    function newCustomAuction(\n        address _owner,\n        IERC1155Upgradeable _nft,\n        uint256 _idx,\n        uint256 _amount,\n        uint256 _startTime,\n        uint256 _endTime,\n        uint256 _minBid\n    ) external onlyRole(DEFAULT_ADMIN_ROLE) returns (uint256) {\n        return\n            _newAuction(\n                _owner,\n                _nft,\n                _idx,\n                _amount,\n                _startTime,\n                _endTime,\n                _minBid\n            );\n    }\n\n    /// @notice Allows the admin to cancel an ongoing auction with no bids\n    /// @param _auctionIndex The index of the auction to cancel\n    /// @param _nftRecipient The address to send the auctioned NFT to\n    function cancelAuction(\n        uint256 _auctionIndex,\n        address _nftRecipient\n    ) external nonReentrant {\n        if (_nftRecipient == address(0)) revert ZeroAddress();\n\n        Auction storage auction = auctions[_auctionIndex];\n        IERC1155Upgradeable _nft = auction.nftAddress;\n        if (address(_nft) == address(0)) revert InvalidAuction(_auctionIndex);\n        if (auction.creator != msg.sender) revert Unauthorized();\n        if (auction.highestBidOwner != address(0)) revert Unauthorized();\n\n        uint256 _nftIndex = auction.nftIndex;\n        uint256 _amount = auction.amount;\n        delete auctions[_auctionIndex];\n\n        _nft.safeTransferFrom(\n            address(this),\n            _nftRecipient,\n            _nftIndex,\n            _amount,\n            '0x'\n        );\n\n        emit AuctionCanceled(_auctionIndex);\n    }\n\n    /// @notice Allows users to bid on an auction. In case of multiple bids by the same user,\n    /// the actual bid value is the sum of all bids.\n    /// @param _auctionIndex The index of the auction to bid on\n    function bid(uint256 _auctionIndex) public payable nonReentrant {\n        Auction storage auction = auctions[_auctionIndex];\n        uint256 _endTime = auction.endTime;\n\n        if (\n            auction.startTime > block.timestamp ||\n            block.timestamp >= auction.endTime\n        ) revert Unauthorized();\n\n        uint256 _previousBid = auction.bids[msg.sender];\n        uint256 _bidValue = msg.value + _previousBid;\n        uint256 _currentMinBid = auction.bids[auction.highestBidOwner];\n        _currentMinBid += minIncrementRate.calculate(_currentMinBid);\n\n        if (_currentMinBid > _bidValue || auction.minBid > _bidValue)\n            revert InvalidBid(_bidValue);\n\n        auction.highestBidOwner = msg.sender;\n        auction.bids[msg.sender] = _bidValue;\n\n        if (_previousBid == 0)\n            assert(userAuctions[msg.sender].add(_auctionIndex));\n\n        uint256 _bidIncrement = bidTimeIncrement;\n        if (_bidIncrement > _endTime - block.timestamp)\n            auction.endTime = block.timestamp + _bidIncrement;\n\n        emit NewBid(_auctionIndex, msg.sender, _bidValue);\n    }\n\n    /// @notice Allows the highest bidder to claim the NFT they bid on if the auction is already over.\n    /// @param _auctionIndex The index of the auction to claim the NFT from\n    function claimNFT(uint256 _auctionIndex) external nonReentrant {\n        Auction storage auction = auctions[_auctionIndex];\n\n        if (\n            auction.highestBidOwner != msg.sender ||\n            auction.endTime > block.timestamp ||\n            !userAuctions[msg.sender].remove(_auctionIndex)\n        ) revert Unauthorized();\n\n        auction.nftAddress.safeTransferFrom(\n            address(this),\n            msg.sender,\n            auction.nftIndex,\n            auction.amount,\n            '0x'\n        );\n\n        emit NFTClaimed(_auctionIndex);\n    }\n\n    /// @notice Allows bidders to withdraw their bid. Only works if `msg.sender` isn't the highest bidder.\n    /// @param _auctionIndex The auction to claim the bid from.\n    function withdrawBid(uint256 _auctionIndex) public nonReentrant {\n        Auction storage auction = auctions[_auctionIndex];\n\n        if (auction.highestBidOwner == msg.sender) revert Unauthorized();\n\n        uint256 _bidAmount = auction.bids[msg.sender];\n        if (_bidAmount == 0) revert Unauthorized();\n\n        delete auction.bids[msg.sender];\n        assert(userAuctions[msg.sender].remove(_auctionIndex));\n\n        (bool _sent, ) = payable(msg.sender).call{value: _bidAmount}('');\n        assert(_sent);\n\n        emit BidWithdrawn(_auctionIndex, msg.sender, _bidAmount);\n    }\n\n    /// @notice Allows bidders to withdraw multiple bids. Only works if `msg.sender` isn't the highest bidder.\n    /// @param _indexes The auctions to claim the bids from.\n    function withdrawBids(uint256[] calldata _indexes) external {\n        for (uint256 i; i < _indexes.length; i++) {\n            withdrawBid(_indexes[i]);\n        }\n    }\n\n    /// @return The list of active bids for an account.\n    /// @param _account The address to check.\n    function getActiveBids(\n        address _account\n    ) external view returns (uint256[] memory) {\n        return userAuctions[_account].values();\n    }\n\n    /// @return The active bid of an account for an auction.\n    /// @param _auctionIndex The auction to retrieve the bid from.\n    /// @param _account The bidder's account\n    function getAuctionBid(\n        uint256 _auctionIndex,\n        address _account\n    ) external view returns (uint256) {\n        return auctions[_auctionIndex].bids[_account];\n    }\n\n    /// @notice Allows admins to withdraw ETH after a successful auction.\n    /// @param _auctionIndex The auction to withdraw the ETH from\n    function withdrawETH(uint256 _auctionIndex) external nonReentrant {\n        Auction storage auction = auctions[_auctionIndex];\n        if (auction.creator != msg.sender) revert Unauthorized();\n\n        address _highestBidder = auction.highestBidOwner;\n        if (\n            auction.endTime > block.timestamp ||\n            _highestBidder == address(0) ||\n            auction.ownerClaimed\n        ) revert Unauthorized();\n\n        auction.ownerClaimed = true;\n\n        emit ETHClaimed(_auctionIndex);\n\n        (bool _sent, ) = payable(msg.sender).call{\n            value: auction.bids[_highestBidder]\n        }('');\n        assert(_sent);\n    }\n\n    /// @notice Allows admins to withdraw an unsold NFT\n    /// @param _auctionIndex The auction to withdraw the NFT from.\n    function withdrawUnsoldNFT(uint256 _auctionIndex) external nonReentrant {\n        Auction storage auction = auctions[_auctionIndex];\n        if (auction.creator != msg.sender) revert Unauthorized();\n\n        address _highestBidder = auction.highestBidOwner;\n        if (\n            auction.endTime > block.timestamp ||\n            _highestBidder != address(0) ||\n            auction.ownerClaimed\n        ) revert Unauthorized();\n\n        auction.ownerClaimed = true;\n\n        auction.nftAddress.safeTransferFrom(\n            address(this),\n            msg.sender,\n            auction.nftIndex,\n            auction.amount,\n            '0x'\n        );\n\n        emit AuctionFailed(_auctionIndex);\n    }\n\n    /// @notice Allows admins to set the amount of time to increase an auction by if a bid happens in the last few minutes\n    /// @param _newTime The new amount of time\n    function setBidTimeIncrement(\n        uint256 _newTime\n    ) public onlyRole(DEFAULT_ADMIN_ROLE) {\n        if (_newTime == 0) revert InvalidAmount();\n\n        emit BidTimeIncrementChanged(_newTime, bidTimeIncrement);\n\n        bidTimeIncrement = _newTime;\n    }\n\n    /// @notice Allows admins to set the minimum increment rate from the last highest bid.\n    /// @param _newIncrementRate The new increment rate.\n    function setMinimumIncrementRate(\n        RateLib.Rate memory _newIncrementRate\n    ) public onlyRole(DEFAULT_ADMIN_ROLE) {\n        if (!_newIncrementRate.isValid() || !_newIncrementRate.isBelowOne())\n            revert RateLib.InvalidRate();\n\n        emit MinimumIncrementRateChanged(_newIncrementRate, minIncrementRate);\n\n        minIncrementRate = _newIncrementRate;\n    }\n\n    /// @notice Allows admins to set the default auction duration\n    /// @param _duration The new default duration\n    function setAuctionDuration(\n        uint256 _duration\n    ) public onlyRole(DEFAULT_ADMIN_ROLE) {\n        if (_duration == 0) revert InvalidAmount();\n\n        emit DurationChanged(_duration, auctionDuration);\n\n        auctionDuration = _duration;\n    }\n\n    function _newAuction(\n        address _owner,\n        IERC1155Upgradeable _nft,\n        uint256 _idx,\n        uint256 _amount,\n        uint256 _startTime,\n        uint256 _endTime,\n        uint256 _minBid\n    ) internal returns (uint256) {\n        if (address(_nft) == address(0)) revert ZeroAddress();\n        if (\n            block.timestamp > _startTime ||\n            _startTime >= _endTime ||\n            _minBid == 0\n        ) revert InvalidAmount();\n\n        Auction storage auction = auctions[auctionsLength++];\n        auction.creator = _owner;\n        auction.nftAddress = _nft;\n        auction.nftIndex = _idx;\n        auction.amount = _amount;\n        auction.startTime = _startTime;\n        auction.endTime = _endTime;\n        auction.minBid = _minBid;\n\n        _nft.safeTransferFrom(msg.sender, address(this), _idx, _amount, '0x');\n\n        emit NewAuction(auctionsLength - 1, _nft, _idx, _amount, _startTime);\n\n        return auctionsLength - 1;\n    }\n\n    function _getNextSlotStart() internal view returns (uint256) {\n        uint256 _duration = auctionDuration;\n        return block.timestamp - (block.timestamp % _duration) + _duration;\n    }\n\n    // ERC1155 Receiver hooks\n\n    function onERC1155Received(\n        address operator,\n        address from,\n        uint256 id,\n        uint256 value,\n        bytes calldata data\n    ) external pure override returns (bytes4) {\n        return\n            bytes4(\n                keccak256(\n                    'onERC1155Received(address,address,uint256,uint256,bytes)'\n                )\n            );\n    }\n\n    function onERC1155BatchReceived(\n        address operator,\n        address from,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external pure override returns (bytes4) {\n        return\n            bytes4(\n                keccak256(\n                    'onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)'\n                )\n            );\n    }\n}\n"
      },
      "contracts/oasis/usd/AbstractAssetVault.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol';\n\nimport '../../interfaces/IStableCoin.sol';\nimport '../../utils/RateLib.sol';\nimport {ERC20ValueProvider} from './ERC20ValueProvider.sol';\n\n/// @title ERC20 / ERC1155 lending vault\n/// @notice This contracts allows users to borrow ShezmuUSD using ERC20/ERC1155 tokens as collateral.\n/// The price of the collateral token is fetched using a chainlink oracle\nabstract contract AbstractAssetVault is\n    AccessControlUpgradeable,\n    ReentrancyGuardUpgradeable\n{\n    using SafeERC20Upgradeable for IERC20Upgradeable;\n    using SafeERC20Upgradeable for IStableCoin;\n    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n    using RateLib for RateLib.Rate;\n\n    error InvalidAmount(uint256 amount);\n    error InvalidPosition(address owner);\n    error DebtCapReached();\n    error NoDebt();\n    error InsufficientCollateral();\n    error UnknownAction(uint8 action);\n    error InvalidLength();\n    error MinBorrowAmount();\n\n    event CollateralAdded(address indexed owner, uint256 colAmount);\n    event Borrowed(address indexed owner, uint256 amount);\n    event Repaid(address indexed owner, uint256 amount);\n    event CollateralRemoved(address indexed owner, uint256 colAmount);\n    event Liquidated(\n        address indexed liquidator,\n        address indexed owner,\n        uint256 colAmount\n    );\n\n    event Accrual(uint256 additionalInterest);\n    event FeeCollected(uint256 collectedAmount);\n\n    struct Position {\n        uint256 collateral;\n        uint256 debtPrincipal;\n        uint256 debtPortion;\n    }\n\n    struct VaultSettings {\n        RateLib.Rate debtInterestApr;\n        RateLib.Rate organizationFeeRate;\n        uint256 borrowAmountCap;\n        uint256 minBorrowAmount;\n    }\n\n    bytes32 internal constant DAO_ROLE = keccak256('DAO_ROLE');\n    bytes32 internal constant LIQUIDATOR_ROLE = keccak256('LIQUIDATOR_ROLE');\n    bytes32 internal constant SETTER_ROLE = keccak256('SETTER_ROLE');\n\n    //accrue required\n    uint8 internal constant ACTION_ADD_COLLATERAL = 0;\n    uint8 internal constant ACTION_REMOVE_COLLATERAL = 1;\n    uint8 internal constant ACTION_BORROW = 2;\n    uint8 internal constant ACTION_REPAY = 3;\n    uint8 internal constant ACTION_LIQUIDATE = 4;\n\n    IStableCoin public stablecoin;\n\n    /// @notice Total outstanding debt\n    uint256 public totalDebtAmount;\n    /// @dev Last time debt was accrued. See {accrue} for more info\n    uint256 internal totalDebtAccruedAt;\n    uint256 public totalFeeCollected;\n    uint256 internal totalDebtPortion;\n\n    VaultSettings public settings;\n\n    /// @dev Keeps track of all the users\n    EnumerableSetUpgradeable.AddressSet internal userIndexes;\n\n    mapping(address => Position) public positions;\n\n    /// @notice This function is only called once during deployment of the proxy contract. It's not called after upgrades.\n    /// @param _stablecoin ShezUSD address\n    /// @param _settings Initial settings used by the contract\n    function __initialize(\n        IStableCoin _stablecoin,\n        VaultSettings calldata _settings\n    ) internal onlyInitializing {\n        __AccessControl_init();\n        __ReentrancyGuard_init();\n\n        _setupRole(DAO_ROLE, msg.sender);\n        _setRoleAdmin(LIQUIDATOR_ROLE, DAO_ROLE);\n        _setRoleAdmin(SETTER_ROLE, DAO_ROLE);\n        _setRoleAdmin(DAO_ROLE, DAO_ROLE);\n\n        if (\n            !_settings.debtInterestApr.isValid() ||\n            !_settings.debtInterestApr.isBelowOne()\n        ) revert RateLib.InvalidRate();\n\n        if (\n            !_settings.organizationFeeRate.isValid() ||\n            !_settings.organizationFeeRate.isBelowOne()\n        ) revert RateLib.InvalidRate();\n\n        stablecoin = _stablecoin;\n        settings = _settings;\n    }\n\n    /// @notice Returns the number of open positions\n    /// @return The number of open positions\n    function totalUsersLength() external view returns (uint256) {\n        return userIndexes.length();\n    }\n\n    /// @notice Returns all open position owners\n    /// @return The open position owners\n    function totalUsers() external view returns (address[] memory) {\n        return userIndexes.values();\n    }\n\n    /// @param _owner The position owner\n    /// @return The ShezUSD credit limit of owner\n    function getCreditLimit(address _owner) external view returns (uint256) {\n        return _getCreditLimit(_owner, positions[_owner].collateral);\n    }\n\n    /// @param _owner The position owner\n    /// @return The ShezUSD liquidation limit of owner\n    function getLiquidationLimit(address _owner) public view returns (uint256) {\n        return _getLiquidationLimit(_owner, positions[_owner].collateral);\n    }\n\n    /// @param _owner The position owner\n    /// @return Whether the position is liquidatable or not\n    function isLiquidatable(address _owner) external view returns (bool) {\n        return\n            positions[_owner].debtPrincipal + getDebtInterest(_owner) >=\n            getLiquidationLimit(_owner);\n    }\n\n    /// @param _owner The position owner\n    /// @return The ShezUSD debt interest accumulated\n    function getDebtInterest(address _owner) public view returns (uint256) {\n        Position storage position = positions[_owner];\n        uint256 principal = position.debtPrincipal;\n        uint256 debt = _calculateDebt(\n            totalDebtAmount + calculateAdditionalInterest(),\n            position.debtPortion,\n            totalDebtPortion\n        );\n\n        //_calculateDebt is prone to rounding errors that may cause\n        //the calculated debt amount to be 1 or 2 units less than\n        //the debt principal if no time has elapsed in between the first borrow\n        //and the _calculateDebt call.\n        if (principal > debt) debt = principal;\n\n        unchecked {\n            return debt - principal;\n        }\n    }\n\n    /// @dev Calculates the additional global interest since last time the contract's state was updated by calling {accrue}\n    /// @return The additional interest value\n    function calculateAdditionalInterest() public view returns (uint256) {\n        // Number of seconds since {accrue} was called\n        uint256 elapsedTime = block.timestamp - totalDebtAccruedAt;\n        if (elapsedTime == 0) {\n            return 0;\n        }\n\n        uint256 totalDebt = totalDebtAmount;\n        if (totalDebt == 0) {\n            return 0;\n        }\n\n        // Accrue interest\n        return\n            (elapsedTime * totalDebt * settings.debtInterestApr.numerator) /\n            settings.debtInterestApr.denominator /\n            365.25 days;\n    }\n\n    /// @dev The {accrue} function updates the contract's state by calculating\n    /// the additional interest accrued since the last state update\n    function accrue() public {\n        uint256 additionalInterest = calculateAdditionalInterest();\n\n        totalDebtAccruedAt = block.timestamp;\n\n        totalDebtAmount += additionalInterest;\n        totalFeeCollected += additionalInterest;\n\n        emit Accrual(additionalInterest);\n    }\n\n    /// @notice Allows to execute multiple actions in a single transaction.\n    /// @param _actions The actions to execute.\n    /// @param _data The abi encoded parameters for the actions to execute.\n    function doActions(\n        uint8[] calldata _actions,\n        bytes[] calldata _data\n    ) external nonReentrant {\n        _doActionsFor(msg.sender, _actions, _data);\n    }\n\n    /// @notice Allows a user to add collateral\n    /// @param _colAmount The collateral amount\n    function addCollateral(uint256 _colAmount) external nonReentrant {\n        accrue();\n        _addCollateral(msg.sender, _colAmount);\n    }\n\n    /// @notice Allows users to borrow ShezUSD\n    /// @dev emits a {Borrowed} event\n    /// @param _amount The amount of ShezUSD to be borrowed. Note that the user will receive less than the amount requested,\n    function borrow(uint256 _amount) external nonReentrant {\n        accrue();\n        _borrow(msg.sender, _amount);\n    }\n\n    /// @notice Allows users to repay a portion/all of their debt. Note that since interest increases every second,\n    /// a user wanting to repay all of their debt should repay for an amount greater than their current debt to account for the\n    /// additional interest while the repay transaction is pending, the contract will only take what's necessary to repay all the debt\n    /// @dev Emits a {Repaid} event\n    /// @param _amount The amount of debt to repay. If greater than the position's outstanding debt, only the amount necessary to repay all the debt will be taken\n    function repay(uint256 _amount) external nonReentrant {\n        accrue();\n        _repay(msg.sender, _amount);\n    }\n\n    /// @notice Allows a user to remove collateral\n    /// @dev Emits a {PositionClosed} event\n    /// @param _colAmount The collateral amount\n    function removeCollateral(uint256 _colAmount) external nonReentrant {\n        accrue();\n        _removeCollateral(msg.sender, _colAmount);\n    }\n\n    /// @notice Allows members of the `LIQUIDATOR_ROLE` to liquidate a position. Positions can only be liquidated\n    /// once their debt amount exceeds the minimum liquidation debt to collateral value rate.\n    /// In order to liquidate a position, the liquidator needs to repay the user's outstanding debt.\n    /// @dev Emits a {Liquidated} event\n    /// @param _owner The position owner\n    /// @param _recipient The address to send collaterals to\n    function liquidate(\n        address _owner,\n        address _recipient\n    ) external nonReentrant {\n        accrue();\n        _liquidate(msg.sender, _owner, _recipient);\n    }\n\n    /// @notice Allows the DAO to collect interest and fees before they are repaid\n    function collect() external nonReentrant onlyRole(DAO_ROLE) {\n        accrue();\n\n        uint256 _totalFeeCollected = totalFeeCollected;\n\n        stablecoin.mint(msg.sender, _totalFeeCollected);\n        totalFeeCollected = 0;\n\n        emit FeeCollected(_totalFeeCollected);\n    }\n\n    /// @notice Allows the DAO to withdraw _amount of an ERC20\n    function rescueToken(\n        IERC20Upgradeable _token,\n        uint256 _amount\n    ) external nonReentrant onlyRole(DAO_ROLE) {\n        _token.safeTransfer(msg.sender, _amount);\n    }\n\n    /// @notice Allows the setter contract to change fields in the `VaultSettings` struct.\n    /// @dev Validation and single field setting is handled by an external contract with the\n    /// `SETTER_ROLE`. This was done to reduce the contract's size.\n    function setSettings(\n        VaultSettings calldata _settings\n    ) external onlyRole(SETTER_ROLE) {\n        accrue();\n\n        if (\n            !_settings.debtInterestApr.isValid() ||\n            !_settings.debtInterestApr.isBelowOne()\n        ) revert RateLib.InvalidRate();\n\n        if (\n            !_settings.organizationFeeRate.isValid() ||\n            !_settings.organizationFeeRate.isBelowOne()\n        ) revert RateLib.InvalidRate();\n\n        settings = _settings;\n    }\n\n    /// @dev See {doActions}\n    function _doActionsFor(\n        address _account,\n        uint8[] calldata _actions,\n        bytes[] calldata _data\n    ) internal {\n        if (_actions.length != _data.length) revert InvalidLength();\n        bool accrueCalled;\n        for (uint256 i; i < _actions.length; ++i) {\n            uint8 action = _actions[i];\n            if (!accrueCalled && action < 100) {\n                accrue();\n                accrueCalled = true;\n            }\n\n            if (action == ACTION_ADD_COLLATERAL) {\n                uint256 colAmount = abi.decode(_data[i], (uint256));\n                _addCollateral(_account, colAmount);\n            } else if (action == ACTION_BORROW) {\n                uint256 amount = abi.decode(_data[i], (uint256));\n                _borrow(_account, amount);\n            } else if (action == ACTION_REPAY) {\n                uint256 amount = abi.decode(_data[i], (uint256));\n                _repay(_account, amount);\n            } else if (action == ACTION_REMOVE_COLLATERAL) {\n                uint256 colAmount = abi.decode(_data[i], (uint256));\n                _removeCollateral(_account, colAmount);\n            } else if (action == ACTION_LIQUIDATE) {\n                (address owner, address recipient) = abi.decode(\n                    _data[i],\n                    (address, address)\n                );\n                _liquidate(_account, owner, recipient);\n            } else {\n                revert UnknownAction(action);\n            }\n        }\n    }\n\n    /// @dev See {addCollateral}\n    function _addCollateral(\n        address _account,\n        uint256 _colAmount\n    ) internal virtual {}\n\n    /// @dev See {borrow}\n    function _borrow(address _account, uint256 _amount) internal {\n        if (_amount < settings.minBorrowAmount) {\n            revert MinBorrowAmount();\n        }\n\n        uint256 _totalDebtAmount = totalDebtAmount;\n        if (_totalDebtAmount + _amount > settings.borrowAmountCap)\n            revert DebtCapReached();\n\n        Position storage position = positions[_account];\n        uint256 _creditLimit = _getCreditLimit(_account, position.collateral);\n        uint256 _debtAmount = _getDebtAmount(_account);\n        if (_debtAmount + _amount > _creditLimit) revert InvalidAmount(_amount);\n\n        //calculate the borrow fee\n        uint256 _organizationFee = (_amount *\n            settings.organizationFeeRate.numerator) /\n            settings.organizationFeeRate.denominator;\n\n        uint256 _feeAmount = _organizationFee;\n        totalFeeCollected += _feeAmount;\n\n        // update debt portion\n        {\n            uint256 _totalDebtPortion = totalDebtPortion;\n            uint256 _plusPortion = _calculatePortion(\n                _totalDebtPortion,\n                _amount,\n                _totalDebtAmount\n            );\n\n            totalDebtPortion = _totalDebtPortion + _plusPortion;\n            position.debtPortion += _plusPortion;\n            position.debtPrincipal += _amount;\n            totalDebtAmount = _totalDebtAmount + _amount;\n        }\n\n        //subtract the fee from the amount borrowed\n        stablecoin.mint(_account, _amount - _feeAmount);\n\n        emit Borrowed(_account, _amount);\n    }\n\n    /// @dev See {repay}\n    function _repay(address _account, uint256 _amount) internal {\n        if (_amount == 0) revert InvalidAmount(_amount);\n\n        Position storage position = positions[_account];\n\n        uint256 _debtAmount = _getDebtAmount(_account);\n        if (_debtAmount == 0) revert NoDebt();\n\n        uint256 _debtPrincipal = position.debtPrincipal;\n        uint256 _debtInterest = _debtAmount - _debtPrincipal;\n\n        _amount = _amount > _debtAmount ? _debtAmount : _amount;\n\n        // burn all payment, the interest is sent to the DAO using the {collect} function\n        stablecoin.burnFrom(_account, _amount);\n\n        uint256 _paidPrincipal;\n\n        unchecked {\n            _paidPrincipal = _amount > _debtInterest\n                ? _amount - _debtInterest\n                : 0;\n        }\n\n        uint256 _totalDebtPortion = totalDebtPortion;\n        uint256 _totalDebtAmount = totalDebtAmount;\n        uint256 _debtPortion = position.debtPortion;\n        uint256 _minusPortion = _paidPrincipal == _debtPrincipal\n            ? _debtPortion\n            : _calculatePortion(_totalDebtPortion, _amount, _totalDebtAmount);\n\n        totalDebtPortion = _totalDebtPortion - _minusPortion;\n        position.debtPortion = _debtPortion - _minusPortion;\n        position.debtPrincipal = _debtPrincipal - _paidPrincipal;\n        totalDebtAmount = _totalDebtAmount - _amount;\n\n        if (\n            position.debtPrincipal > 0 &&\n            position.debtPrincipal < settings.minBorrowAmount\n        ) {\n            revert MinBorrowAmount();\n        }\n\n        emit Repaid(_account, _amount);\n    }\n\n    /// @dev See {removeCollateral}\n    function _removeCollateral(\n        address _account,\n        uint256 _colAmount\n    ) internal virtual {}\n\n    /// @dev See {liquidate}\n    function _liquidate(\n        address _account,\n        address _owner,\n        address _recipient\n    ) internal virtual {}\n\n    /// @dev Returns the credit limit\n    /// @param _owner The position owner\n    /// @param _colAmount The collateral amount\n    /// @return The credit limit\n    function _getCreditLimit(\n        address _owner,\n        uint256 _colAmount\n    ) internal view virtual returns (uint256) {}\n\n    /// @dev Returns the minimum amount of debt necessary to liquidate the position\n    /// @param _owner The position owner\n    /// @param _colAmount The collateral amount\n    /// @return The minimum amount of debt to liquidate the position\n    function _getLiquidationLimit(\n        address _owner,\n        uint256 _colAmount\n    ) internal view virtual returns (uint256) {}\n\n    /// @dev Calculates current outstanding debt of a user\n    /// @param _owner The position owner\n    /// @return The outstanding debt value\n    function _getDebtAmount(address _owner) internal view returns (uint256) {\n        uint256 calculatedDebt = _calculateDebt(\n            totalDebtAmount,\n            positions[_owner].debtPortion,\n            totalDebtPortion\n        );\n\n        uint256 principal = positions[_owner].debtPrincipal;\n\n        //_calculateDebt is prone to rounding errors that may cause\n        //the calculated debt amount to be 1 or 2 units less than\n        //the debt principal when the accrue() function isn't called\n        //in between the first borrow and the _calculateDebt call.\n        return principal > calculatedDebt ? principal : calculatedDebt;\n    }\n\n    /// @dev Calculates the total debt of a position given the global debt, the user's portion of the debt and the total user portions\n    /// @param total The global outstanding debt\n    /// @param userPortion The user's portion of debt\n    /// @param totalPortion The total user portions of debt\n    /// @return The outstanding debt of the position\n    function _calculateDebt(\n        uint256 total,\n        uint256 userPortion,\n        uint256 totalPortion\n    ) internal pure returns (uint256) {\n        return totalPortion == 0 ? 0 : (total * userPortion) / totalPortion;\n    }\n\n    /// @dev Calculates the debt portion of a position given the global debt portion, the debt amount and the global debt amount\n    /// @param _total The total user portions of debt\n    /// @param _userDebt The user's debt\n    /// @param _totalDebt The global outstanding debt\n    /// @return _userDebt converted into a debt portion\n    function _calculatePortion(\n        uint256 _total,\n        uint256 _userDebt,\n        uint256 _totalDebt\n    ) internal pure returns (uint256) {\n        return _total == 0 ? _userDebt : (_total * _userDebt) / _totalDebt;\n    }\n}\n"
      },
      "contracts/oasis/usd/ERC1155ValueProvider.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol';\n\nimport '../../utils/AccessControlUpgradeable.sol';\nimport '../../utils/RateLib.sol';\nimport '../../interfaces/IChainlinkV3Aggregator.sol';\n\nabstract contract ERC1155ValueProvider is\n    ReentrancyGuardUpgradeable,\n    AccessControlUpgradeable\n{\n    using RateLib for RateLib.Rate;\n    using SafeERC20Upgradeable for IERC20Upgradeable;\n\n    error InvalidAmount(uint256 amount);\n    error ZeroAddress();\n    error InvalidOracleResults();\n\n    event DaoFloorChanged(uint256 newFloor);\n    event NewBaseCreditLimitRate(RateLib.Rate rate);\n    event NewBaseLiquidationLimitRate(RateLib.Rate rate);\n\n    /// @notice The NFT floor oracles aggregator\n    IChainlinkV3Aggregator public aggregator;\n    /// @notice If true, the floor price won't be fetched using the Chainlink oracle but\n    /// a value set by the DAO will be used instead\n    bool public daoFloorOverride;\n    /// @notice Value of floor set by the DAO. Only used if `daoFloorOverride` is true\n    uint256 public overriddenFloorValueUSD;\n\n    RateLib.Rate public baseCreditLimitRate;\n    RateLib.Rate public baseLiquidationLimitRate;\n\n    /// @notice This function is only called once during deployment of the proxy contract. It's not called after upgrades.\n    /// @param _aggregator The NFT floor oracles aggregator\n    /// @param _baseCreditLimitRate The base credit limit rate\n    /// @param _baseLiquidationLimitRate The base liquidation limit rate\n    function __initialize(\n        IChainlinkV3Aggregator _aggregator,\n        RateLib.Rate calldata _baseCreditLimitRate,\n        RateLib.Rate calldata _baseLiquidationLimitRate\n    ) internal onlyInitializing {\n        __AccessControl_init();\n        __ReentrancyGuard_init();\n\n        _validateRateBelowOne(_baseCreditLimitRate);\n        _validateRateBelowOne(_baseLiquidationLimitRate);\n\n        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);\n\n        aggregator = _aggregator;\n        baseCreditLimitRate = _baseCreditLimitRate;\n        baseLiquidationLimitRate = _baseLiquidationLimitRate;\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The credit limit rate\n    function getCreditLimitRate(\n        address _owner,\n        uint256 _colAmount\n    ) public view returns (RateLib.Rate memory) {\n        return baseCreditLimitRate;\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The liquidation limit rate\n    function getLiquidationLimitRate(\n        address _owner,\n        uint256 _colAmount\n    ) public view returns (RateLib.Rate memory) {\n        return baseLiquidationLimitRate;\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The credit limit for collateral amount\n    function getCreditLimitUSD(\n        address _owner,\n        uint256 _colAmount\n    ) external view returns (uint256) {\n        RateLib.Rate memory _creditLimitRate = getCreditLimitRate(\n            _owner,\n            _colAmount\n        );\n        return _creditLimitRate.calculate(getNFTValueUSD(_colAmount));\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The liquidation limit for collateral amount\n    function getLiquidationLimitUSD(\n        address _owner,\n        uint256 _colAmount\n    ) external view returns (uint256) {\n        RateLib.Rate memory _liquidationLimitRate = getLiquidationLimitRate(\n            _owner,\n            _colAmount\n        );\n        return _liquidationLimitRate.calculate(getNFTValueUSD(_colAmount));\n    }\n\n    /// @return The floor value for the collection, in USD.\n    function getFloorUSD() public view virtual returns (uint256) {\n        if (daoFloorOverride) {\n            return overriddenFloorValueUSD;\n        }\n\n        (, int256 answer, , uint256 timestamp, ) = aggregator.latestRoundData();\n\n        if (answer == 0 || timestamp == 0) revert InvalidOracleResults();\n\n        uint8 decimals = aggregator.decimals();\n\n        unchecked {\n            //converts the answer to have 18 decimals\n            return\n                decimals > 18\n                    ? uint256(answer) / 10 ** (decimals - 18)\n                    : uint256(answer) * 10 ** (18 - decimals);\n        }\n    }\n\n    /// @param _colAmount The collateral amount\n    /// @return The value in USD of the NFT at index `_nftIndex`, with 18 decimals.\n    function getNFTValueUSD(uint256 _colAmount) public view returns (uint256) {\n        uint256 _floor = getFloorUSD();\n        return _floor * _colAmount;\n    }\n\n    /// @notice Allows the DAO to bypass the floor oracle and override the NFT floor value\n    /// @param _newFloor The new floor\n    function overrideFloor(\n        uint256 _newFloor\n    ) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        if (_newFloor == 0) revert InvalidAmount(_newFloor);\n        overriddenFloorValueUSD = _newFloor;\n        daoFloorOverride = true;\n\n        emit DaoFloorChanged(_newFloor);\n    }\n\n    /// @notice Allows the DAO to stop overriding floor\n    function disableFloorOverride() external onlyRole(DEFAULT_ADMIN_ROLE) {\n        daoFloorOverride = false;\n    }\n\n    function setBaseCreditLimitRate(\n        RateLib.Rate memory _baseCreditLimitRate\n    ) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        _validateRateBelowOne(_baseCreditLimitRate);\n\n        baseCreditLimitRate = _baseCreditLimitRate;\n\n        emit NewBaseCreditLimitRate(_baseCreditLimitRate);\n    }\n\n    function setBaseLiquidationLimitRate(\n        RateLib.Rate memory _liquidationLimitRate\n    ) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        _validateRateBelowOne(_liquidationLimitRate);\n\n        baseLiquidationLimitRate = _liquidationLimitRate;\n\n        emit NewBaseLiquidationLimitRate(_liquidationLimitRate);\n    }\n\n    /// @dev Validates a rate. The denominator must be greater than zero and greater than or equal to the numerator.\n    /// @param _rate The rate to validate\n    function _validateRateBelowOne(RateLib.Rate memory _rate) internal pure {\n        if (!_rate.isValid() || _rate.isAboveOne())\n            revert RateLib.InvalidRate();\n    }\n}\n"
      },
      "contracts/oasis/usd/ERC1155Vault.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol';\n\nimport '../../interfaces/IStableCoin.sol';\nimport '../../utils/RateLib.sol';\nimport {ERC1155ValueProvider} from './ERC1155ValueProvider.sol';\nimport {AbstractAssetVault} from './AbstractAssetVault.sol';\n\n/// @title ERC1155 lending vault\n/// @notice This contracts allows users to borrow ShezmuUSD using ERC1155 as collateral.\n/// The floor price of the NFT collection is fetched using a chainlink oracle, while some other more valuable traits\n/// can have an higher price set by the DAO. Users can also increase the price (and thus the borrow limit) of their\n/// NFT by submitting a governance proposal. If the proposal is approved the user can lock a percentage of the new price\n/// worth of Shezmu to make it effective\ncontract ERC1155Vault is AbstractAssetVault, IERC1155ReceiverUpgradeable {\n    using SafeERC20Upgradeable for IERC20Upgradeable;\n    using SafeERC20Upgradeable for IStableCoin;\n    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n    using RateLib for RateLib.Rate;\n    /// @notice The Shezmu trait boost locker contract\n    ERC1155ValueProvider public valueProvider;\n\n    IERC1155Upgradeable public tokenContract;\n    uint256 public tokenIndex;\n\n    /// @notice This function is only called once during deployment of the proxy contract. It's not called after upgrades.\n    /// @param _stablecoin ShezUSD address\n    /// @param _tokenContract The collateral token address\n    /// @param _valueProvider The collateral token value provider\n    /// @param _settings Initial settings used by the contract\n    function initialize(\n        IStableCoin _stablecoin,\n        IERC1155Upgradeable _tokenContract,\n        uint256 _tokenIndex,\n        ERC1155ValueProvider _valueProvider,\n        VaultSettings calldata _settings\n    ) external initializer {\n        __initialize(_stablecoin, _settings);\n        tokenContract = _tokenContract;\n        tokenIndex = _tokenIndex;\n        valueProvider = _valueProvider;\n    }\n\n    function setValueProvider(\n        ERC1155ValueProvider _valueProvider\n    ) external onlyRole(SETTER_ROLE) {\n        valueProvider = _valueProvider;\n    }\n\n    /// @dev See {addCollateral}\n    function _addCollateral(\n        address _account,\n        uint256 _colAmount\n    ) internal override {\n        if (_colAmount == 0) revert InvalidAmount(_colAmount);\n\n        tokenContract.safeTransferFrom(\n            _account,\n            address(this),\n            tokenIndex,\n            _colAmount,\n            '0x'\n        );\n\n        Position storage position = positions[_account];\n\n        if (!userIndexes.contains(_account)) {\n            userIndexes.add(_account);\n        }\n        position.collateral += _colAmount;\n\n        emit CollateralAdded(_account, _colAmount);\n    }\n\n    /// @dev See {removeCollateral}\n    function _removeCollateral(\n        address _account,\n        uint256 _colAmount\n    ) internal override {\n        Position storage position = positions[_account];\n\n        uint256 _debtAmount = _getDebtAmount(_account);\n        uint256 _creditLimit = _getCreditLimit(\n            _account,\n            position.collateral - _colAmount\n        );\n\n        if (_debtAmount > _creditLimit) revert InsufficientCollateral();\n\n        position.collateral -= _colAmount;\n\n        if (position.collateral == 0) {\n            delete positions[_account];\n            userIndexes.remove(_account);\n        }\n\n        tokenContract.safeTransferFrom(\n            address(this),\n            _account,\n            tokenIndex,\n            _colAmount,\n            '0x'\n        );\n\n        emit CollateralRemoved(_account, _colAmount);\n    }\n\n    /// @dev See {liquidate}\n    function _liquidate(\n        address _account,\n        address _owner,\n        address _recipient\n    ) internal override {\n        _checkRole(LIQUIDATOR_ROLE, _account);\n\n        Position storage position = positions[_owner];\n        uint256 colAmount = position.collateral;\n\n        uint256 debtAmount = _getDebtAmount(_owner);\n        if (debtAmount < _getLiquidationLimit(_owner, position.collateral))\n            revert InvalidPosition(_owner);\n\n        // burn all payment\n        stablecoin.burnFrom(_account, debtAmount);\n\n        // update debt portion\n        totalDebtPortion -= position.debtPortion;\n        totalDebtAmount -= debtAmount;\n        position.debtPortion = 0;\n\n        // transfer collateral to liquidator\n        delete positions[_owner];\n        userIndexes.remove(_owner);\n        tokenContract.safeTransferFrom(\n            address(this),\n            _recipient,\n            tokenIndex,\n            colAmount,\n            '0x'\n        );\n\n        emit Liquidated(_account, _owner, colAmount);\n    }\n\n    /// @dev Returns the credit limit\n    /// @param _owner The position owner\n    /// @param _colAmount The collateral amount\n    /// @return The credit limit\n    function _getCreditLimit(\n        address _owner,\n        uint256 _colAmount\n    ) internal view override returns (uint256) {\n        uint256 creditLimitUSD = valueProvider.getCreditLimitUSD(\n            _owner,\n            _colAmount\n        );\n        return creditLimitUSD;\n    }\n\n    /// @dev Returns the minimum amount of debt necessary to liquidate the position\n    /// @param _owner The position owner\n    /// @param _colAmount The collateral amount\n    /// @return The minimum amount of debt to liquidate the position\n    function _getLiquidationLimit(\n        address _owner,\n        uint256 _colAmount\n    ) internal view override returns (uint256) {\n        uint256 liquidationLimitUSD = valueProvider.getLiquidationLimitUSD(\n            _owner,\n            _colAmount\n        );\n        return liquidationLimitUSD;\n    }\n\n    // ERC1155 Receiver hooks\n\n    function onERC1155Received(\n        address operator,\n        address from,\n        uint256 id,\n        uint256 value,\n        bytes calldata data\n    ) external pure override returns (bytes4) {\n        return\n            bytes4(\n                keccak256(\n                    'onERC1155Received(address,address,uint256,uint256,bytes)'\n                )\n            );\n    }\n\n    function onERC1155BatchReceived(\n        address operator,\n        address from,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external pure override returns (bytes4) {\n        return\n            bytes4(\n                keccak256(\n                    'onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)'\n                )\n            );\n    }\n}\n"
      },
      "contracts/oasis/usd/ERC20ValueProvider.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';\nimport '@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol';\n\nimport '../../utils/AccessControlUpgradeable.sol';\nimport '../../utils/RateLib.sol';\nimport '../../interfaces/IChainlinkV3Aggregator.sol';\n\nabstract contract ERC20ValueProvider is\n    ReentrancyGuardUpgradeable,\n    AccessControlUpgradeable\n{\n    using RateLib for RateLib.Rate;\n\n    error InvalidAmount(uint256 amount);\n    error ZeroAddress();\n    error InvalidOracleResults();\n\n    event NewBaseCreditLimitRate(RateLib.Rate rate);\n    event NewBaseLiquidationLimitRate(RateLib.Rate rate);\n\n    /// @notice The token oracles aggregator\n    IChainlinkV3Aggregator public aggregator;\n\n    /// @notice The token address\n    IERC20MetadataUpgradeable public token;\n\n    RateLib.Rate public baseCreditLimitRate;\n    RateLib.Rate public baseLiquidationLimitRate;\n\n    /// @notice This function is only called once during deployment of the proxy contract. It's not called after upgrades.\n    /// @param _aggregator The token oracles aggregator\n    /// @param _token The token address\n    /// @param _baseCreditLimitRate The base credit limit rate\n    /// @param _baseLiquidationLimitRate The base liquidation limit rate\n    function __initialize(\n        IChainlinkV3Aggregator _aggregator,\n        IERC20MetadataUpgradeable _token,\n        RateLib.Rate calldata _baseCreditLimitRate,\n        RateLib.Rate calldata _baseLiquidationLimitRate\n    ) internal onlyInitializing {\n        __AccessControl_init();\n        __ReentrancyGuard_init();\n\n        if (address(_aggregator) == address(0)) revert ZeroAddress();\n\n        _validateRateBelowOne(_baseCreditLimitRate);\n        _validateRateBelowOne(_baseLiquidationLimitRate);\n\n        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);\n\n        aggregator = _aggregator;\n        token = _token;\n        baseCreditLimitRate = _baseCreditLimitRate;\n        baseLiquidationLimitRate = _baseLiquidationLimitRate;\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The credit limit rate\n    function getCreditLimitRate(\n        address _owner,\n        uint256 _colAmount\n    ) public view returns (RateLib.Rate memory) {\n        return baseCreditLimitRate;\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The liquidation limit rate\n    function getLiquidationLimitRate(\n        address _owner,\n        uint256 _colAmount\n    ) public view returns (RateLib.Rate memory) {\n        return baseLiquidationLimitRate;\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The credit limit for collateral amount\n    function getCreditLimitUSD(\n        address _owner,\n        uint256 _colAmount\n    ) external view returns (uint256) {\n        RateLib.Rate memory _creditLimitRate = getCreditLimitRate(\n            _owner,\n            _colAmount\n        );\n        return _creditLimitRate.calculate(getPriceUSD(_colAmount));\n    }\n\n    /// @param _owner The owner address\n    /// @param _colAmount The collateral amount\n    /// @return The liquidation limit for collateral amount\n    function getLiquidationLimitUSD(\n        address _owner,\n        uint256 _colAmount\n    ) external view returns (uint256) {\n        RateLib.Rate memory _liquidationLimitRate = getLiquidationLimitRate(\n            _owner,\n            _colAmount\n        );\n        return _liquidationLimitRate.calculate(getPriceUSD(_colAmount));\n    }\n\n    /// @return The value for the collection, in USD.\n    function getPriceUSD(uint256 colAmount) public view returns (uint256) {\n        uint256 price = getPriceUSD();\n        return (price * colAmount) / (10 ** token.decimals());\n    }\n\n    /// @return The value for the collection, in USD.\n    function getPriceUSD() public view virtual returns (uint256) {\n        (, int256 answer, , uint256 timestamp, ) = aggregator.latestRoundData();\n\n        if (answer == 0 || timestamp == 0) revert InvalidOracleResults();\n\n        uint8 decimals = aggregator.decimals();\n\n        unchecked {\n            //converts the answer to have 18 decimals\n            return\n                decimals > 18\n                    ? uint256(answer) / 10 ** (decimals - 18)\n                    : uint256(answer) * 10 ** (18 - decimals);\n        }\n    }\n\n    function setBaseCreditLimitRate(\n        RateLib.Rate memory _baseCreditLimitRate\n    ) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        _validateRateBelowOne(_baseCreditLimitRate);\n\n        baseCreditLimitRate = _baseCreditLimitRate;\n\n        emit NewBaseCreditLimitRate(_baseCreditLimitRate);\n    }\n\n    function setBaseLiquidationLimitRate(\n        RateLib.Rate memory _liquidationLimitRate\n    ) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        _validateRateBelowOne(_liquidationLimitRate);\n\n        baseLiquidationLimitRate = _liquidationLimitRate;\n\n        emit NewBaseLiquidationLimitRate(_liquidationLimitRate);\n    }\n\n    /// @dev Validates a rate. The denominator must be greater than zero and greater than or equal to the numerator.\n    /// @param _rate The rate to validate\n    function _validateRateBelowOne(RateLib.Rate memory _rate) internal pure {\n        if (!_rate.isValid() || _rate.isAboveOne())\n            revert RateLib.InvalidRate();\n    }\n}\n"
      },
      "contracts/utils/AccessControlUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\n\n//copy paste of openzeppelin's {AccessControlUpgradeable} contract but instead of extending\n//{ERC165Upgradeable} it extends {ERC165} to have the storage layout match {OwnableUpgradeable}'s\n//and allow replacing it.\nabstract contract AccessControlUpgradeable is\n    Initializable,\n    ContextUpgradeable,\n    IAccessControlUpgradeable,\n    ERC165\n{\n    function __AccessControl_init() internal onlyInitializing {}\n\n    function __AccessControl_init_unchained() internal onlyInitializing {}\n\n    struct RoleData {\n        mapping(address => bool) members;\n        bytes32 adminRole;\n    }\n\n    mapping(bytes32 => RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with a standardized message including the required role.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     *\n     * _Available since v4.1._\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role, _msgSender());\n        _;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(\n        bytes4 interfaceId\n    ) public view virtual override returns (bool) {\n        return\n            interfaceId == type(IAccessControlUpgradeable).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(\n        bytes32 role,\n        address account\n    ) public view virtual override returns (bool) {\n        return _roles[role].members[account];\n    }\n\n    /**\n     * @dev Revert with a standard message if `account` is missing `role`.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert(\n                string(\n                    abi.encodePacked(\n                        \"AccessControl: account \",\n                        StringsUpgradeable.toHexString(uint160(account), 20),\n                        \" is missing role \",\n                        StringsUpgradeable.toHexString(uint256(role), 32)\n                    )\n                )\n            );\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(\n        bytes32 role\n    ) public view virtual override returns (bytes32) {\n        return _roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(\n        bytes32 role,\n        address account\n    ) public virtual override onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(\n        bytes32 role,\n        address account\n    ) public virtual override onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(\n        bytes32 role,\n        address account\n    ) public virtual override {\n        require(\n            account == _msgSender(),\n            \"AccessControl: can only renounce roles for self\"\n        );\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event. Note that unlike {grantRole}, this function doesn't perform any\n     * checks on the calling account.\n     *\n     * [WARNING]\n     * ====\n     * This function should only be called from the constructor when setting\n     * up the initial roles for the system.\n     *\n     * Using this function in any other way is effectively circumventing the admin\n     * system imposed by {AccessControl}.\n     * ====\n     *\n     * NOTE: This function is deprecated in favor of {_grantRole}.\n     */\n    function _setupRole(bytes32 role, address account) internal virtual {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        _roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * Internal function without access restriction.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual {\n        if (!hasRole(role, account)) {\n            _roles[role].members[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n        }\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * Internal function without access restriction.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual {\n        if (hasRole(role, account)) {\n            _roles[role].members[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n        }\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "contracts/utils/RateLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.17;\n\nlibrary RateLib {\n    error InvalidRate();\n\n    struct Rate {\n        uint128 numerator;\n        uint128 denominator;\n    }\n\n    function isValid(Rate memory _rate) internal pure returns (bool) {\n        return _rate.denominator != 0;\n    }\n\n    function isZero(Rate memory _rate) internal pure returns (bool) {\n        return _rate.numerator == 0;\n    }\n\n    function isAboveOne(Rate memory _rate) internal pure returns (bool) {\n        return _rate.numerator > _rate.denominator;\n    }\n\n    function isBelowOne(Rate memory _rate) internal pure returns (bool) {\n        return _rate.denominator > _rate.numerator;\n    }\n\n    function isOne(Rate memory _rate) internal pure returns (bool) {\n        return _rate.numerator == _rate.denominator;\n    }\n\n    function greaterThan(\n        Rate memory _r1,\n        Rate memory _r2\n    ) internal pure returns (bool) {\n        return\n            _r1.numerator * _r2.denominator > _r2.numerator * _r1.denominator;\n    }\n\n    function sum(\n        Rate memory _r1,\n        Rate memory _r2\n    ) internal pure returns (Rate memory) {\n        return\n            Rate({\n                numerator: _r1.numerator *\n                    _r2.denominator +\n                    _r1.denominator *\n                    _r2.numerator,\n                denominator: _r1.denominator * _r2.denominator\n            });\n    }\n\n    function calculate(\n        Rate memory _rate,\n        uint256 _num\n    ) internal pure returns (uint256) {\n        return (_num * _rate.numerator) / _rate.denominator;\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "metadata": {
        "useLiteralContent": true
      },
      "libraries": {}
    }
  }}