creation_sourcecode: {{
    "sources": {
      "lib/openzeppelin-contracts/contracts/access/IAccessControl.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 IAccessControl {\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"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n *\n * _Available since v4.8.3._\n */\ninterface IERC1967 {\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n    /**\n     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n     * address.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy.\n     */\n    function proxiableUUID() external view returns (bytes32);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Proxy.sol\";\nimport \"./ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\n    /**\n     * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\n     *\n     * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\n     * function call, and allows initializing the storage of the proxy like a Solidity constructor.\n     */\n    constructor(address _logic, bytes memory _data) payable {\n        _upgradeToAndCall(_logic, _data, false);\n    }\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function _implementation() internal view virtual override returns (address impl) {\n        return ERC1967Upgrade._getImplementation();\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/IERC1967.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n */\nabstract contract ERC1967Upgrade is IERC1967 {\n    // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n     * validated in the constructor.\n     */\n    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function _getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Perform implementation upgrade\n     *\n     * Emits an {Upgraded} event.\n     */\n    function _upgradeTo(address newImplementation) internal {\n        _setImplementation(newImplementation);\n        emit Upgraded(newImplementation);\n    }\n\n    /**\n     * @dev Perform implementation upgrade with additional setup call.\n     *\n     * Emits an {Upgraded} event.\n     */\n    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {\n        _upgradeTo(newImplementation);\n        if (data.length > 0 || forceCall) {\n            Address.functionDelegateCall(newImplementation, data);\n        }\n    }\n\n    /**\n     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n     *\n     * Emits an {Upgraded} event.\n     */\n    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {\n        // Upgrades from old implementations will perform a rollback test. This test requires the new\n        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n        // this special case will break upgrade paths from old UUPS implementation to new ones.\n        if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n            _setImplementation(newImplementation);\n        } else {\n            try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n                require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n            } catch {\n                revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n            }\n            _upgradeToAndCall(newImplementation, data, forceCall);\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n     * validated in the constructor.\n     */\n    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Returns the current admin.\n     */\n    function _getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {AdminChanged} event.\n     */\n    function _changeAdmin(address newAdmin) internal {\n        emit AdminChanged(_getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n     */\n    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function _getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the EIP1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n        require(\n            Address.isContract(IBeacon(newBeacon).implementation()),\n            \"ERC1967: beacon implementation is not a contract\"\n        );\n        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n    }\n\n    /**\n     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n     *\n     * Emits a {BeaconUpgraded} event.\n     */\n    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {\n        _setBeacon(newBeacon);\n        emit BeaconUpgraded(newBeacon);\n        if (data.length > 0 || forceCall) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n    /**\n     * @dev Delegates the current call to `implementation`.\n     *\n     * This function does not return to its internal call site, it will return directly to the external caller.\n     */\n    function _delegate(address implementation) internal virtual {\n        assembly {\n            // Copy msg.data. We take full control of memory in this inline assembly\n            // block because it will not return to Solidity code. We overwrite the\n            // Solidity scratch pad at memory position 0.\n            calldatacopy(0, 0, calldatasize())\n\n            // Call the implementation.\n            // out and outsize are 0 because we don't know the size yet.\n            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n            // Copy the returned data.\n            returndatacopy(0, 0, returndatasize())\n\n            switch result\n            // delegatecall returns 0 on error.\n            case 0 {\n                revert(0, returndatasize())\n            }\n            default {\n                return(0, returndatasize())\n            }\n        }\n    }\n\n    /**\n     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n     * and {_fallback} should delegate.\n     */\n    function _implementation() internal view virtual returns (address);\n\n    /**\n     * @dev Delegates the current call to the address returned by `_implementation()`.\n     *\n     * This function does not return to its internal call site, it will return directly to the external caller.\n     */\n    function _fallback() internal virtual {\n        _beforeFallback();\n        _delegate(_implementation());\n    }\n\n    /**\n     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n     * function in the contract matches the call data.\n     */\n    fallback() external payable virtual {\n        _fallback();\n    }\n\n    /**\n     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n     * is empty.\n     */\n    receive() external payable virtual {\n        _fallback();\n    }\n\n    /**\n     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n     * call, or as part of the Solidity `fallback` or `receive` functions.\n     *\n     * If overridden should call `super._beforeFallback()`.\n     */\n    function _beforeFallback() internal virtual {}\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {BeaconProxy} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/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/Address.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) || (!Address.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"
      },
      "lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n *\n * _Available since v4.1._\n */\nabstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment\n    address private immutable __self = address(this);\n\n    /**\n     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case\n     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n     * fail.\n     */\n    modifier onlyProxy() {\n        require(address(this) != __self, \"Function must be called through delegatecall\");\n        require(_getImplementation() == __self, \"Function must be called through active proxy\");\n        _;\n    }\n\n    /**\n     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n     * callable on the implementing contract but not through proxies.\n     */\n    modifier notDelegated() {\n        require(address(this) == __self, \"UUPSUpgradeable: must not be called through delegatecall\");\n        _;\n    }\n\n    /**\n     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the\n     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n     */\n    function proxiableUUID() external view virtual override notDelegated returns (bytes32) {\n        return _IMPLEMENTATION_SLOT;\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy to `newImplementation`.\n     *\n     * Calls {_authorizeUpgrade}.\n     *\n     * Emits an {Upgraded} event.\n     *\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function upgradeTo(address newImplementation) public virtual onlyProxy {\n        _authorizeUpgrade(newImplementation);\n        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n     * encoded in `data`.\n     *\n     * Calls {_authorizeUpgrade}.\n     *\n     * Emits an {Upgraded} event.\n     *\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n        _authorizeUpgrade(newImplementation);\n        _upgradeToAndCallUUPS(newImplementation, data, true);\n    }\n\n    /**\n     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n     * {upgradeTo} and {upgradeToAndCall}.\n     *\n     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n     *\n     * ```solidity\n     * function _authorizeUpgrade(address) internal override onlyOwner {}\n     * ```\n     */\n    function _authorizeUpgrade(address newImplementation) internal virtual;\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.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 IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the 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"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.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 *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.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(IERC20 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(IERC20 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(IERC20 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(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 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        IERC20Permit 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(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"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(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Address.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 Address {\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"
      },
      "lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._\n * _Available since v4.9 for `string`, `bytes`._\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     *\n     * _Available since v3.0._\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
      },
      "lib/solady/src/utils/FixedPointMathLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\nlibrary FixedPointMathLib {\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                       CUSTOM ERRORS                        */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The operation failed, as the output exceeds the maximum value of uint256.\n    error ExpOverflow();\n\n    /// @dev The operation failed, as the output exceeds the maximum value of uint256.\n    error FactorialOverflow();\n\n    /// @dev The operation failed, due to an overflow.\n    error RPowOverflow();\n\n    /// @dev The operation failed, due to an multiplication overflow.\n    error MulWadFailed();\n\n    /// @dev The operation failed, either due to a\n    /// multiplication overflow, or a division by a zero.\n    error DivWadFailed();\n\n    /// @dev The multiply-divide operation failed, either due to a\n    /// multiplication overflow, or a division by a zero.\n    error MulDivFailed();\n\n    /// @dev The division failed, as the denominator is zero.\n    error DivFailed();\n\n    /// @dev The full precision multiply-divide operation failed, either due\n    /// to the result being larger than 256 bits, or a division by a zero.\n    error FullMulDivFailed();\n\n    /// @dev The output is undefined, as the input is less-than-or-equal to zero.\n    error LnWadUndefined();\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                         CONSTANTS                          */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The scalar of ETH and most ERC20s.\n    uint256 internal constant WAD = 1e18;\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*              SIMPLIFIED FIXED POINT OPERATIONS             */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Equivalent to `(x * y) / WAD` rounded down.\n    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.\n            if mul(y, gt(x, div(not(0), y))) {\n                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.\n                revert(0x1c, 0x04)\n            }\n            z := div(mul(x, y), WAD)\n        }\n    }\n\n    /// @dev Equivalent to `(x * y) / WAD` rounded up.\n    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.\n            if mul(y, gt(x, div(not(0), y))) {\n                mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))\n        }\n    }\n\n    /// @dev Equivalent to `(x * WAD) / y` rounded down.\n    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.\n            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {\n                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.\n                revert(0x1c, 0x04)\n            }\n            z := div(mul(x, WAD), y)\n        }\n    }\n\n    /// @dev Equivalent to `(x * WAD) / y` rounded up.\n    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.\n            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {\n                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))\n        }\n    }\n\n    /// @dev Equivalent to `x` to the power of `y`.\n    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.\n    function powWad(int256 x, int256 y) internal pure returns (int256) {\n        // Using `ln(x)` means `x` must be greater than 0.\n        return expWad((lnWad(x) * y) / int256(WAD));\n    }\n\n    /// @dev Returns `exp(x)`, denominated in `WAD`.\n    function expWad(int256 x) internal pure returns (int256 r) {\n        unchecked {\n            // When the result is < 0.5 we return zero. This happens when\n            // x <= floor(log(0.5e18) * 1e18) ~ -42e18\n            if (x <= -42139678854452767551) return r;\n\n            /// @solidity memory-safe-assembly\n            assembly {\n                // When the result is > (2**255 - 1) / 1e18 we can not represent it as an\n                // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.\n                if iszero(slt(x, 135305999368893231589)) {\n                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.\n                    revert(0x1c, 0x04)\n                }\n            }\n\n            // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96\n            // for more intermediate precision and a binary basis. This base conversion\n            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.\n            x = (x << 78) / 5 ** 18;\n\n            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers\n            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.\n            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).\n            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;\n            x = x - k * 54916777467707473351141471128;\n\n            // k is in the range [-61, 195].\n\n            // Evaluate using a (6, 7)-term rational approximation.\n            // p is made monic, we'll multiply by a scale factor later.\n            int256 y = x + 1346386616545796478920950773328;\n            y = ((y * x) >> 96) + 57155421227552351082224309758442;\n            int256 p = y + x - 94201549194550492254356042504812;\n            p = ((p * y) >> 96) + 28719021644029726153956944680412240;\n            p = p * x + (4385272521454847904659076985693276 << 96);\n\n            // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n            int256 q = x - 2855989394907223263936484059900;\n            q = ((q * x) >> 96) + 50020603652535783019961831881945;\n            q = ((q * x) >> 96) - 533845033583426703283633433725380;\n            q = ((q * x) >> 96) + 3604857256930695427073651918091429;\n            q = ((q * x) >> 96) - 14423608567350463180887372962807573;\n            q = ((q * x) >> 96) + 26449188498355588339934803723976023;\n\n            /// @solidity memory-safe-assembly\n            assembly {\n                // Div in assembly because solidity adds a zero check despite the unchecked.\n                // The q polynomial won't have zeros in the domain as all its roots are complex.\n                // No scaling is necessary because p is already 2**96 too large.\n                r := sdiv(p, q)\n            }\n\n            // r should be in the range (0.09, 0.25) * 2**96.\n\n            // We now need to multiply r by:\n            // * the scale factor s = ~6.031367120.\n            // * the 2**k factor from the range reduction.\n            // * the 1e18 / 2**96 factor for base conversion.\n            // We do this all at once, with an intermediate result in 2**213\n            // basis, so the final right shift is always by a positive amount.\n            r = int256(\n                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)\n            );\n        }\n    }\n\n    /// @dev Returns `ln(x)`, denominated in `WAD`.\n    function lnWad(int256 x) internal pure returns (int256 r) {\n        unchecked {\n            /// @solidity memory-safe-assembly\n            assembly {\n                if iszero(sgt(x, 0)) {\n                    mstore(0x00, 0x1615e638) // `LnWadUndefined()`.\n                    revert(0x1c, 0x04)\n                }\n            }\n\n            // We want to convert x from 10**18 fixed point to 2**96 fixed point.\n            // We do this by multiplying by 2**96 / 10**18. But since\n            // ln(x * C) = ln(x) + ln(C), we can simply do nothing here\n            // and add ln(2**96 / 10**18) at the end.\n\n            // Compute k = log2(x) - 96.\n            int256 k;\n            /// @solidity memory-safe-assembly\n            assembly {\n                k := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n                k := or(k, shl(6, lt(0xffffffffffffffff, shr(k, x))))\n                k := or(k, shl(5, lt(0xffffffff, shr(k, x))))\n                k := or(k, shl(4, lt(0xffff, shr(k, x))))\n                k := or(k, shl(3, lt(0xff, shr(k, x))))\n                k := or(k, shl(2, lt(0xf, shr(k, x))))\n                k := sub(or(k, byte(shr(k, x), hex\"00000101020202020303030303030303\")), 96)\n            }\n\n            // Reduce range of x to (1, 2) * 2**96\n            // ln(2^k * x) = k * ln(2) + ln(x)\n            x = int256(uint256(x << uint256(159 - k)) >> 159);\n\n            // Evaluate using a (8, 8)-term rational approximation.\n            // p is made monic, we will multiply by a scale factor later.\n            int256 p = x + 3273285459638523848632254066296;\n            p = ((p * x) >> 96) + 24828157081833163892658089445524;\n            p = ((p * x) >> 96) + 43456485725739037958740375743393;\n            p = ((p * x) >> 96) - 11111509109440967052023855526967;\n            p = ((p * x) >> 96) - 45023709667254063763336534515857;\n            p = ((p * x) >> 96) - 14706773417378608786704636184526;\n            p = p * x - (795164235651350426258249787498 << 96);\n\n            // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n            // q is monic by convention.\n            int256 q = x + 5573035233440673466300451813936;\n            q = ((q * x) >> 96) + 71694874799317883764090561454958;\n            q = ((q * x) >> 96) + 283447036172924575727196451306956;\n            q = ((q * x) >> 96) + 401686690394027663651624208769553;\n            q = ((q * x) >> 96) + 204048457590392012362485061816622;\n            q = ((q * x) >> 96) + 31853899698501571402653359427138;\n            q = ((q * x) >> 96) + 909429971244387300277376558375;\n            /// @solidity memory-safe-assembly\n            assembly {\n                // Div in assembly because solidity adds a zero check despite the unchecked.\n                // The q polynomial is known not to have zeros in the domain.\n                // No scaling required because p is already 2**96 too large.\n                r := sdiv(p, q)\n            }\n\n            // r is in the range (0, 0.125) * 2**96\n\n            // Finalization, we need to:\n            // * multiply by the scale factor s = 5.549…\n            // * add ln(2**96 / 10**18)\n            // * add k * ln(2)\n            // * multiply by 10**18 / 2**96 = 5**18 >> 78\n\n            // mul s * 5e18 * 2**96, base is now 5**18 * 2**192\n            r *= 1677202110996718588342820967067443963516166;\n            // add ln(2) * k * 5e18 * 2**192\n            r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;\n            // add ln(2**96 / 10**18) * 5e18 * 2**192\n            r += 600920179829731861736702779321621459595472258049074101567377883020018308;\n            // base conversion: mul 2**18 / 2**192\n            r >>= 174;\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                  GENERAL NUMBER UTILITIES                  */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Calculates `floor(a * b / d)` with full precision.\n    /// Throws if result overflows a uint256 or when `d` is zero.\n    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv\n    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            for {} 1 {} {\n                // 512-bit multiply `[p1 p0] = x * y`.\n                // Compute the product mod `2**256` and mod `2**256 - 1`\n                // then use the Chinese Remainder Theorem to reconstruct\n                // the 512 bit result. The result is stored in two 256\n                // variables such that `product = p1 * 2**256 + p0`.\n\n                // Least significant 256 bits of the product.\n                let p0 := mul(x, y)\n                let mm := mulmod(x, y, not(0))\n                // Most significant 256 bits of the product.\n                let p1 := sub(mm, add(p0, lt(mm, p0)))\n\n                // Handle non-overflow cases, 256 by 256 division.\n                if iszero(p1) {\n                    if iszero(d) {\n                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.\n                        revert(0x1c, 0x04)\n                    }\n                    result := div(p0, d)\n                    break\n                }\n\n                // Make sure the result is less than `2**256`. Also prevents `d == 0`.\n                if iszero(gt(d, p1)) {\n                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.\n                    revert(0x1c, 0x04)\n                }\n\n                /*------------------- 512 by 256 division --------------------*/\n\n                // Make division exact by subtracting the remainder from `[p1 p0]`.\n                // Compute remainder using mulmod.\n                let r := mulmod(x, y, d)\n                // `t` is the least significant bit of `d`.\n                // Always greater or equal to 1.\n                let t := and(d, sub(0, d))\n                // Divide `d` by `t`, which is a power of two.\n                d := div(d, t)\n                // Invert `d mod 2**256`\n                // Now that `d` is an odd number, it has an inverse\n                // modulo `2**256` such that `d * inv = 1 mod 2**256`.\n                // Compute the inverse by starting with a seed that is correct\n                // correct for four bits. That is, `d * inv = 1 mod 2**4`.\n                let inv := xor(mul(3, d), 2)\n                // Now use Newton-Raphson iteration to improve the precision.\n                // Thanks to Hensel's lifting lemma, this also works in modular\n                // arithmetic, doubling the correct bits in each step.\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128\n                result :=\n                    mul(\n                        // Divide [p1 p0] by the factors of two.\n                        // Shift in bits from `p1` into `p0`. For this we need\n                        // to flip `t` such that it is `2**256 / t`.\n                        or(mul(sub(p1, gt(r, p0)), add(div(sub(0, t), t), 1)), div(sub(p0, r), t)),\n                        // inverse mod 2**256\n                        mul(inv, sub(2, mul(d, inv)))\n                    )\n                break\n            }\n        }\n    }\n\n    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.\n    /// Throws if result overflows a uint256 or when `d` is zero.\n    /// Credit to Uniswap-v3-core under MIT license:\n    /// https://github.com/Uniswap/v3-core/blob/contracts/libraries/FullMath.sol\n    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {\n        result = fullMulDiv(x, y, d);\n        /// @solidity memory-safe-assembly\n        assembly {\n            if mulmod(x, y, d) {\n                result := add(result, 1)\n                if iszero(result) {\n                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.\n                    revert(0x1c, 0x04)\n                }\n            }\n        }\n    }\n\n    /// @dev Returns `floor(x * y / d)`.\n    /// Reverts if `x * y` overflows, or `d` is zero.\n    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {\n                mstore(0x00, 0xad251c27) // `MulDivFailed()`.\n                revert(0x1c, 0x04)\n            }\n            z := div(mul(x, y), d)\n        }\n    }\n\n    /// @dev Returns `ceil(x * y / d)`.\n    /// Reverts if `x * y` overflows, or `d` is zero.\n    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {\n                mstore(0x00, 0xad251c27) // `MulDivFailed()`.\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))\n        }\n    }\n\n    /// @dev Returns `ceil(x / d)`.\n    /// Reverts if `d` is zero.\n    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            if iszero(d) {\n                mstore(0x00, 0x65244e4e) // `DivFailed()`.\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(x, d))), div(x, d))\n        }\n    }\n\n    /// @dev Returns `max(0, x - y)`.\n    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mul(gt(x, y), sub(x, y))\n        }\n    }\n\n    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.\n    /// Reverts if the computation overflows.\n    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.\n            if x {\n                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`\n                let half := shr(1, b) // Divide `b` by 2.\n                // Divide `y` by 2 every iteration.\n                for { y := shr(1, y) } y { y := shr(1, y) } {\n                    let xx := mul(x, x) // Store x squared.\n                    let xxRound := add(xx, half) // Round to the nearest number.\n                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.\n                    if or(lt(xxRound, xx), shr(128, x)) {\n                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.\n                        revert(0x1c, 0x04)\n                    }\n                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.\n                    // If `y` is odd:\n                    if and(y, 1) {\n                        let zx := mul(z, x) // Compute `z * x`.\n                        let zxRound := add(zx, half) // Round to the nearest number.\n                        // If `z * x` overflowed or `zx + half` overflowed:\n                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {\n                            // Revert if `x` is non-zero.\n                            if iszero(iszero(x)) {\n                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.\n                                revert(0x1c, 0x04)\n                            }\n                        }\n                        z := div(zxRound, b) // Return properly scaled `zxRound`.\n                    }\n                }\n            }\n        }\n    }\n\n    /// @dev Returns the square root of `x`.\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`\n            // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.\n            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffffff, shr(r, x))))\n            z := shl(shr(1, r), z)\n\n            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could\n            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.\n            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.\n            // That's not possible if `x < 256` but we can just verify those cases exhaustively.\n\n            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.\n            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.\n            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.\n\n            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`\n            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,\n            // with largest error when `s = 1` and when `s = 256` or `1/256`.\n\n            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.\n            // Then we can estimate `sqrt(y)` using\n            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.\n\n            // There is no overflow risk here since `y < 2**136` after the first branch above.\n            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If `x+1` is a perfect square, the Babylonian method cycles between\n            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n\n    /// @dev Returns the cube root of `x`.\n    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:\n    /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy\n    function cbrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n\n            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))\n\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n\n            z := sub(z, lt(div(x, mul(z, z)), z))\n        }\n    }\n\n    /// @dev Returns the square root of `x`, denominated in `WAD`.\n    function sqrtWad(uint256 x) internal pure returns (uint256 z) {\n        unchecked {\n            z = 10 ** 9;\n            if (x <= type(uint256).max / 10 ** 36 - 1) {\n                x *= 10 ** 18;\n                z = 1;\n            }\n            z *= sqrt(x);\n        }\n    }\n\n    /// @dev Returns the cube root of `x`, denominated in `WAD`.\n    function cbrtWad(uint256 x) internal pure returns (uint256 z) {\n        unchecked {\n            z = 10 ** 12;\n            if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {\n                if (x >= type(uint256).max / 10 ** 36) {\n                    x *= 10 ** 18;\n                    z = 10 ** 6;\n                } else {\n                    x *= 10 ** 36;\n                    z = 1;\n                }\n            }\n            z *= cbrt(x);\n        }\n    }\n\n    /// @dev Returns the factorial of `x`.\n    function factorial(uint256 x) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            if iszero(lt(x, 58)) {\n                mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.\n                revert(0x1c, 0x04)\n            }\n            for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }\n        }\n    }\n\n    /// @dev Returns the log2 of `x`.\n    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.\n    /// Returns 0 if `x` is zero.\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n            r := or(r, shl(2, lt(0xf, shr(r, x))))\n            r := or(r, byte(shr(r, x), hex\"00000101020202020303030303030303\"))\n        }\n    }\n\n    /// @dev Returns the log2 of `x`, rounded up.\n    /// Returns 0 if `x` is zero.\n    function log2Up(uint256 x) internal pure returns (uint256 r) {\n        r = log2(x);\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := add(r, lt(shl(r, 1), x))\n        }\n    }\n\n    /// @dev Returns the log10 of `x`.\n    /// Returns 0 if `x` is zero.\n    function log10(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            if iszero(lt(x, 100000000000000000000000000000000000000)) {\n                x := div(x, 100000000000000000000000000000000000000)\n                r := 38\n            }\n            if iszero(lt(x, 100000000000000000000)) {\n                x := div(x, 100000000000000000000)\n                r := add(r, 20)\n            }\n            if iszero(lt(x, 10000000000)) {\n                x := div(x, 10000000000)\n                r := add(r, 10)\n            }\n            if iszero(lt(x, 100000)) {\n                x := div(x, 100000)\n                r := add(r, 5)\n            }\n            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))\n        }\n    }\n\n    /// @dev Returns the log10 of `x`, rounded up.\n    /// Returns 0 if `x` is zero.\n    function log10Up(uint256 x) internal pure returns (uint256 r) {\n        r = log10(x);\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := add(r, lt(exp(10, r), x))\n        }\n    }\n\n    /// @dev Returns the log256 of `x`.\n    /// Returns 0 if `x` is zero.\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(shr(3, r), lt(0xff, shr(r, x)))\n        }\n    }\n\n    /// @dev Returns the log256 of `x`, rounded up.\n    /// Returns 0 if `x` is zero.\n    function log256Up(uint256 x) internal pure returns (uint256 r) {\n        r = log256(x);\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := add(r, lt(shl(shl(3, r), 1), x))\n        }\n    }\n\n    /// @dev Returns the average of `x` and `y`.\n    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = (x & y) + ((x ^ y) >> 1);\n        }\n    }\n\n    /// @dev Returns the average of `x` and `y`.\n    function avg(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = (x >> 1) + (y >> 1) + (((x & 1) + (y & 1)) >> 1);\n        }\n    }\n\n    /// @dev Returns the absolute value of `x`.\n    function abs(int256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x))\n        }\n    }\n\n    /// @dev Returns the absolute distance between `x` and `y`.\n    function dist(int256 x, int256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))\n        }\n    }\n\n    /// @dev Returns the minimum of `x` and `y`.\n    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), lt(y, x)))\n        }\n    }\n\n    /// @dev Returns the minimum of `x` and `y`.\n    function min(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), slt(y, x)))\n        }\n    }\n\n    /// @dev Returns the maximum of `x` and `y`.\n    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), gt(y, x)))\n        }\n    }\n\n    /// @dev Returns the maximum of `x` and `y`.\n    function max(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), sgt(y, x)))\n        }\n    }\n\n    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.\n    function clamp(uint256 x, uint256 minValue, uint256 maxValue)\n        internal\n        pure\n        returns (uint256 z)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))\n            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))\n        }\n    }\n\n    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.\n    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))\n            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))\n        }\n    }\n\n    /// @dev Returns greatest common divisor of `x` and `y`.\n    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            for { z := x } y {} {\n                let t := y\n                y := mod(z, y)\n                z := t\n            }\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                   RAW NUMBER OPERATIONS                    */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Returns `x + y`, without checking for overflow.\n    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = x + y;\n        }\n    }\n\n    /// @dev Returns `x + y`, without checking for overflow.\n    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = x + y;\n        }\n    }\n\n    /// @dev Returns `x - y`, without checking for underflow.\n    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = x - y;\n        }\n    }\n\n    /// @dev Returns `x - y`, without checking for underflow.\n    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = x - y;\n        }\n    }\n\n    /// @dev Returns `x * y`, without checking for overflow.\n    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = x * y;\n        }\n    }\n\n    /// @dev Returns `x * y`, without checking for overflow.\n    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = x * y;\n        }\n    }\n\n    /// @dev Returns `x / y`, returning 0 if `y` is zero.\n    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := div(x, y)\n        }\n    }\n\n    /// @dev Returns `x / y`, returning 0 if `y` is zero.\n    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := sdiv(x, y)\n        }\n    }\n\n    /// @dev Returns `x % y`, returning 0 if `y` is zero.\n    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mod(x, y)\n        }\n    }\n\n    /// @dev Returns `x % y`, returning 0 if `y` is zero.\n    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := smod(x, y)\n        }\n    }\n\n    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.\n    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := addmod(x, y, d)\n        }\n    }\n\n    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.\n    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mulmod(x, y, d)\n        }\n    }\n}\n"
      },
      "lib/unlockdv2-wallet/src/interfaces/IAllowedControllers.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.8.19;\n\ninterface IAllowedControllers {\n    event Collections(address indexed collections, bool isAllowed);\n\n    event DelegationController(address indexed delegationController, bool isAllowed);\n\n    function isAllowedDelegationController(address _controller) external view returns (bool);\n\n    function isAllowedCollection(address _collection) external view returns (bool);\n}\n"
      },
      "lib/unlockdv2-wallet/src/interfaces/IDelegationWalletRegistry.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.8.19;\n\ninterface IDelegationWalletRegistry {\n    struct Wallet {\n        address wallet;\n        address owner;\n        address guard;\n        address guardOwner;\n        address delegationOwner;\n        address protocolOwner;\n    }\n\n    function setFactory(address _delegationWalletFactory) external;\n\n    function setWallet(\n        address _wallet,\n        address _owner,\n        address _guard,\n        address _guardOwner,\n        address _delegationGuard,\n        address _protocolOwner\n    ) external;\n\n    function getWallet(address _wallet) external view returns (Wallet memory);\n\n    function getOwnerWalletAddresses(address _owner) external view returns (address[] memory);\n\n    function getOwnerWalletAt(address _owner, uint256 _index) external view returns (Wallet memory);\n}\n"
      },
      "lib/unlockdv2-wallet/src/interfaces/IProtocolOwner.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\ninterface IProtocolOwner {\n    ////////////////////////////////////////////////////////////////////////////////\n    // Events\n    ////////////////////////////////////////////////////////////////////////////////\n\n    event SetLockController(address indexed lockController, bool allowed);\n    event ChangeOwner(address indexed asset, uint256 indexed assetId, address newOwner);\n    event LockedAsset(\n        address indexed asset,\n        uint256 indexed assetId,\n        uint256 claimDate,\n        address indexed lockController\n    );\n\n    event UnlockedAsset(address indexed asset, uint256 indexed assetId, address indexed lockController);\n    event ClaimedAsset(address indexed asset, uint256 indexed assetId, address indexed receiver);\n    event TransferredAsset(address indexed asset, uint256 indexed assetId, address indexed receiver);\n\n    event SetLoanId(bytes32 index, bytes32 loanId);\n    event SetBatchLoanId(bytes32[] indexed assets, bytes32 indexed loanId);\n\n    ////////////////////////////////////////////////////////////////////////////////\n    // Functions\n    ////////////////////////////////////////////////////////////////////////////////\n\n    function approveSale(\n        address _collection,\n        uint256 _tokenId,\n        address _underlyingAsset,\n        uint256 _amount,\n        address _marketApproval,\n        bytes32 _loanId\n    ) external;\n\n    // Delegatee Functions\n    function execTransaction(\n        address _to,\n        uint256 _value,\n        bytes calldata _data,\n        uint256 _safeTxGas,\n        uint256 _baseGas,\n        uint256 _gasPrice,\n        address _gasToken,\n        address payable _refundReceiver\n    ) external returns (bool success);\n\n    function delegateOneExecution(address to, bool value) external;\n\n    function isDelegatedExecution(address to) external view returns (bool);\n\n    function isAssetLocked(bytes32 _id) external view returns (bool);\n\n    function batchSetLoanId(bytes32[] calldata _assets, bytes32 _loanId) external;\n\n    function batchSetToZeroLoanId(bytes32[] calldata _assets) external;\n\n    function changeOwner(address _asset, uint256 _id, address _newOwner) external;\n\n    function getLoanId(bytes32 _assetId) external view returns (bytes32);\n\n    function setLoanId(bytes32 _assetId, bytes32 _loanId) external;\n\n    function safeSetLoanId(address _asset, uint256 _id, bytes32 _loanId) external;\n}\n"
      },
      "lib/unlockdv2-wallet/src/libs/logic/AssetLogic.sol": {
        "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.19;\n\nlibrary AssetLogic {\n    function assetId(address _asset, uint256 _id) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(_asset, _id));\n    }\n\n    function getSelector(bytes memory _data) internal pure returns (bytes4 selector) {\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            selector := mload(add(_data, 32))\n        }\n    }\n}\n"
      },
      "src/interfaces/IACLManager.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {IAccessControl} from '@openzeppelin/contracts/access/IAccessControl.sol';\n\n/**\n * @title IACLManager\n * @author Unlockd\n * @notice Defines the basic interface for the ACL Manager\n */\ninterface IACLManager is IAccessControl {\n  /**\n   * @notice Returns the identifier of the UtokenAdmin role\n   * @return The id of the UtokenAdmin role\n   */\n  function UTOKEN_ADMIN() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the Protocol Admin role\n   * @return The id of the Protocol Admin role\n   */\n  function PROTOCOL_ADMIN() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the PriceUpdater role\n   * @return The id of the PriceUpdater role\n   */\n  function PRICE_UPDATER() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the EmergencyAdmin role\n   * @return The id of the EmergencyAdmin role\n   */\n  function AUCTION_ADMIN() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the EmergencyAdmin role\n   * @return The id of the EmergencyAdmin role\n   */\n  function EMERGENCY_ADMIN() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the Governance Admin role\n   * @return The id of the PriceUpdater role\n   */\n  function GOVERNANCE_ADMIN() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the WRAPPER ADAPTER role\n   * @return The id of the PriceUpdater role\n   */\n  function WRAPPER_ADAPTER() external view returns (bytes32);\n\n  /**\n   * @notice Set the address of the protocol\n   * @dev Is the main address of the protocol.Only can be updated by the ADMIN.\n   * @param protocol address of the protocol\n   */\n  function setProtocol(address protocol) external;\n\n  /**\n   * @notice Returns true if the address is the protocol, false otherwise\n   * @param protocol The address to check\n   * @return True if the given address is the protocol, false otherwise\n   */\n  function isProtocol(address protocol) external view returns (bool);\n\n  /**\n   * @notice Set the role as admin of a specific role.\n   * @dev By default the admin role for all roles is `DEFAULT_ADMIN_ROLE`.\n   * @param role The role to be managed by the admin role\n   * @param adminRole The admin role\n   */\n  function setRoleAdmin(bytes32 role, bytes32 adminRole) external;\n\n  // UTOKEN\n  /**\n   * @notice Adds a new admin as  Utoken Admin\n   * @param admin The address of the new admin\n   */\n  function addUTokenAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as  Utoken Admin\n   * @param admin The address of the admin to remove\n   */\n  function removeUTokenAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is Utoken Admin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is  Utoken Admin, false otherwise\n   */\n  function isUTokenAdmin(address admin) external view returns (bool);\n\n  // PROTOCOL\n  /**\n   * @notice Adds a new admin as  Protocol Admin\n   * @param admin The address of the new admin\n   */\n  function addProtocolAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as  Protocol Admin\n   * @param admin The address of the admin to remove\n   */\n  function removeProtocolAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is Protocol Admin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is  Protocol Admin, false otherwise\n   */\n  function isProtocolAdmin(address admin) external view returns (bool);\n\n  // AUCTION ADMIN\n  /**\n   * @notice Adds a new admin as  Auction Admin\n   * @param admin The address of the new admin\n   */\n  function addAuctionAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as  Auction Admin\n   * @param admin The address of the admin to remove\n   */\n  function removeAuctionAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is Auction Admin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is  Auction Admin, false otherwise\n   */\n  function isAuctionAdmin(address admin) external view returns (bool);\n\n  // EMERGENCY\n  /**\n   * @notice Adds a new admin as EmergencyAdmin\n   * @param admin The address of the new admin\n   */\n  function addEmergencyAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as EmergencyAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removeEmergencyAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is EmergencyAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is EmergencyAdmin, false otherwise\n   */\n  function isEmergencyAdmin(address admin) external view returns (bool);\n\n  // PRICE UPDATER\n  /**\n   * @notice Adds a new admin as PriceUpdater\n   * @param admin The address of the new PriceUpdater\n   */\n  function addPriceUpdater(address admin) external;\n\n  /**\n   * @notice Removes an admin as PriceUpdater\n   * @param admin The address of the PriceUpdater to remove\n   */\n  function removePriceUpdater(address admin) external;\n\n  /**\n   * @notice Returns true if the address is PriceUpdater, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is PriceUpdater, false otherwise\n   */\n  function isPriceUpdater(address admin) external view returns (bool);\n\n  // Governance admin\n  /**\n   * @notice Adds a new admin as Govnernance admin\n   * @param admin The address of the new Governance admin\n   */\n  function addGovernanceAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as Governance Admin\n   * @param admin The address of the Governance Admin to remove\n   */\n  function removeGovernanceAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is Governance Admin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is Governance Admin, false otherwise\n   */\n  function isGovernanceAdmin(address admin) external view returns (bool);\n\n  // Wrapper ADAPTER\n  /**\n   * @notice Adds a new adapter as WRAPPER_ADAPTER\n   * @param adapter The address of the new adapter\n   */\n  function addWrapperAdapter(address adapter) external;\n\n  /**\n   * @notice Removes an adapter as WRAPPER_ADAPTER\n   * @param adapter The address of the WRAPPER_ADAPTER to remove\n   */\n  function removeWrapperAdapter(address adapter) external;\n\n  /**\n   * @notice Returns true if the address is WRAPPER_ADAPTER, false otherwise\n   * @param adapter The address to check\n   * @return True if the given address is WRAPPER_ADAPTER, false otherwise\n   */\n  function isWrapperAdapter(address adapter) external view returns (bool);\n}\n"
      },
      "src/interfaces/IEmergency.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\ninterface IEmergency {\n  function emergencyWithdraw(address payable _to) external;\n\n  function emergencyWithdrawERC20(address _asset, address _to) external;\n}\n"
      },
      "src/interfaces/IStrategy.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\ninterface IStrategy {\n  struct StrategyConfig {\n    address asset;\n    address vault;\n    uint256 minCap;\n    uint256 percentageToInvest;\n  }\n\n  function asset() external view returns (address);\n\n  function getConfig() external view returns (StrategyConfig memory);\n\n  // Returns the total value the strategy holds (principle + gain) expressed in asset token amount.\n  function balanceOf(address sharesPool) external view returns (uint256);\n\n  function calculateAmountToSupply(\n    uint256 totalSupplyNotInvested_,\n    address from_,\n    uint256 amount_\n  ) external returns (uint256);\n\n  // Function that invest on the this strategy\n  function supply(\n    address vault_,\n    address asset_,\n    address from_,\n    uint256 amount_\n  ) external returns (uint256);\n\n  function calculateAmountToWithdraw(\n    uint256 totalSupplyNotInvested_,\n    address from_,\n    uint256 amount_\n  ) external view returns (uint256);\n\n  // Function to withdraw specific amount\n  function withdraw(address vault_, address to_, uint256 amount_) external returns (uint256);\n}\n"
      },
      "src/interfaces/IUTokenVault.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {Constants} from '../libraries/helpers/Constants.sol';\n\ninterface IUTokenVault {\n  //////////////////////////////////\n  // EVENS\n\n  event MarketCreated(\n    address indexed underlyingAsset,\n    address indexed interestRate,\n    address indexed strategy,\n    address sharesToken\n  );\n\n  event MarketInterestRateUpdated(address indexed underlyingAsset, address indexed interestRate);\n\n  event ReserveDataUpdated(\n    address indexed reserve,\n    uint256 liquidityRate,\n    uint256 variableBorrowRate,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex\n  );\n\n  event Deposit(\n    address indexed user,\n    address indexed onBehalfOf,\n    address indexed underlyingAsset,\n    uint256 amount\n  );\n  event Withdraw(\n    address indexed user,\n    address indexed to,\n    address indexed underlyingAsset,\n    uint256 amount\n  );\n\n  event Borrow(\n    address indexed iniciator,\n    address indexed onBehalfOf,\n    address indexed underlyingAsset,\n    uint256 amount,\n    bytes32 loanId,\n    uint256 borrowRate\n  );\n\n  event Repay(\n    address indexed iniciator,\n    address indexed onBehalfOf,\n    address indexed underlyingAsset,\n    uint256 amount,\n    bytes32 loanId,\n    uint256 borrowRate\n  );\n\n  event UpdateReserveState(address indexed underlyingAsset, uint256 newState);\n\n  event DisableReserveStrategy(address indexed underlyingAsset);\n\n  event UpdateReserveStrategy(address indexed underlyingAsset, address indexed newStrategy);\n  /**\n   * @dev Emitted when the pause is triggered.\n   */\n  event Paused();\n\n  /**\n   * @dev Emitted when the pause is lifted.\n   */\n  event Unpaused();\n\n  event ActiveVault(address indexed underlyingAsset, bool isActive);\n  event FrozenVault(address indexed underlyingAsset, bool isFrozen);\n  event PausedVault(address indexed underlyingAsset, bool isPaused);\n\n  event UpdateCaps(\n    address indexed underlyingAsset,\n    uint256 minCap,\n    uint256 depositCap,\n    uint256 borrowCap\n  );\n  //////////////////////////////////\n  // STRUCTS\n\n  struct CreateMarketParams {\n    address interestRateAddress;\n    address strategyAddress;\n    uint16 reserveFactor;\n    address underlyingAsset;\n    Constants.ReserveType reserveType;\n    uint8 decimals;\n    string tokenName;\n    string tokenSymbol;\n  }\n\n  //////////////////////////////////\n  // ONLY ADMIN\n\n  function createMarket(CreateMarketParams calldata params) external;\n\n  //////////////////////////////////\n  // PUBLIC\n\n  function deposit(address underlyingAsset, uint256 amount, address onBehalf) external;\n\n  function withdraw(address underlyingAsset, uint256 amount, address onBehalf) external;\n\n  //////////////////////////////////\n  // ONLY PROTOCOL\n\n  function borrow(\n    address underlyingAsset,\n    bytes32 loanId,\n    uint256 amount,\n    address to,\n    address onBehalfOf\n  ) external;\n\n  function repay(\n    address underlyingAsset,\n    bytes32 loanId,\n    uint256 amount,\n    address from,\n    address onBehalfOf\n  ) external;\n\n  function updateState(address underlyingAsset) external;\n\n  //////////////////////////////////\n  // GETTERS\n\n  function validateReserveType(\n    Constants.ReserveType currentReserveType,\n    Constants.ReserveType reserveType\n  ) external view returns (bool);\n\n  function getReserveData(\n    address underlyingAsset\n  ) external view returns (DataTypes.ReserveData memory);\n\n  function getScaledToken(address underlyingAsset) external view returns (address);\n\n  function getCaps(address underlyingAsset) external view returns (uint256, uint256, uint256);\n\n  function getFlags(address underlyingAsset) external view returns (bool, bool, bool);\n\n  function getDecimals(address underlyingAsset) external view returns (uint256);\n\n  function getReserveType(address underlyingAsset) external view returns (Constants.ReserveType);\n\n  function getScaledTotalDebtMarket(address underlyingAsset) external view returns (uint256);\n\n  function getTotalDebtFromUser(\n    address underlyingAsset,\n    address user\n  ) external view returns (uint256);\n\n  function getScaledTotalDebtFromUser(\n    address underlyingAsset,\n    address user\n  ) external view returns (uint256);\n\n  function getDebtFromLoanId(\n    address underlyingAsset,\n    bytes32 loanId\n  ) external view returns (uint256);\n\n  function getScaledDebtFromLoanId(\n    address underlyingAsset,\n    bytes32 loanId\n  ) external view returns (uint256);\n\n  function getBalances(\n    address underlyingAsset\n  ) external view returns (DataTypes.MarketBalance memory);\n\n  function getBalanceByUser(address underlyingAsset, address user) external view returns (uint256);\n\n  function getScaledBalanceByUser(\n    address underlyingAsset,\n    address user\n  ) external view returns (uint256);\n\n  function totalSupply(address underlyingAsset) external view returns (uint256);\n\n  function totalAvailableSupply(address underlyingAsset) external view returns (uint256);\n\n  function totalSupplyNotInvested(address underlyingAsset) external view returns (uint256);\n}\n"
      },
      "src/interfaces/oracles/IReserveOracle.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\n/**\n *\n * @title IReserveOracle interface\n * @notice Interface for getting Reserve price oracle.\n */\ninterface IReserveOracle {\n  event AggregatorAdded(address currencyKey, address aggregator);\n  event AggregatorRemoved(address currencyKey, address aggregator);\n\n  /**\n   *\n   * @dev returns the asset price in the base CURRENCY\n   */\n  function getAssetPrice(address asset) external view returns (uint256);\n}\n"
      },
      "src/interfaces/tokens/IInterestRate.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\n/**\n * @title IInterestRate interface\n * @dev Interface for the calculation of the interest rates\n * @author Unlockd\n */\ninterface IInterestRate {\n  struct CalculateInterestRatesParams {\n    uint256 liquidityAdded;\n    uint256 liquidityTaken;\n    uint256 totalVariableDebt;\n    uint256 totalSupplyAssets;\n    uint256 reserveFactor;\n  }\n\n  /**\n   * @dev Get the variable borrow rate\n   * @return the base variable borrow rate\n   *\n   */\n  function baseVariableBorrowRate() external view returns (uint256);\n\n  /**\n   * @dev Get the maximum variable borrow rate\n   * @return the maximum variable borrow rate\n   *\n   */\n  function getMaxVariableBorrowRate() external view returns (uint256);\n\n  /**\n   * @dev Calculates the interest rates depending on the reserve's state and configurations\n   * @param params params needed to calculate the interest rate\n   */\n  function calculateInterestRates(\n    CalculateInterestRatesParams memory params\n  ) external view returns (uint256, uint256);\n\n  /**\n   * @dev Calculates the interest rates depending on the reserve's state and configurations\n   * @param availableLiquidity The available liquidity for the reserve\n   * @param totalVariableDebt The total borrowed from the reserve at a variable rate\n   * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market\n   *\n   */\n  function calculateInterestRates(\n    uint256 availableLiquidity,\n    uint256 totalVariableDebt,\n    uint256 reserveFactor\n  ) external view returns (uint256 currentLiquidityRate, uint256 currentVariableBorrowRate);\n}\n"
      },
      "src/libraries/base/BaseEmergency.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\nimport {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';\nimport {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\nimport {IACLManager} from '../../interfaces/IACLManager.sol';\nimport {IEmergency} from '../../interfaces/IEmergency.sol';\nimport {Errors} from '../helpers/Errors.sol';\n\n/**\n * @title BaseEmergency\n * @notice Base logic to recover funds\n * @author Unlockd\n */\ncontract BaseEmergency is IEmergency {\n  using SafeERC20 for IERC20;\n\n  address immutable _aclManager;\n  /**\n   * @dev Modifier that checks if the sender has Protocol Emergency Admin ROLE\n   */\n  modifier onlyEmergencyAdmin() {\n    if (!IACLManager(_aclManager).isEmergencyAdmin(msg.sender)) {\n      revert Errors.ProtocolAccessDenied();\n    }\n    _;\n  }\n\n  constructor(address aclManager) {\n    if (aclManager == address(0)) revert Errors.ZeroAddress();\n    _aclManager = aclManager;\n  }\n\n  /**\n   * @dev Execute emegency native withdraw, only executable by the emergency admin\n   * @param _to address to send the amount\n   */\n  function emergencyWithdraw(address payable _to) external onlyEmergencyAdmin {\n    (bool sent, ) = _to.call{value: address(this).balance}('');\n    if (sent == false) revert Errors.UnsuccessfulExecution();\n  }\n\n  /**\n   * @dev Execute emegency ERC20 withdraw, only executable by the emergency admin\n   * @param _to address to send the amount\n   */\n  function emergencyWithdrawERC20(address _asset, address _to) external onlyEmergencyAdmin {\n    IERC20(_asset).safeTransfer(_to, IERC20(_asset).balanceOf(address(this)));\n  }\n}\n"
      },
      "src/libraries/base/BaseToken.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {ERC20Upgradeable} from '../utils/tokens/ERC20Upgradeable.sol';\nimport {IACLManager} from '../../interfaces/IACLManager.sol';\nimport {DataTypes} from '../../types/DataTypes.sol';\nimport {Errors} from '../helpers/Errors.sol';\n\n/**\n * @title BaseToken\n * @notice Base ERC20 implementation\n * @author Unlockd\n *\n */\nabstract contract BaseToken is ERC20Upgradeable {\n  /////////////////////////////////////////\n  //  CONFIGURATION\n  /////////////////////////////////////////\n  address internal _aclManager;\n  address internal _uTokenVault;\n  uint8 internal _decimals;\n  /////////////////////////////////////////\n  //  Status\n  /////////////////////////////////////////\n  bool internal _active;\n  bool internal _frozen;\n\n  /////////////////////////////////////////\n  //  MODIFIERS\n  /////////////////////////////////////////\n\n  /**\n   * @dev Modifier that checks if the token is Active\n   */\n  modifier isActive() {\n    if (!_active) revert Errors.Paused();\n    _;\n  }\n\n  /**\n   * @dev Modifier that checks if the token is Frozen\n   */\n  modifier isFrozen() {\n    if (_frozen) revert Errors.Frozen();\n    _;\n  }\n\n  /**\n   * @dev Modifier that checks if the sender is the protocol\n   */\n  modifier onlyProtocol() {\n    if (!IACLManager(_aclManager).isProtocol(_msgSender())) {\n      revert Errors.ProtocolAccessDenied();\n    }\n    _;\n  }\n\n  /**\n   * @dev Modifier that checks if the sender has Protocol Emergency Admin ROLE\n   */\n  modifier onlyEmergencyAdmin() {\n    if (!IACLManager(_aclManager).isEmergencyAdmin(msg.sender)) {\n      revert Errors.ProtocolAccessDenied();\n    }\n    _;\n  }\n\n  /**\n   * @dev Modifier that checks if the sender has Protocol UToken Admin ROLE\n   */\n  modifier onlyAdmin() {\n    if (!IACLManager(_aclManager).isUTokenAdmin(_msgSender())) {\n      revert Errors.UTokenAccessDenied();\n    }\n    _;\n  }\n\n  /**\n   * @dev Modifier that checks if the sender is the uTokenVault\n   */\n  modifier onlyUTokenVault() {\n    if (_uTokenVault != _msgSender()) revert Errors.UTokenAccessDenied();\n    _;\n  }\n\n  ////////////////////////////////////////////////////7\n\n  function __BaseToken_init(\n    address aclManager_,\n    address uTokenVault_,\n    uint8 decimals_,\n    string calldata name_,\n    string calldata symbol_\n  ) internal initializer {\n    _aclManager = aclManager_;\n    _uTokenVault = uTokenVault_;\n    _decimals = decimals_;\n    __ERC20_init(name_, symbol_);\n\n    // Set inital state\n    _active = true;\n    _frozen = false;\n  }\n\n  ////////////////////////////////////////////////////7\n  // PUBLIC\n  ////////////////////////////////////////////////////7\n\n  /**\n   * @dev Update to active the token state\n   * @param active boolean\n   */\n  function setActive(bool active) external onlyEmergencyAdmin {\n    _active = active;\n  }\n\n  /**\n   * @dev Update to frozen the token state\n   * @param frozen boolean\n   */\n  function setFrozen(bool frozen) external onlyEmergencyAdmin {\n    _frozen = frozen;\n  }\n\n  /**\n   * @dev Return the number of decimals of the token\n   */\n  function decimals() public view virtual override returns (uint8) {\n    return _decimals;\n  }\n\n  ////////////////////////////////////////////////////7\n  // PRIVATE\n  ////////////////////////////////////////////////////7\n\n  function _transfer(address sender, address recipient, uint256 amount) internal virtual override {\n    super._transfer(sender, recipient, amount);\n  }\n\n  function _mint(address account, uint256 amount) internal virtual override isFrozen isActive {\n    super._mint(account, amount);\n  }\n\n  function _burn(address account, uint256 amount) internal virtual override isFrozen {\n    super._burn(account, amount);\n  }\n}\n"
      },
      "src/libraries/configuration/ReserveConfiguration.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {DataTypes, Constants} from '../../types/DataTypes.sol';\nimport {Errors} from '../helpers/Errors.sol';\n\n/**\n * @title ReserveConfiguration library\n * @author Unlockd\n * @notice Implements the bitmap logic to handle the reserve configuration\n * @dev based on Aave ReserveConfiguration https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/configuration/ReserveConfiguration.sol\n */\nlibrary ReserveConfiguration {\n  // @dev each F is x4\n  uint256 internal constant RESERVE_FACTOR_MASK =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n  uint256 internal constant BORROW_CAP_MASK     =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFF; // prettier-ignore\n  uint256 internal constant DEPOSIT_CAP_MASK    =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant MIN_CAP_MASK        =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant DECIMALS_MASK       =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant ACTIVE_MASK         =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant FROZEN_MASK         =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant PAUSED_MASK         =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant RESERVE_TYPE_MASK   =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n\n  ///////////////////////////////////////\n  // BIT POSITIONS\n  /// @dev For the RESERVE_FACTOR, the start bit is 0 (up to 15), hence no bitshifting is needed\n\n  uint256 internal constant BORROW_CAP_START_BIT_POSITION     = 16; // prettier-ignore\n  uint256 internal constant DEPOSIT_CAP_START_BIT_POSITION    = 52; // prettier-ignore\n  uint256 internal constant MIN_CAP_START_BIT_POSITION        = 88; // prettier-ignore\n\n  uint256 internal constant DECIMALS_START_BIT_POSITION       = 124; // prettier-ignore\n\n  uint256 internal constant IS_ACTIVE_START_BIT_POSITION      = 132; // prettier-ignore\n  uint256 internal constant IS_FROZEN_START_BIT_POSITION      = 133; // prettier-ignore\n  uint256 internal constant IS_PAUSED_START_BIT_POSITION      = 136; // prettier-ignore\n\n  uint256 internal constant RESERVE_TYPE_START_BIT_POSITION   = 140; // prettier-ignore\n\n  ///////////////////////////////////////\n  // VALIDATIONS\n\n  uint256 internal constant MAX_VALID_DECIMALS                = 255; // prettier-ignore\n  uint256 internal constant MAX_VALID_RESERVE_FACTOR          = 65535; // prettier-ignore\n  uint256 internal constant MAX_VALID_BORROW_CAP              = 68719476735; // prettier-ignore\n  uint256 internal constant MAX_VALID_DEPOSIT_CAP             = 68719476735; // prettier-ignore\n  uint256 internal constant MAX_VALID_MIN_CAP                 = 68719476735; // prettier-ignore\n\n  /**\n   * @notice Sets reserve factor\n   * @param self The reserve configuration\n   * @param reserveFactor value reserve factor\n   */\n  function setReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 reserveFactor\n  ) internal pure {\n    if (reserveFactor > MAX_VALID_RESERVE_FACTOR) revert Errors.InvalidReserveFactor();\n    self.data = (self.data & RESERVE_FACTOR_MASK) | reserveFactor;\n  }\n\n  /**\n   * @notice Gets reserve factor\n   * @param self The reserve configuration\n   * @return The borrow cap\n   */\n  function getReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return self.data & ~RESERVE_FACTOR_MASK;\n  }\n\n  /**\n   * @notice Sets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @param borrowCap The borrow cap\n   */\n  function setBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 borrowCap\n  ) internal pure {\n    if (borrowCap > MAX_VALID_BORROW_CAP) revert Errors.InvalidMaxBorrowCap();\n    self.data = (self.data & BORROW_CAP_MASK) | (borrowCap << BORROW_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @return The borrow cap\n   */\n  function getBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @param depositCap The supply cap\n   */\n  function setDepositCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 depositCap\n  ) internal pure {\n    if (depositCap > MAX_VALID_DEPOSIT_CAP) revert Errors.InvalidMaxDepositCap();\n    self.data = (self.data & DEPOSIT_CAP_MASK) | (depositCap << DEPOSIT_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @return The deposit cap\n   */\n  function getDepositCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~DEPOSIT_CAP_MASK) >> DEPOSIT_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the min cap of the reserve\n   * @param self The reserve configuration\n   * @param minCap The supply cap\n   */\n  function setMinCap(DataTypes.ReserveConfigurationMap memory self, uint256 minCap) internal pure {\n    if (minCap > MAX_VALID_MIN_CAP) revert Errors.InvalidMaxMinCap();\n    self.data = (self.data & MIN_CAP_MASK) | (minCap << MIN_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the min cap of the reserve\n   * @param self The reserve configuration\n   * @return The supply cap\n   */\n  function getMinCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~MIN_CAP_MASK) >> MIN_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @param decimals The decimals\n   */\n  function setDecimals(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 decimals\n  ) internal pure {\n    if (decimals > MAX_VALID_DECIMALS) revert Errors.InvalidMaxDecimals();\n    self.data = (self.data & DECIMALS_MASK) | (decimals << DECIMALS_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @return The decimals of the asset\n   */\n  function getDecimals(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~DECIMALS_MASK) >> DECIMALS_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the active state of the reserve\n   * @param self The reserve configuration\n   * @param active The active state\n   */\n  function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {\n    self.data =\n      (self.data & ACTIVE_MASK) |\n      (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the active state of the reserve\n   * @param self The reserve configuration\n   * @return The active state\n   */\n  function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~ACTIVE_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @param frozen The frozen state\n   */\n  function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {\n    self.data =\n      (self.data & FROZEN_MASK) |\n      (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @return The frozen state\n   */\n  function getFrozen(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~FROZEN_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the paused state of the reserve\n   * @param self The reserve configuration\n   * @param paused The paused state\n   */\n  function setPaused(DataTypes.ReserveConfigurationMap memory self, bool paused) internal pure {\n    self.data =\n      (self.data & PAUSED_MASK) |\n      (uint256(paused ? 1 : 0) << IS_PAUSED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the paused state of the reserve\n   * @param self The reserve configuration\n   * @return The paused state\n   */\n  function getPaused(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~PAUSED_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the reserve type of the reserve\n   * @param self The reserve configuration\n   * @param reserveType type of the reserve\n   */\n  function setReserveType(\n    DataTypes.ReserveConfigurationMap memory self,\n    Constants.ReserveType reserveType\n  ) internal pure {\n    self.data =\n      (self.data & RESERVE_TYPE_MASK) |\n      (uint(reserveType) << RESERVE_TYPE_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @return The decimals of the asset\n   */\n  function getReserveType(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (Constants.ReserveType) {\n    return\n      Constants.ReserveType((self.data & ~RESERVE_TYPE_MASK) >> RESERVE_TYPE_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the caps parameters of the reserve from storage\n   * @param self The reserve configuration\n   * @return borrowCap The state param representing borrow cap\n   * @return depositCap The state param representing supply cap.\n   * @return MinCap The state param representing min cap.\n   */\n  function getCaps(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256, uint256, uint256) {\n    uint256 dataLocal = self.data;\n\n    return (\n      (dataLocal & ~BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION,\n      (dataLocal & ~DEPOSIT_CAP_MASK) >> DEPOSIT_CAP_START_BIT_POSITION,\n      (dataLocal & ~MIN_CAP_MASK) >> MIN_CAP_START_BIT_POSITION\n    );\n  }\n\n  /**\n   * @notice Gets the configuration flags of the reserve\n   * @param self The reserve configuration\n   * @return The state flag representing active\n   * @return The state flag representing frozen\n   * @return The state flag representing paused\n   */\n  function getFlags(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool, bool, bool) {\n    uint256 dataLocal = self.data;\n\n    return (\n      (dataLocal & ~ACTIVE_MASK) != 0,\n      (dataLocal & ~FROZEN_MASK) != 0,\n      (dataLocal & ~PAUSED_MASK) != 0\n    );\n  }\n}\n"
      },
      "src/libraries/helpers/Constants.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nlibrary Constants {\n  ////////////////////////////////////////////\n  // Reentrancy Guard for modules\n  ////////////////////////////////////////////\n  uint256 internal constant REENTRANCYLOCK__UNLOCKED = 0; // prettier-ignore\n  uint256 internal constant REENTRANCYLOCK__LOCKED   = 2; // prettier-ignore\n\n  ////////////////////////////////////////////\n  // Modules Configuration\n  ////////////////////////////////////////////\n\n  uint256 internal constant MAX_EXTERNAL_SINGLE_PROXY_MODULEID = 499_999; // prettier-ignore\n  uint256 internal constant MAX_EXTERNAL_MODULEID              = 999_999; // prettier-ignore\n\n  ////////////////////////////////////////////\n  // List Modules\n  ////////////////////////////////////////////\n\n  // Public single-proxy modules\n  uint256 internal constant MODULEID__INSTALLER  = 1; // prettier-ignore\n  uint256 internal constant MODULEID__MANAGER    = 2; // prettier-ignore\n  uint256 internal constant MODULEID__ACTION     = 3; // prettier-ignore\n  uint256 internal constant MODULEID__AUCTION    = 4; // prettier-ignore\n  uint256 internal constant MODULEID__MARKET     = 5; // prettier-ignore\n  uint256 internal constant MODULEID__BUYNOW     = 6; // prettier-ignore\n  uint256 internal constant MODULEID__SELLNOW    = 7; // prettier-ignore\n\n  ////////////////////////////////////////////\n  // RESERVE STATE\n  ////////////////////////////////////////////\n\n  enum ReserveState {\n    STOPPED, // No supply, No borrow\n    FREEZED, // No supply, No withdraw , No borrow, No repay\n    ACTIVE // All OK\n  }\n\n  ////////////////////////////////////////////\n  // LOAN STATE\n  ////////////////////////////////////////////\n\n  enum LoanState {\n    BLOCKED,\n    ACTIVE,\n    FREEZE\n  }\n\n  ////////////////////////////////////////////\n  // GRUP RESERVE TYPE\n  ////////////////////////////////////////////\n\n  enum ReserveType {\n    DISABLED, // Disabled collection\n    ALL, // All the assets with the exception SPECIAL\n    STABLE, // For the stable coins\n    COMMON, // Common coins WETH etc ...\n    SPECIAL // Only if the collection is also isolated to one asset token\n  }\n\n  ////////////////////////////////////////////\n  // ORDER TYPE\n  ////////////////////////////////////////////\n\n  enum OrderType {\n    TYPE_LIQUIDATION_AUCTION,\n    //Auction with BIDs\n    TYPE_AUCTION,\n    // Fixed price only buynow function\n    TYPE_FIXED_PRICE,\n    // Fixed price and auction with bids\n    TYPE_FIXED_PRICE_AND_AUCTION\n  }\n}\n"
      },
      "src/libraries/helpers/Errors.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\n/**\n * @title Errors library\n * @author Unlockd\n * @notice Defines the error messages emitted by the different contracts of the Unlockd protocol\n */\nlibrary Errors {\n  ///////////////////////////////////////////\n  ///   GENERIC\n  ///////////////////////////////////////////\n\n  error AccessDenied();\n  //error ZeroAddress(string paramName);\n\n  error InvalidParam(string paramName);\n  error ArrayLengthMismatch(string details);\n  error InvalidArrayLength();\n  error Paused();\n  error Frozen();\n\n  error AddressesNotEquals();\n  error NumbersNotEquals();\n\n  error ZeroAddress();\n  error ZeroBytes();\n  error ZeroNumber();\n\n  error ACLAdminZeroAddress();\n\n  error UTokenNotAllowed();\n  error AdapterNotAllowed();\n  error TimestampExpired();\n  error TimestampNotExpired();\n  error NotImplemented();\n\n  error InvalidParams();\n  error InvalidModule();\n  error InvalidCurrentLtv();\n  error InvalidTotalAmount();\n  error InvalidCurrentLiquidationThreshold();\n  error InvalidUserCollateralBalance();\n  error InvalidOrderOwner();\n  error InvalidOrderBuyer();\n  error InvalidBidAmount();\n  error InvalidLoanOwner();\n  error InvalidUnderlyingAsset();\n  error InvalidAssets();\n  error InvalidEndAmount();\n  error InvalidStartAmount();\n  error InvalidEndTime();\n  error InvalidStartTime();\n\n  error InvalidPriceFeedKey();\n  error InvalidAggregator();\n  error InvalidLastRoundData();\n\n  error NotEnoughLiquidity();\n  error DebtExceedsAmount();\n  error AmountExceedsDebt();\n  error AmountExceedsBalance();\n  error AmountToLow();\n  error CollectionNotAllowed();\n  error NotAssetOwner();\n  error UnsuccessfulExecution();\n  error AssetsMismatch();\n  error InvalidRecoveredAddress();\n  error SenderZeroAddress();\n  error OrderActive();\n\n  error WrongNonce();\n\n  error NotEqualDeadline();\n  error NotEqualUnderlyingAsset();\n  error NotEqualTotalAssets();\n  error NotEqualOrderOwner();\n  error NotEqualSender();\n\n  error ProtocolAccessDenied();\n  error GovernanceAccessDenied();\n  error EmergencyAccessDenied();\n  error RoleAccessDenied();\n  error MarketPriceNotCoverDebt();\n  error StrategyNotEmpty();\n\n  error InvalidDepositCap();\n  error InvalidBorrowCap();\n  error PoolNotActive();\n  error PoolPaused();\n  error PoolFrozen();\n\n  ///////////////////////////////////////////\n  ///   RESERVE CONFIG\n  ///////////////////////////////////////////\n\n  error InvalidReserveFactor();\n  error InvalidMaxBorrowCap();\n  error InvalidMaxDepositCap();\n  error InvalidMaxMinCap();\n  error InvalidMaxDecimals();\n  ///////////////////////////////////////////\n  ///   UTOKEN\n  ///////////////////////////////////////////\n  error UnderlyingMarketNotExist();\n  error UnderlyingMarketAlreadyExist();\n  error UTokenAccessDenied();\n  error ReserveNotActive();\n  error NotValidReserve();\n  ///////////////////////////////////////////\n  ///   ROUTER\n  ///////////////////////////////////////////\n\n  error BaseInputToShort();\n  error ReentrancyLocked();\n  error RevertEmptyBytes();\n  ///////////////////////////////////////////\n  ///   WALLET\n  ///////////////////////////////////////////\n\n  error UnlockdWalletNotFound();\n  error InvalidWalletOwner();\n  error NotEqualWallet();\n  error ProtocolOwnerZeroAddress();\n\n  ///////////////////////////////////////////\n  ///   LOAN\n  ///////////////////////////////////////////\n\n  error HealtyLoan();\n  error UnhealtyLoan();\n  error UnableToBorrowMore();\n  error LoanNotActive();\n  error LowCollateral();\n  error InvalidLoanId();\n  error LoanNotUpdated();\n  error LoanBlocked();\n  error LoanWithDebtRepayed();\n  ///////////////////////////////////////////\n  ///   ORDER\n  ///////////////////////////////////////////\n\n  error OrderNotAllowed();\n  error InvalidOrderId();\n\n  ///////////////////////////////////////////\n  ///   ASSETS\n  ///////////////////////////////////////////\n\n  error InvalidAssetAmount();\n  error InvalidAmount();\n  error AssetLocked();\n  error AssetUnlocked();\n  error LiquidityRateOverflow();\n  error LiquidityIndexOverflow();\n  error BorrorRateOverflow();\n  error BorrowIndexOverflow();\n\n  ///////////////////////////////////////////\n  ///   WRAPPERS\n  ///////////////////////////////////////////\n\n  error TransferNotSupported();\n  error ApproveNotSupported();\n  error SetApprovalForAllNotSupported();\n  error StreamERC20NotSupported();\n  error CallerNotNFTOwner();\n  error StreamCancelable();\n  error StreamNotTransferable();\n  error BurnerNotApproved();\n  error ERC721ReceiverNotSupported();\n\n  error ERC1155AmountNotValid();\n  error ERC1155BatchNotAllowed();\n  error NotWrapperAdapter();\n  error SoldForASmallerAmount();\n\n  function verifyNotZero(address addr) internal pure {\n    if (addr == address(0)) {\n      revert ZeroAddress();\n    }\n  }\n\n  function verifyNotZero(bytes32 key) internal pure {\n    if (key == bytes32(0)) {\n      revert ZeroBytes();\n    }\n  }\n\n  function verifyNotZero(uint256 num) internal pure {\n    if (num == 0) {\n      revert ZeroNumber();\n    }\n  }\n\n  function verifyAreEquals(address ad1, address ad2) internal pure {\n    if (ad1 != ad2) {\n      revert AddressesNotEquals();\n    }\n  }\n\n  function verifyAreEquals(uint256 pa1, uint256 pa2) internal pure {\n    if (pa1 != pa2) {\n      revert NumbersNotEquals();\n    }\n  }\n\n  function verifyNotExpiredTimestamp(uint256 endTimestamp, uint256 nowTimestamp) internal pure {\n    assembly {\n      // if (endTimestamp <= nowTimestamp)\n      if iszero(gt(endTimestamp, nowTimestamp)) {\n        mstore(0x00, 0x26c69d1a) // TimestampExpired() selector\n        revert(0x1c, 0x04)\n      }\n    }\n  }\n\n  function verifyExpiredTimestamp(uint256 endTimestamp, uint256 nowTimestamp) internal pure {\n    assembly {\n      // if (endTimestamp > nowTimestamp)\n      if gt(endTimestamp, nowTimestamp) {\n        mstore(0x00, 0x2499486c) // TimestampNotExpired() selector\n        revert(0x1c, 0x04)\n      }\n    }\n  }\n}\n"
      },
      "src/libraries/logic/GenericLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {IDelegationWalletRegistry} from '@unlockd-wallet/src/interfaces/IDelegationWalletRegistry.sol';\nimport {FixedPointMathLib} from '@solady/utils/FixedPointMathLib.sol';\n\nimport {IProtocolOwner} from '@unlockd-wallet/src/interfaces/IProtocolOwner.sol';\nimport {IReserveOracle} from '../../interfaces/oracles/IReserveOracle.sol';\nimport {IUTokenVault} from '../../interfaces/IUTokenVault.sol';\n\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../../types/DataTypes.sol';\n\n/**\n * @title GenericLogic library\n * @author Unlockd\n * @notice Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using FixedPointMathLib for uint256;\n  // HEALTH FACTOR 1\n  uint256 internal constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;\n  uint256 internal constant FIRST_BID_INCREMENT = 250; // 2.5 %\n  uint256 internal constant NEXT_BID_INCREMENT = 100; // 1 %\n\n  struct CalculateLoanDataVars {\n    uint256 reserveUnitPrice;\n    uint256 reserveUnit;\n    uint256 healthFactor;\n    uint256 totalCollateralInReserve;\n    uint256 totalDebtInReserve;\n    uint256 amount;\n  }\n\n  /**\n   * @dev Calculates the current debt of a specific loand and asset\n   * @param loanId identifier of the loan\n   * @param uTokenVault Current vault\n   * @param underlyingAsset Underlying asset of the debt\n   * @return currentDebt the amount of debt\n   *\n   */\n  function calculateLoanDebt(\n    bytes32 loanId,\n    address uTokenVault,\n    address underlyingAsset\n  ) internal view returns (uint256) {\n    if (loanId == 0) return 0;\n    // fetching variable debt\n    uint256 userTotalDebt = IUTokenVault(uTokenVault).getScaledDebtFromLoanId(\n      underlyingAsset,\n      loanId\n    );\n    return userTotalDebt;\n  }\n\n  /**\n   * @dev Calculates the health factor from the corresponding balances\n   * @param totalCollateral The total collateral\n   * @param totalDebt The total debt\n   * @param liquidationThreshold The avg liquidation threshold\n   * @return healthFactor The health factor calculated from the balances provided\n   *\n   */\n  function calculateHealthFactorFromBalances(\n    uint256 totalCollateral,\n    uint256 totalDebt,\n    uint256 liquidationThreshold\n  ) internal pure returns (uint256 healthFactor) {\n    healthFactor = totalDebt == 0\n      ? type(uint256).max\n      : (totalCollateral.percentMul(liquidationThreshold)).wadDiv(totalDebt);\n  }\n\n  /**\n   * @dev Calculates the equivalent amount that an user can borrow, depending on the available collateral and the\n   * average Loan To Value\n   * @param totalCollateral The total collateral\n   * @param totalDebt The total borrow balance\n   * @param ltv The average loan to value\n   * @return availableBorrows the amount available to borrow for the user\n   *\n   */\n  function calculateAvailableBorrows(\n    uint256 totalCollateral,\n    uint256 totalDebt,\n    uint256 ltv\n  ) internal pure returns (uint256 availableBorrows) {\n    availableBorrows = totalCollateral.percentMul(ltv);\n\n    unchecked {\n      availableBorrows = availableBorrows < totalDebt ? 0 : availableBorrows - totalDebt;\n    }\n  }\n\n  /**\n   * @dev Calculates the amount needed to arrive the LTV, in case of a healty position returns 0\n   * @param totalCollateral The total collateral\n   * @param totalDebt The total borrow balance\n   * @param ltv The average loan to value\n   * @return amountToLtv the amount needed to arrive to LTV\n   */\n  function calculateAmountToArriveToLTV(\n    uint256 totalCollateral,\n    uint256 totalDebt,\n    uint256 ltv\n  ) internal pure returns (uint256 amountToLtv) {\n    uint256 availableBorrows = totalCollateral.percentMul(ltv);\n\n    unchecked {\n      amountToLtv = availableBorrows < totalDebt ? totalDebt - availableBorrows : 0;\n    }\n  }\n\n  /**\n   * @dev Get the abstract wallet information\n   * @param walletRegistry address of the wallet registry\n   * @param owner Owner of the wallet\n   * @return address wallet\n   * @return address protocol owner\n   */\n  function getMainWallet(\n    address walletRegistry,\n    address owner\n  ) internal view returns (address, address) {\n    IDelegationWalletRegistry.Wallet memory wallet = IDelegationWalletRegistry(walletRegistry)\n      .getOwnerWalletAt(owner, 0);\n    return (wallet.wallet, wallet.protocolOwner);\n  }\n\n  /**\n   * @dev Get the wallet adderess of the abstract wallet\n   * @param walletRegistry address of the wallet registry\n   * @param owner Owner of the wallet\n   * @return walletAddress wallet\n   */\n  function getMainWalletAddress(\n    address walletRegistry,\n    address owner\n  ) internal view returns (address walletAddress) {\n    IDelegationWalletRegistry.Wallet memory wallet = IDelegationWalletRegistry(walletRegistry)\n      .getOwnerWalletAt(owner, 0);\n    walletAddress = wallet.wallet;\n  }\n\n  /**\n   * @dev Get the owner adderess of the abstract wallet\n   * @param walletRegistry address of the wallet registry\n   * @param owner Owner of the wallet\n   * @return walletOwner owner\n   */\n  function getMainWalletOwner(\n    address walletRegistry,\n    address owner\n  ) internal view returns (address walletOwner) {\n    IDelegationWalletRegistry.Wallet memory wallet = IDelegationWalletRegistry(walletRegistry)\n      .getOwnerWalletAt(owner, 0);\n    walletOwner = wallet.owner;\n  }\n\n  /**\n   * @dev Get the protocol owner adderess of the abstract wallet\n   * @param walletRegistry address of the wallet registry\n   * @param owner Owner of the wallet\n   * @return walletProtocolOwner protocol owner\n   */\n  function getMainWalletProtocolOwner(\n    address walletRegistry,\n    address owner\n  ) internal view returns (address walletProtocolOwner) {\n    IDelegationWalletRegistry.Wallet memory wallet = IDelegationWalletRegistry(walletRegistry)\n      .getOwnerWalletAt(owner, 0);\n    walletProtocolOwner = wallet.protocolOwner;\n  }\n}\n"
      },
      "src/libraries/logic/OrderLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';\nimport {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\nimport {DataTypes} from '../../types/DataTypes.sol';\nimport {IUTokenVault} from '../../interfaces/IUTokenVault.sol';\nimport {GenericLogic, Errors} from './GenericLogic.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Constants} from '../helpers/Constants.sol';\nimport {MathUtils} from '../math/MathUtils.sol';\n\nlibrary OrderLogic {\n  using SafeERC20 for IERC20;\n  using PercentageMath for uint256;\n\n  event OrderCreated(\n    address indexed owner,\n    bytes32 indexed orderId,\n    bytes32 indexed loanId,\n    Constants.OrderType orderType\n  );\n\n  struct ParamsCreateOrder {\n    Constants.OrderType orderType;\n    address owner;\n    bytes32 orderId;\n    bytes32 loanId;\n    bytes32 assetId;\n    uint128 startAmount;\n    uint128 endAmount;\n    uint128 debtToSell;\n    uint40 startTime;\n    uint40 endTime;\n  }\n\n  /**\n   * @dev generate unique loanId, because the nonce is x address and is incremental it should be unique.\n   * */\n  function generateId(bytes32 assetId, bytes32 loanId) internal pure returns (bytes32) {\n    return keccak256(abi.encodePacked(loanId, assetId));\n  }\n\n  /**\n   * @dev creates a new order\n   * @param order storage of the order\n   * @param params struct with params\n   *  struct ParamsCreateOrder {\n   *    Constants.OrderType orderType;\n   *    address owner;\n   *    bytes32 orderId;\n   *    bytes32 loanId;\n   *    bytes32 assetId;\n   *    uint128 startAmount;\n   *    uint128 endAmount;\n   *    uint128 debtToSell;\n   *    uint40 startTime;\n   *    uint40 endTime;\n   *  }\n   */\n  function createOrder(DataTypes.Order storage order, ParamsCreateOrder memory params) internal {\n    unchecked {\n      order.orderId = params.orderId;\n      order.owner = params.owner;\n      order.orderType = params.orderType;\n      order.offer = DataTypes.OfferItem({\n        loanId: params.loanId,\n        assetId: params.assetId,\n        startAmount: params.startAmount,\n        endAmount: params.endAmount,\n        // debToSell is the % of the final bid or payed that is going to repay debt.\n        debtToSell: params.debtToSell\n      });\n\n      order.timeframe = DataTypes.Timeframe({startTime: params.startTime, endTime: params.endTime});\n    }\n    emit OrderCreated(params.owner, params.orderId, params.loanId, params.orderType);\n  }\n\n  struct ParamsUpdateOrder {\n    bytes32 loanId;\n    bytes32 assetId;\n    uint128 minBid;\n    uint40 endTime;\n  }\n\n  /**\n   * @dev Change the order type to LIQUIDATION_AUCTION\n   * @param order order previously created\n   * @param params data needed to migrate from one order type to other\n   *  struct ParamsUpdateOrder {\n   *     bytes32 loanId;\n   *     bytes32 assetId;\n   *     uint128 minBid;\n   *     uint40 endTime;\n   *  }\n   */\n  function updateToLiquidationOrder(\n    DataTypes.Order storage order,\n    ParamsUpdateOrder memory params\n  ) internal {\n    // Check if the Loan is Unhealty\n    order.orderType = Constants.OrderType.TYPE_LIQUIDATION_AUCTION;\n    // Overwrite offer\n    order.offer = DataTypes.OfferItem({\n      loanId: params.loanId,\n      assetId: params.assetId,\n      startAmount: params.minBid,\n      endAmount: 0,\n      // debToSell is the % of the final bid or payed that is going to repay debt.\n      debtToSell: 1e4\n    });\n\n    order.timeframe = DataTypes.Timeframe({startTime: 0, endTime: params.endTime});\n  }\n\n  struct BorrowByBidderParams {\n    bytes32 loanId;\n    address owner;\n    address to;\n    address underlyingAsset;\n    address uTokenVault;\n    uint256 amountOfDebt;\n    uint256 assetPrice;\n    uint256 assetLtv;\n  }\n\n  /**\n   * @dev Borrow function from bidder\n   * @param params data needed to migrate from one order type to other\n   *  struct BorrowByBidderParams {\n   *    bytes32 loanId;\n   *    address owner;\n   *    address to;\n   *    address underlyingAsset;\n   *    address uTokenVault;\n   *    uint256 amountOfDebt;\n   *    uint256 assetPrice;\n   *    uint256 assetLtv;\n   *  }\n   *\n   */\n  function borrowByBidder(BorrowByBidderParams memory params) internal {\n    if (params.loanId == 0) revert Errors.InvalidLoanId();\n    uint256 maxAmountToBorrow = GenericLogic.calculateAvailableBorrows(\n      params.assetPrice,\n      0,\n      params.assetLtv\n    );\n    if (params.amountOfDebt >= maxAmountToBorrow) {\n      revert Errors.AmountExceedsDebt();\n    }\n    // Borrow on the factory\n    IUTokenVault(params.uTokenVault).borrow(\n      params.underlyingAsset,\n      params.loanId,\n      params.amountOfDebt,\n      params.to,\n      params.owner\n    );\n  }\n\n  struct RepayDebtParams {\n    address owner;\n    address from;\n    address underlyingAsset;\n    address uTokenVault;\n    bytes32 loanId;\n    uint256 amount;\n  }\n\n  /**\n   * @dev Repay specified debt\n   * @param params data needed to migrate from one order type to other\n   *  struct RepayDebtParams {\n   *    address owner;\n   *    address from;\n   *    address underlyingAsset;\n   *    address uTokenVault;\n   *    bytes32 loanId;\n   *    uint256 amount;\n   *  }\n   *\n   */\n  function repayDebt(RepayDebtParams memory params) internal {\n    // Check if there is a loan asociated\n    // We repay the total debt\n    IERC20(params.underlyingAsset).approve(params.uTokenVault, params.amount);\n    // Repay the debt\n    IUTokenVault(params.uTokenVault).repay(\n      params.underlyingAsset,\n      params.loanId,\n      params.amount,\n      params.from,\n      params.owner\n    );\n  }\n\n  struct RefundBidderParams {\n    bytes32 loanId;\n    address owner;\n    address from;\n    address underlyingAsset;\n    address uTokenVault;\n    address reserveOracle;\n    uint256 amountToPay;\n    uint256 amountOfDebt;\n    DataTypes.ReserveData reserve;\n  }\n\n  /**\n   * @dev Refund bidder amount\n   * @param params data needed to migrate from one order type to other\n   *  struct RefundBidderParams {\n   *    bytes32 loanId;\n   *    address owner;\n   *    address from;\n   *    address underlyingAsset;\n   *    address uTokenVault;\n   *    address reserveOracle;\n   *    uint256 amountToPay;\n   *    uint256 amountOfDebt;\n   *    DataTypes.ReserveData reserve;\n   *  }\n   */\n  function refundBidder(RefundBidderParams memory params) internal {\n    uint256 totalAmount = params.amountToPay + params.amountOfDebt;\n    // Check if there is a loan asociated\n\n    if (params.amountOfDebt > 0 && params.loanId != 0) {\n      uint256 currentDebt = GenericLogic.calculateLoanDebt(\n        params.loanId,\n        params.uTokenVault,\n        params.reserve.underlyingAsset\n      );\n      // Check if this loan has currentDebt\n      if (currentDebt > 0) {\n        /**\n          WARNING : If the debt exceeds the total bid amount, we attempt to repay as much as possible. \n          However, in the rare instance where the utilization rate is exceptionally high and borrowing \n          is significantly increased, the debt could surpass the full amount.\n\n          That's why we calculate the total amount of debt that the user is capable of repaying. \n        **/\n        uint256 supportedDebt = MathUtils.minOf(currentDebt, totalAmount);\n        // We remove the current debt\n        totalAmount = totalAmount - supportedDebt;\n\n        repayDebt(\n          RepayDebtParams({\n            loanId: params.loanId,\n            owner: params.owner,\n            from: params.from,\n            amount: supportedDebt,\n            underlyingAsset: params.underlyingAsset,\n            uTokenVault: params.uTokenVault\n          })\n        );\n      }\n    }\n\n    if (totalAmount > 0) {\n      // Return the amount to the first bidder\n      IERC20(params.underlyingAsset).safeTransfer(\n        params.owner,\n        // We return the amount payed minus the interest of the debt\n        totalAmount\n      );\n    }\n  }\n\n  /**\n   * @dev Get the bigger amount between the amount needed to be healty or the amount provided\n   * @param loanId Id from the loan\n   * @param uTokenVault vault address\n   * @param defaultAmount default amount to compare with the debt\n   * @param totalCollateral total amount of collateral of the Loan provided\n   * @param ltv ltv of the asset\n   * @param reserveData reserve data\n   * @return amount Max amount calculated\n   */\n  function getMaxDebtOrDefault(\n    bytes32 loanId,\n    address uTokenVault,\n    uint256 defaultAmount,\n    uint256 totalCollateral,\n    uint256 ltv,\n    DataTypes.ReserveData memory reserveData\n  ) internal view returns (uint256) {\n    uint256 totalDebt = GenericLogic.calculateLoanDebt(\n      loanId,\n      uTokenVault,\n      reserveData.underlyingAsset\n    );\n    if (totalDebt == 0) return defaultAmount;\n    uint256 minAmountNeeded = GenericLogic.calculateAmountToArriveToLTV(\n      totalCollateral,\n      totalDebt,\n      ltv\n    );\n\n    return MathUtils.maxOf(minAmountNeeded, defaultAmount);\n  }\n\n  /**\n   * @dev Get the lower amount between the amount needed to be healty or the amount provided\n   * @param loanId Id from the loan\n   * @param uTokenVault vault address\n   * @param defaultAmount default amount to compare with the debt\n   * @param totalCollateral total amount of collateral of the Loan provided\n   * @param ltv ltv of the asset\n   * @param reserveData reserve data\n   * @return amount lower amount calculated\n   */\n  function getMinDebtOrDefault(\n    bytes32 loanId,\n    address uTokenVault,\n    uint256 defaultAmount,\n    uint256 totalCollateral,\n    uint256 ltv,\n    DataTypes.ReserveData memory reserveData\n  ) internal view returns (uint256) {\n    uint256 totalDebt = GenericLogic.calculateLoanDebt(\n      loanId,\n      uTokenVault,\n      reserveData.underlyingAsset\n    );\n    if (totalDebt < defaultAmount) return totalDebt;\n\n    uint256 minAmountNeeded = GenericLogic.calculateAmountToArriveToLTV(\n      totalCollateral,\n      totalDebt,\n      ltv\n    );\n    return MathUtils.minOf(minAmountNeeded, defaultAmount);\n  }\n\n  /**\n   * @dev Calculate the minimum bid based on the amount of debt to be healty or the startAmount\n   * 0 bids then debt or startAmoun\n   * 1 > bids then debt or lastBid + 1%\n   * @param order current order\n   * @param uTokenVault address of the vault\n   * @param totalCollateral total collateral of the loan\n   * @param ltv ltv of the loan\n   * @return amount Calculation of the min bid\n   * */\n  function getMinBid(\n    DataTypes.Order memory order,\n    address uTokenVault,\n    uint256 totalCollateral,\n    uint256 ltv,\n    DataTypes.ReserveData memory reserveData\n  ) internal view returns (uint256) {\n    if (order.countBids == 0) {\n      return\n        getMaxDebtOrDefault(\n          order.offer.loanId,\n          uTokenVault,\n          order.offer.startAmount,\n          totalCollateral,\n          ltv,\n          reserveData\n        );\n    }\n    uint256 lastBid = order.bid.amountOfDebt + order.bid.amountToPay;\n\n    return\n      getMaxDebtOrDefault(\n        order.offer.loanId,\n        uTokenVault,\n        calculateMinBid(lastBid, order.countBids),\n        totalCollateral,\n        ltv,\n        reserveData\n      );\n  }\n\n  function calculateMinBid(\n    uint256 lastBid,\n    uint256 countBids\n  ) internal pure returns (uint256 minBid) {\n    minBid = countBids == 1\n      ? lastBid + lastBid.percentMul(GenericLogic.FIRST_BID_INCREMENT) // At least 2.5% more than the last bid\n      : lastBid + lastBid.percentMul(GenericLogic.NEXT_BID_INCREMENT); // At least %1 more than the last bid\n  }\n\n  struct RepayDebtToSellParams {\n    address reserveOracle;\n    address underlyingAsset;\n    address uTokenVault;\n    address from;\n    uint256 totalAmount;\n    uint256 aggLoanPrice;\n    uint256 aggLtv;\n  }\n\n  function repayDebtToSell(\n    DataTypes.Order memory order,\n    RepayDebtToSellParams memory params,\n    DataTypes.ReserveData memory reserveData\n  ) internal returns (uint256 totalAmount) {\n    uint256 totalDebt = GenericLogic.calculateLoanDebt(\n      order.offer.loanId,\n      params.uTokenVault,\n      reserveData.underlyingAsset\n    );\n    totalAmount = params.totalAmount;\n\n    if (totalDebt > 0 && order.offer.debtToSell > 0) {\n      uint256 minAmountNeeded = GenericLogic.calculateAmountToArriveToLTV(\n        params.aggLoanPrice,\n        totalDebt,\n        params.aggLtv\n      );\n      // We need to choose between the debt or the % selected by the user to repay.\n      uint256 amounToRepay = MathUtils.maxOf(\n        totalDebt.percentMul(order.offer.debtToSell),\n        minAmountNeeded\n      );\n      if (amounToRepay > 0) {\n        if (amounToRepay > totalAmount) {\n          revert Errors.DebtExceedsAmount();\n        }\n        // Repay the debt\n        repayDebt(\n          RepayDebtParams({\n            loanId: order.offer.loanId,\n            owner: order.owner,\n            from: params.from,\n            amount: amounToRepay,\n            underlyingAsset: params.underlyingAsset,\n            uTokenVault: params.uTokenVault\n          })\n        );\n        // // We remove from the total amount the debt repayed\n        totalAmount = totalAmount - amounToRepay;\n      }\n    }\n  }\n}\n"
      },
      "src/libraries/logic/ReserveLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';\nimport {SafeCast} from '@openzeppelin/contracts/utils/math/SafeCast.sol';\nimport {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\n\nimport {IInterestRate} from '../../interfaces/tokens/IInterestRate.sol';\n\nimport {DelegateCall} from '../utils/DelegateCall.sol';\nimport {MathUtils} from '../math/MathUtils.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes, Constants} from '../../types/DataTypes.sol';\nimport {IStrategy} from '../../interfaces/IStrategy.sol';\nimport {ScaledToken} from '../tokens/ScaledToken.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\n\n/**\n * @title ReserveLogic library\n * @author Unlockd\n * @notice Implements the logic to update the reserves state\n */\nlibrary ReserveLogic {\n  using WadRayMath for uint256;\n  using WadRayMath for uint128;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using SafeERC20 for IERC20;\n  using DelegateCall for address;\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  // See `IPool` for descriptions\n  event ReserveDataUpdated(\n    address indexed underlyingAsset,\n    uint256 liquidityRate,\n    uint256 variableBorrowRate,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex\n  );\n\n  /**\n   * @notice Returns the ongoing normalized income for the reserve.\n   * @dev A value of 1e27 means there is no income. As time passes, the income is accrued\n   * @dev A value of 2*1e27 means for each unit of asset one unit of income has been accrued\n   * @param reserve The reserve object\n   * @return The normalized income, expressed in ray\n   */\n  function getNormalizedIncome(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.liquidityIndex;\n    } else {\n      return\n        MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(\n          reserve.liquidityIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Returns the ongoing normalized variable debt for the reserve.\n   * @dev A value of 1e27 means there is no debt. As time passes, the debt is accrued\n   * @dev A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated\n   * @param reserve The reserve object\n   * @return The normalized variable debt, expressed in ray\n   */\n  function getNormalizedDebt(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.variableBorrowIndex;\n    } else {\n      return\n        MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(\n          reserve.variableBorrowIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Updates the liquidity cumulative index and the variable borrow index.\n   */\n  function updateState(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balance\n  ) internal {\n    // If time didn't pass since last stored timestamp, skip state update\n    //solium-disable-next-line\n    if (reserve.lastUpdateTimestamp == uint40(block.timestamp)) {\n      return;\n    }\n\n    _updateIndexes(reserve, balance);\n    _updateBalances(reserve, balance);\n\n    //solium-disable-next-line\n    reserve.lastUpdateTimestamp = uint40(block.timestamp);\n  }\n\n  function _updateBalances(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balance\n  ) internal {\n    // We calculate the current value based on the current scaled\n    uint256 totalBalance = balance.totalSupplyScaledNotInvested; // + balance.borrow\n    uint256 totalBorrow = balance.totalBorrowScaled;\n    balance.totalSupplyAssets =\n      totalBalance.rayMul(reserve.getNormalizedIncome()).toUint128() +\n      totalBorrow.rayMul(reserve.getNormalizedDebt()).toUint128();\n\n    if (reserve.strategyAddress != address(0)) {\n      balance.totalSupplyAssets += IStrategy(reserve.strategyAddress)\n        .balanceOf(address(this))\n        .toUint128();\n    }\n  }\n\n  /**\n   * @notice Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example\n   * to accumulate the flashloan fee to the reserve, and spread it between all the suppliers.\n   * @param reserve The reserve object\n   * @param totalLiquidity The total liquidity available in the reserve\n   * @param amount The amount to accumulate\n   * @return The next liquidity index of the reserve\n   */\n  function cumulateToLiquidityIndex(\n    DataTypes.ReserveData storage reserve,\n    uint256 totalLiquidity,\n    uint256 amount\n  ) internal returns (uint256) {\n    //next liquidity index is calculated this way: `((amount / totalLiquidity) + 1) * liquidityIndex`\n    //division `amount / totalLiquidity` done in ray for precision\n    uint256 result = (amount.wadToRay().rayDiv(totalLiquidity.wadToRay()) + WadRayMath.RAY).rayMul(\n      reserve.liquidityIndex\n    );\n    reserve.liquidityIndex = result.toUint128();\n    return result;\n  }\n\n  /**\n   * @notice Initializes a reserve.\n   */\n  function init(\n    DataTypes.ReserveData storage reserve,\n    Constants.ReserveType reserveType,\n    address underlyingAsset,\n    address scaledTokenAddress,\n    address interestRateAddress,\n    address strategyAddress,\n    uint8 decimals,\n    uint16 reserveFactor\n  ) internal {\n    reserve.liquidityIndex = uint128(WadRayMath.RAY);\n    reserve.variableBorrowIndex = uint128(WadRayMath.RAY);\n    reserve.scaledTokenAddress = scaledTokenAddress;\n    reserve.interestRateAddress = interestRateAddress;\n    reserve.strategyAddress = strategyAddress;\n    reserve.underlyingAsset = underlyingAsset;\n    reserve.lastUpdateTimestamp = uint40(block.timestamp);\n    // CONFIG\n    DataTypes.ReserveConfigurationMap memory config = reserve.config;\n    config.setReserveFactor(reserveFactor);\n    config.setDecimals(decimals);\n    config.setReserveType(reserveType);\n\n    reserve.config = config;\n  }\n\n  struct UpdateInterestRatesLocalVars {\n    uint256 nextLiquidityRate;\n    uint256 nextVariableRate;\n    uint256 totalVariableDebt;\n  }\n\n  /**\n   * @notice Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate.\n   * @param reserve The reserve reserve to be updated\n   * @param totalBorrowScaled total borrowed scaled\n   * @param totalSupplyAssets total balance\n   * @param liquidityAdded The amount of liquidity added to the protocol (supply or repay) in the previous action\n   * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)\n   */\n  function updateInterestRates(\n    DataTypes.ReserveData storage reserve,\n    uint128 totalBorrowScaled,\n    uint128 totalSupplyAssets,\n    uint256 liquidityAdded,\n    uint256 liquidityTaken\n  ) internal {\n    UpdateInterestRatesLocalVars memory vars;\n\n    vars.totalVariableDebt = totalBorrowScaled.rayMul(reserve.variableBorrowIndex);\n\n    // We calculate the interest rate of all the amount include the current deposited on the strategy\n    (vars.nextLiquidityRate, vars.nextVariableRate) = IInterestRate(reserve.interestRateAddress)\n      .calculateInterestRates(\n        IInterestRate.CalculateInterestRatesParams({\n          liquidityAdded: liquidityAdded,\n          liquidityTaken: liquidityTaken,\n          totalVariableDebt: vars.totalVariableDebt, // Need to be the real not the scaled\n          reserveFactor: reserve.config.getReserveFactor(),\n          totalSupplyAssets: totalSupplyAssets // Need to be the real not the scaled\n        })\n      );\n\n    reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();\n    reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();\n\n    emit ReserveDataUpdated(\n      reserve.underlyingAsset,\n      vars.nextLiquidityRate,\n      vars.nextVariableRate,\n      reserve.liquidityIndex,\n      reserve.variableBorrowIndex\n    );\n  }\n\n  struct AccrueToTreasuryLocalVars {\n    uint256 prevTotalStableDebt;\n    uint256 prevTotalVariableDebt;\n    uint256 currTotalVariableDebt;\n    uint256 cumulatedStableInterest;\n    uint256 totalDebtAccrued;\n    uint256 amountToMint;\n  }\n\n  /**\n   * @notice Updates the reserve indexes and the timestamp of the update.\n   */\n  function _updateIndexes(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balance\n  ) internal {\n    // Only cumulating on the supply side if there is any income being produced\n    // The case of Reserve Factor 100% is not a problem (currentLiquidityRate == 0),\n    // as liquidity index should not be updated\n    if (reserve.currentLiquidityRate != 0) {\n      uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(\n        reserve.currentLiquidityRate,\n        reserve.lastUpdateTimestamp\n      );\n      reserve.liquidityIndex = cumulatedLiquidityInterest\n        .rayMul(reserve.liquidityIndex)\n        .toUint128();\n    }\n\n    if (balance.totalBorrowScaled != 0) {\n      uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(\n        reserve.currentVariableBorrowRate,\n        reserve.lastUpdateTimestamp\n      );\n      reserve.variableBorrowIndex = cumulatedVariableBorrowInterest\n        .rayMul(reserve.variableBorrowIndex)\n        .toUint128();\n    }\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // DEBT\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  function increaseDebt(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balances,\n    uint256 amount\n  ) internal returns (uint256) {\n    uint256 amountScaled = amount.rayDiv(reserve.variableBorrowIndex);\n    if (amountScaled == 0) {\n      revert Errors.InvalidAmount();\n    }\n    balances.totalBorrowScaled += amountScaled.toUint128();\n    balances.totalSupplyScaledNotInvested -= amountScaled.toUint128();\n    // Updates general balances\n    return amountScaled;\n  }\n\n  function decreaseDebt(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balances,\n    uint256 amount\n  ) internal returns (uint256) {\n    uint256 amountScaled = amount.rayDiv(reserve.variableBorrowIndex);\n    if (amountScaled == 0) {\n      revert Errors.InvalidAmount();\n    }\n    // Updates general balances\n    balances.totalBorrowScaled -= amountScaled.toUint128();\n    balances.totalSupplyScaledNotInvested += amountScaled.toUint128();\n\n    return amountScaled;\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // SHARES\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n\n  function mintScaled(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balances,\n    address user,\n    address onBehalfOf,\n    uint256 amount\n  ) internal {\n    IERC20(reserve.underlyingAsset).safeTransferFrom(user, address(this), amount);\n    // MINT SHARES TO THE USER\n    uint256 scaledAmount = ScaledToken(reserve.scaledTokenAddress).mint(\n      onBehalfOf,\n      amount,\n      reserve.liquidityIndex\n    );\n    // calculate the new amounts\n    balances.totalSupplyAssets += amount.toUint128();\n    balances.totalSupplyScaled += scaledAmount.toUint128();\n    balances.totalSupplyScaledNotInvested += scaledAmount.toUint128();\n  }\n\n  function burnScaled(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balances,\n    address user,\n    address to,\n    uint256 amount\n  ) internal {\n    // Check shares\n    uint256 scaledAmount = ScaledToken(reserve.scaledTokenAddress).burn(\n      user,\n      amount,\n      reserve.liquidityIndex\n    );\n\n    balances.totalSupplyAssets -= amount.toUint128();\n    balances.totalSupplyScaled -= scaledAmount.toUint128();\n    balances.totalSupplyScaledNotInvested -= scaledAmount.toUint128();\n    // Transfer the amount to the user\n    IERC20(reserve.underlyingAsset).safeTransfer(to, amount);\n  }\n\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n  // INVEST ON ESTRATEGY\n  /////////////////////////////////////////////////////////////////////////////////////////////////\n\n  function strategyInvest(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balances,\n    uint256 amount\n  ) internal {\n    // If there is no strategy just ignore\n    if (reserve.strategyAddress == address(0)) return;\n\n    uint256 amountToInvest = IStrategy(reserve.strategyAddress).calculateAmountToSupply(\n      balances.totalSupplyScaledNotInvested.rayMul(reserve.getNormalizedIncome()),\n      address(this),\n      amount\n    );\n\n    if (amountToInvest > 0) {\n      IStrategy.StrategyConfig memory config = IStrategy(reserve.strategyAddress).getConfig();\n\n      reserve.strategyAddress.functionDelegateCall(\n        abi.encodeWithSelector(\n          IStrategy.supply.selector,\n          config.vault,\n          config.asset,\n          address(this),\n          amountToInvest\n        )\n      );\n\n      balances.totalSupplyScaledNotInvested -= amountToInvest\n        .rayDiv(reserve.liquidityIndex)\n        .toUint128();\n    }\n  }\n\n  function strategyWithdraw(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balances,\n    uint256 amount\n  ) internal {\n    if (reserve.strategyAddress == address(0)) return;\n    uint256 totalSupplyScaledNotInvested = balances.totalSupplyScaledNotInvested;\n    uint256 totalSupplyNotInvested = totalSupplyScaledNotInvested.rayMul(\n      reserve.getNormalizedIncome()\n    );\n\n    uint256 amountNeed = IStrategy(reserve.strategyAddress).calculateAmountToWithdraw(\n      totalSupplyNotInvested,\n      address(this),\n      amount\n    );\n\n    if (amountNeed > 0) {\n      IStrategy.StrategyConfig memory config = IStrategy(reserve.strategyAddress).getConfig();\n\n      bytes memory returnData = reserve.strategyAddress.functionDelegateCall(\n        abi.encodeWithSelector(IStrategy.withdraw.selector, config.vault, address(this), amountNeed)\n      );\n\n      // Because of the slippage we need to ensure the exact withdraw\n      uint256 amountWithdrawn = abi.decode(returnData, (uint256));\n\n      balances.totalSupplyScaledNotInvested += amountWithdrawn\n        .rayDiv(reserve.liquidityIndex)\n        .toUint128();\n    }\n  }\n\n  function strategyWithdrawAll(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.MarketBalance storage balances\n  ) internal {\n    IStrategy.StrategyConfig memory config = IStrategy(reserve.strategyAddress).getConfig();\n\n    bytes memory returnData = reserve.strategyAddress.functionDelegateCall(\n      abi.encodeWithSelector(\n        IStrategy.withdraw.selector,\n        config.vault,\n        address(this),\n        IStrategy(reserve.strategyAddress).balanceOf(address(this))\n      )\n    );\n\n    // Because of the slippage we need to ensure the exact withdraw\n    uint256 amountWithdrawn = abi.decode(returnData, (uint256));\n\n    balances.totalSupplyScaledNotInvested += amountWithdrawn\n      .rayDiv(reserve.liquidityIndex)\n      .toUint128();\n  }\n}\n"
      },
      "src/libraries/logic/ValidationLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\nimport {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';\nimport {IDelegationWalletRegistry} from '@unlockd-wallet/src/interfaces/IDelegationWalletRegistry.sol';\nimport {IProtocolOwner} from '@unlockd-wallet/src/interfaces/IProtocolOwner.sol';\nimport {AssetLogic} from '@unlockd-wallet/src/libs/logic/AssetLogic.sol';\nimport {IAllowedControllers} from '@unlockd-wallet/src/interfaces/IAllowedControllers.sol';\nimport {Constants} from '../helpers/Constants.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {OrderLogic} from './OrderLogic.sol';\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../../types/DataTypes.sol';\n\nimport {IInterestRate} from '../../interfaces/tokens/IInterestRate.sol';\n\n/**\n * @title ValidationLogic library\n * @author Unlockd\n * @notice Implements functions to validate the different actions of the protocol\n */\nlibrary ValidationLogic {\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  struct ValidateLoanStateParams {\n    uint256 amount;\n    uint256 price;\n    address reserveOracle;\n    address uTokenVault;\n    DataTypes.ReserveData reserve;\n    DataTypes.SignLoanConfig loanConfig;\n  }\n\n  function validateFutureLoanState(ValidateLoanStateParams memory params) internal view {\n    // We always need to define the LTV and the Liquidation threshold\n    if (params.loanConfig.aggLtv == 0 || params.loanConfig.aggLtv > 9999) {\n      revert Errors.InvalidCurrentLtv();\n    }\n    if (\n      params.loanConfig.aggLiquidationThreshold == 0 ||\n      params.loanConfig.aggLiquidationThreshold > 9999 ||\n      params.loanConfig.aggLtv > params.loanConfig.aggLiquidationThreshold\n    ) {\n      revert Errors.InvalidCurrentLiquidationThreshold();\n    }\n    uint256 currentDebt = GenericLogic.calculateLoanDebt(\n      params.loanConfig.loanId,\n      params.uTokenVault,\n      params.reserve.underlyingAsset\n    );\n\n    uint256 updatedDebt = currentDebt < params.amount ? 0 : currentDebt - params.amount;\n\n    // We calculate the current debt and the HF\n    uint256 healthFactor = GenericLogic.calculateHealthFactorFromBalances(\n      params.loanConfig.totalAssets == 0 ? params.price : params.loanConfig.aggLoanPrice,\n      updatedDebt,\n      params.loanConfig.aggLiquidationThreshold\n    );\n\n    if (healthFactor <= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) {\n      revert Errors.UnhealtyLoan();\n    }\n\n    if (params.loanConfig.totalAssets == 0 && updatedDebt > 0) {\n      revert Errors.UnhealtyLoan();\n    }\n  }\n\n  function validateFutureUnhealtyLoanState(ValidateLoanStateParams memory params) internal view {\n    // We always need to define the LTV and the Liquidation threshold\n    if (params.loanConfig.aggLtv == 0 || params.loanConfig.aggLtv > 9999) {\n      revert Errors.InvalidCurrentLtv();\n    }\n    if (\n      params.loanConfig.aggLiquidationThreshold == 0 ||\n      params.loanConfig.aggLiquidationThreshold > 9999 ||\n      params.loanConfig.aggLtv > params.loanConfig.aggLiquidationThreshold\n    ) {\n      revert Errors.InvalidCurrentLiquidationThreshold();\n    }\n\n    uint256 currentDebt = GenericLogic.calculateLoanDebt(\n      params.loanConfig.loanId,\n      params.uTokenVault,\n      params.reserve.underlyingAsset\n    );\n\n    uint256 updatedDebt = currentDebt < params.amount ? 0 : currentDebt - params.amount;\n\n    uint256 healthFactor = GenericLogic.calculateHealthFactorFromBalances(\n      params.loanConfig.totalAssets == 0 ? params.price : params.loanConfig.aggLoanPrice,\n      updatedDebt,\n      params.loanConfig.aggLiquidationThreshold\n    );\n\n    if (healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) {\n      revert Errors.HealtyLoan();\n    }\n\n    if (params.loanConfig.totalAssets == 0 && updatedDebt == 0) {\n      revert Errors.HealtyLoan();\n    }\n  }\n\n  function validateRepay(\n    bytes32 loanId,\n    address uTokenVault,\n    uint256 amount,\n    DataTypes.ReserveData memory reserve\n  ) internal view {\n    // Check allowance to perform the payment to the UToken\n    uint256 loanDebt = GenericLogic.calculateLoanDebt(loanId, uTokenVault, reserve.underlyingAsset);\n\n    if (amount > loanDebt) {\n      revert Errors.AmountExceedsDebt();\n    }\n  }\n\n  ///////////////////////////////////////////////////////\n  // Validation Market Orders\n  ///////////////////////////////////////////////////////\n\n  function validateOrderBid(\n    Constants.OrderType orderType,\n    uint40 orderTimeframeEndtime,\n    uint256 totalAssets,\n    uint88 loanTotalAssets,\n    Constants.LoanState loanState\n  ) internal view {\n    if (\n      orderType == Constants.OrderType.TYPE_FIXED_PRICE ||\n      orderType == Constants.OrderType.TYPE_LIQUIDATION_AUCTION\n    ) {\n      revert Errors.OrderNotAllowed();\n    }\n    if (loanState == Constants.LoanState.BLOCKED) {\n      revert Errors.LoanBlocked();\n    }\n    // Check if the starting time is not in the past\n    Errors.verifyNotExpiredTimestamp(orderTimeframeEndtime, block.timestamp);\n\n    // Check if it is a biddable order\n    if (loanTotalAssets != totalAssets + 1) revert Errors.LoanNotUpdated();\n  }\n\n  function validateBuyNow(\n    uint256 totalAssets,\n    DataTypes.Order memory order,\n    uint88 loanTotalAssets,\n    Constants.LoanState loanState\n  ) internal view {\n    if (\n      order.orderType == Constants.OrderType.TYPE_AUCTION ||\n      order.orderType == Constants.OrderType.TYPE_LIQUIDATION_AUCTION\n    ) {\n      revert Errors.OrderNotAllowed();\n    }\n    if (loanTotalAssets != totalAssets + 1) revert Errors.LoanNotUpdated();\n    if (order.owner == address(0)) revert Errors.InvalidOrderOwner();\n    if (loanState == Constants.LoanState.BLOCKED) {\n      revert Errors.LoanBlocked();\n    }\n    if (order.orderType == Constants.OrderType.TYPE_FIXED_PRICE_AND_AUCTION) {\n      // Check time only for typefixed price\n      Errors.verifyNotExpiredTimestamp(order.timeframe.endTime, block.timestamp);\n    }\n  }\n\n  function validateOrderClaim(\n    uint256 totalAssets,\n    DataTypes.Order memory order,\n    uint88 loanTotalAssets,\n    Constants.LoanState loanState\n  ) internal view {\n    if (\n      order.orderType == Constants.OrderType.TYPE_FIXED_PRICE ||\n      order.orderType == Constants.OrderType.TYPE_LIQUIDATION_AUCTION\n    ) {\n      revert Errors.OrderNotAllowed();\n    }\n    if (order.owner == address(0)) revert Errors.InvalidOrderOwner();\n    if (order.bid.buyer == address(0)) revert Errors.InvalidOrderBuyer();\n\n    // Check if is auction over\n    Errors.verifyExpiredTimestamp(order.timeframe.endTime, block.timestamp);\n    if (loanState == Constants.LoanState.BLOCKED) {\n      revert Errors.LoanBlocked();\n    }\n    if (loanTotalAssets != totalAssets + 1) revert Errors.LoanNotUpdated();\n  }\n\n  struct ValidateCreateOrderMarketParams {\n    Constants.OrderType orderType;\n    Constants.LoanState loanState;\n    uint256 endAmount;\n    uint256 startAmount;\n    uint256 endTime;\n    uint256 startTime;\n    uint256 debtToSell;\n    uint256 currentTimestamp;\n  }\n\n  function validateCreateOrderMarket(ValidateCreateOrderMarketParams memory params) internal pure {\n    if (params.loanState != Constants.LoanState.ACTIVE) {\n      revert Errors.LoanNotActive();\n    }\n    // Check order not liquidation\n    if (params.orderType == Constants.OrderType.TYPE_LIQUIDATION_AUCTION) {\n      revert Errors.OrderNotAllowed();\n    }\n    if (\n      params.orderType == Constants.OrderType.TYPE_FIXED_PRICE ||\n      params.orderType == Constants.OrderType.TYPE_FIXED_PRICE_AND_AUCTION\n    ) {\n      if (params.endAmount == 0) {\n        revert Errors.InvalidEndAmount();\n      }\n      if (params.startAmount == 0) {\n        revert Errors.InvalidStartAmount();\n      }\n      if (params.startAmount > params.endAmount) {\n        revert Errors.InvalidParams();\n      }\n    }\n\n    if (\n      params.orderType == Constants.OrderType.TYPE_AUCTION ||\n      params.orderType == Constants.OrderType.TYPE_FIXED_PRICE_AND_AUCTION\n    ) {\n      if (params.startTime == 0) {\n        revert Errors.InvalidEndTime();\n      }\n      if (params.endTime == 0) {\n        revert Errors.InvalidStartTime();\n      }\n      if (params.startTime > params.endTime || params.currentTimestamp > params.endTime) {\n        revert Errors.InvalidParams();\n      }\n    }\n\n    // Validate value percentage\n    if (params.debtToSell > PercentageMath.ONE_HUNDRED_PERCENT) {\n      revert Errors.InvalidParams();\n    }\n  }\n\n  function validateCancelOrderMarket(\n    address msgSender,\n    Constants.LoanState loanState,\n    address orderOwner,\n    Constants.OrderType orderType,\n    uint40 orderTimeframeEndTime,\n    DataTypes.Bid memory bidData\n  ) internal view {\n    // Only ORDER OWNER\n    if (msgSender != orderOwner) {\n      revert Errors.NotEqualOrderOwner();\n    }\n\n    if (loanState == Constants.LoanState.BLOCKED) {\n      revert Errors.LoanBlocked();\n    }\n\n    if (\n      orderType == Constants.OrderType.TYPE_FIXED_PRICE_AND_AUCTION ||\n      orderType == Constants.OrderType.TYPE_AUCTION\n    ) {\n      // If it's expired and has buyer\n      if (orderTimeframeEndTime < block.timestamp && bidData.buyer != address(0)) {\n        revert Errors.TimestampExpired();\n      }\n    }\n  }\n\n  ///////////////////////////////////////////////////////\n  // Validation Liquidation Order\n  ///////////////////////////////////////////////////////\n\n  function validateBid(\n    uint256 totalAmount,\n    uint256 totalAssets,\n    uint256 minBid,\n    DataTypes.Order memory order,\n    DataTypes.Loan memory loan\n  ) internal view {\n    if (loan.totalAssets != totalAssets + 1) revert Errors.LoanNotUpdated();\n    if (order.orderType != Constants.OrderType.TYPE_LIQUIDATION_AUCTION)\n      revert Errors.OrderNotAllowed();\n\n    Errors.verifyNotExpiredTimestamp(order.timeframe.endTime, block.timestamp);\n    if (totalAmount == 0) revert Errors.InvalidTotalAmount();\n    if (totalAmount < minBid) revert Errors.InvalidBidAmount();\n  }\n\n  ///////////////////////////////////////////////////////\n  // Validation Vault\n  ///////////////////////////////////////////////////////\n\n  function validateVaultDeposit(\n    DataTypes.ReserveData storage reserve,\n    uint256 amount\n  ) internal view {\n    if (reserve.lastUpdateTimestamp == 0) {\n      revert Errors.UnderlyingMarketNotExist();\n    }\n\n    (, uint256 depositCap, uint256 minCap) = reserve.config.getCaps();\n\n    if (depositCap != 0) {\n      uint256 decimals = reserve.config.getDecimals();\n      uint256 depositCap_ = depositCap + 10 ** decimals;\n\n      if (amount <= minCap || amount > depositCap_) {\n        revert Errors.InvalidDepositCap();\n      }\n    }\n\n    (bool isActive, bool isFrozen, ) = reserve.config.getFlags();\n\n    if (!isActive) revert Errors.PoolNotActive();\n    if (isFrozen) revert Errors.PoolFrozen();\n  }\n\n  function validateVaultWithdraw(DataTypes.ReserveData memory reserve) internal pure {\n    if (reserve.lastUpdateTimestamp == 0) {\n      revert Errors.UnderlyingMarketNotExist();\n    }\n\n    (bool isActive, , bool isPaused) = reserve.config.getFlags();\n\n    if (!isActive) revert Errors.PoolNotActive();\n    if (isPaused) revert Errors.PoolPaused();\n  }\n\n  function validateVaultRepay(DataTypes.ReserveData memory reserve) internal pure {\n    if (reserve.lastUpdateTimestamp == 0) {\n      revert Errors.UnderlyingMarketNotExist();\n    }\n\n    (bool isActive, , bool isPaused) = reserve.config.getFlags();\n\n    if (!isActive) revert Errors.PoolNotActive();\n    if (isPaused) revert Errors.PoolPaused();\n  }\n\n  function validateVaultBorrow(DataTypes.ReserveData memory reserve, uint256 amount) internal pure {\n    if (reserve.lastUpdateTimestamp == 0) {\n      revert Errors.UnderlyingMarketNotExist();\n    }\n\n    (uint256 borrowCap, , uint256 minCap) = reserve.config.getCaps();\n\n    if (borrowCap != 0) {\n      uint256 decimals = reserve.config.getDecimals();\n      uint256 borrowCap_ = borrowCap * 10 ** decimals;\n\n      if (amount <= minCap || amount > borrowCap_) {\n        revert Errors.InvalidBorrowCap();\n      }\n    }\n\n    (bool isActive, , bool isPaused) = reserve.config.getFlags();\n\n    if (!isActive) revert Errors.PoolNotActive();\n    if (isPaused) revert Errors.PoolPaused();\n  }\n}\n"
      },
      "src/libraries/math/MathUtils.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport {FixedPointMathLib} from '@solady/utils/FixedPointMathLib.sol';\nimport {WadRayMath} from './WadRayMath.sol';\n\n/**\n * @title MathUtils library\n * @author Unlockd\n * @notice Provides functions to perform linear and compounded interest calculations\n * @dev fork from https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/math/MathUtils.sol\n */\nlibrary MathUtils {\n  using WadRayMath for uint256;\n\n  /// @dev Ignoring leap years\n  uint256 internal constant SECONDS_PER_YEAR = 365 days;\n\n  /**\n   * @dev Function to calculate the interest accumulated using a linear interest rate formula\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return interest The interest rate linearly accumulated during the timeDelta, in ray\n   *\n   */\n\n  function calculateLinearInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    //solium-disable-next-line\n    uint256 result = rate * (block.timestamp - uint256(lastUpdateTimestamp));\n    unchecked {\n      result = result / SECONDS_PER_YEAR;\n    }\n\n    return WadRayMath.RAY + result;\n  }\n\n  /**\n   * @dev Function to calculate the interest using a compounded interest rate formula\n   * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n   *\n   *  (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n   *\n   * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions\n   * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods\n   *\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return compoundedInterest The interest rate compounded during the timeDelta, in ray\n   *\n   */\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp,\n    uint256 currentTimestamp\n  ) internal pure returns (uint256) {\n    //solium-disable-next-line\n    uint256 exp = currentTimestamp - uint256(lastUpdateTimestamp);\n\n    if (exp == 0) {\n      return WadRayMath.RAY;\n    }\n\n    uint256 expMinusOne;\n    uint256 expMinusTwo;\n    uint256 basePowerTwo;\n    uint256 basePowerThree;\n    unchecked {\n      expMinusOne = exp - 1;\n\n      expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n      basePowerTwo = rate.rayMul(rate) / (SECONDS_PER_YEAR * SECONDS_PER_YEAR);\n      basePowerThree = basePowerTwo.rayMul(rate) / SECONDS_PER_YEAR;\n    }\n\n    uint256 secondTerm = exp * expMinusOne * basePowerTwo;\n    unchecked {\n      secondTerm /= 2;\n    }\n    uint256 thirdTerm = exp * expMinusOne * expMinusTwo * basePowerThree;\n    unchecked {\n      thirdTerm /= 6;\n    }\n\n    return WadRayMath.RAY + (rate * exp) / SECONDS_PER_YEAR + secondTerm + thirdTerm;\n  }\n\n  /**\n   * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp\n   * @param rate The interest rate (in ray)\n   * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated\n   *\n   */\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);\n  }\n\n  /**\n   * @dev max between two numbers\n   * @param x number one\n   * @param y number two\n   */\n  function maxOf(uint256 x, uint256 y) internal pure returns (uint256 max) {\n    assembly {\n      max := xor(x, mul(xor(x, y), gt(y, x)))\n    }\n  }\n\n  /**\n   * @dev min between two numbers\n   * @param x number one\n   * @param y number two\n   */\n  function minOf(uint256 x, uint256 y) internal pure returns (uint256 min) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      min := xor(x, mul(xor(x, y), lt(y, x)))\n    }\n  }\n}\n"
      },
      "src/libraries/math/PercentageMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\n/**\n * @title PercentageMath library\n * @author Unlockd\n * @notice Provides functions to perform percentage calculations\n * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n * @dev fork from https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/math/PercentageMath.sol\n */\nlibrary PercentageMath {\n  uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals\n  uint256 constant ONE_HUNDRED_PERCENT = 1e4; //10000, 100%\n  uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4;\n\n  /**\n   * @notice Executes a percentage multiplication\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return result value percentmul percentage\n   */\n  function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage\n    assembly {\n      if iszero(\n        or(\n          iszero(percentage),\n          iszero(gt(value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage)))\n        )\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)\n    }\n  }\n\n  /**\n   * @notice Executes a percentage division\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return result value percentdiv percentage\n   */\n  function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR\n    assembly {\n      if or(\n        iszero(percentage),\n        iszero(iszero(gt(value, div(sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR))))\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage)\n    }\n  }\n}\n"
      },
      "src/libraries/math/WadRayMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\n/**\n * @title WadRayMath library\n * @author Unlockd\n * @notice Provides functions to perform calculations with Wad and Ray units\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers\n * with 27 digits of precision)\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n * @dev fork from https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/math/WadRayMath.sol\n */\nlibrary WadRayMath {\n  // HALF_WAD and HALF_RAY expressed with extended notation as constant with operations are not supported in Yul assembly\n  uint256 internal constant WAD = 1e18;\n  uint256 internal constant HALF_WAD = 0.5e18; // 18\n\n  uint256 internal constant RAY = 1e27;\n  uint256 internal constant HALF_RAY = 0.5e27; // A Ray is a unit with 27 decimals of precision.\n\n  uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n  /**\n   * @return One ray, 1e27\n   *\n   */\n  function ray() internal pure returns (uint256) {\n    return RAY;\n  }\n\n  /**\n   * @return One wad, 1e18\n   *\n   */\n\n  function wad() internal pure returns (uint256) {\n    return WAD;\n  }\n\n  /**\n   * @return Half ray, 1e27/2\n   *\n   */\n  function halfRay() internal pure returns (uint256) {\n    return HALF_RAY;\n  }\n\n  /**\n   * @return Half ray, 1e18/2\n   *\n   */\n  function halfWad() internal pure returns (uint256) {\n    return HALF_WAD;\n  }\n\n  /**\n   * @dev Solady FixedPointMathLib.sol mulWad (Equivalent to `(x * y) / WAD` rounded up.)\n   * @param x Wad\n   * @param y Wad\n   * @return z = x*y, in wad\n   */\n  function wadMul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.\n      if mul(y, gt(x, div(not(0), y))) {\n        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.\n        revert(0x1c, 0x04)\n      }\n      z := div(mul(x, y), WAD)\n    }\n  }\n\n  /**\n   * @dev Solady FixedPointMathLib.sol divWad (Equivalent to `(x * WAD) / y` rounded down.)\n   * @param x Wad\n   * @param y Wad\n   * @return z = z/y, in wad\n   */\n  function wadDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.\n      if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {\n        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.\n        revert(0x1c, 0x04)\n      }\n      z := div(mul(x, WAD), y)\n    }\n  }\n\n  /**\n   * @notice Multiplies two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raymul b\n   */\n  function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b\n    assembly {\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, b), HALF_RAY), RAY)\n    }\n  }\n\n  /**\n   * @notice Divides two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raydiv b\n   */\n  function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - halfB) / RAY\n    assembly {\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, RAY), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @dev Casts ray down to wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @return b = a converted to wad, rounded half up to the nearest wad\n   */\n  function rayToWad(uint256 a) internal pure returns (uint256 b) {\n    assembly {\n      b := div(a, WAD_RAY_RATIO)\n      let remainder := mod(a, WAD_RAY_RATIO)\n      if iszero(lt(remainder, div(WAD_RAY_RATIO, 2))) {\n        b := add(b, 1)\n      }\n    }\n  }\n\n  /**\n   * @dev Converts wad up to ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @return b = a converted in ray\n   */\n  function wadToRay(uint256 a) internal pure returns (uint256 b) {\n    // to avoid overflow, b/WAD_RAY_RATIO == a\n    assembly {\n      b := mul(a, WAD_RAY_RATIO)\n\n      if iszero(eq(div(b, WAD_RAY_RATIO), a)) {\n        revert(0, 0)\n      }\n    }\n  }\n}\n"
      },
      "src/libraries/proxy/UnlockdUpgradeableProxy.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.19;\n\nimport {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';\n\n/**\n * @title Unlockd UnlockdUpgradeableProxy\n * @author Unlockd\n * @notice Proxy ERC1967Proxy\n */\ncontract UnlockdUpgradeableProxy is ERC1967Proxy {\n  constructor(address _implementation, bytes memory _data) ERC1967Proxy(_implementation, _data) {}\n}\n"
      },
      "src/libraries/storage/UVaultStorage.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.19;\n\nimport {DataTypes} from '../../types/DataTypes.sol';\n\n/**\n * @title UVaultStorage\n * @author Unlockd\n * @notice Storage for the Vault\n */\ncontract UVaultStorage {\n  /////////////////////////////////////////\n  //  Configurations\n  /////////////////////////////////////////\n  address internal _sharesTokenImp;\n\n  /////////////////////////////////////////\n  //  Data\n  /////////////////////////////////////////\n  // UnderlyingAsset -> Reserve\n  mapping(address => DataTypes.ReserveData) public reserves;\n  // UnderlyingAsset -> Reserve\n  mapping(address => DataTypes.MarketBalance) public balances;\n\n  /////////////////////////////////////////\n  //  Borrow Balances\n  /////////////////////////////////////////\n\n  mapping(address => mapping(bytes32 => uint256)) internal borrowScaledBalanceByLoanId;\n  mapping(address => mapping(address => uint256)) internal borrowScaledBalanceByUser;\n}\n"
      },
      "src/libraries/tokens/ScaledToken.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {UUPSUpgradeable} from '@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol';\nimport {BaseToken, Errors, DataTypes} from '../base/BaseToken.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\n\n/**\n * @title ScaledToken\n * @author Unlockd\n * @notice Implements a scaled token to track the amount deposited of the user\n */\ncontract ScaledToken is BaseToken, UUPSUpgradeable {\n  using WadRayMath for uint256;\n\n  /**\n   * @dev Initializes the scaled token.\n   * @param aclManager ACLManager aclManager\n   * @param tokenDecimals The decimals of the ScaledToken, same as the underlying asset's\n   * @param tokenName The name of the token\n   * @param tokenSymbol The symbol of the token\n   */\n  function initialize(\n    address aclManager,\n    address uTokenVault,\n    uint8 tokenDecimals,\n    string calldata tokenName,\n    string calldata tokenSymbol\n  ) public initializer {\n    __BaseToken_init(aclManager, uTokenVault, tokenDecimals, tokenName, tokenSymbol);\n  }\n\n  /**\n   * @dev Mints scaled token to the `user` address\n   * -  Only callable by the UToken\n   * @param amount The amount being minted\n   * @param index The variable index of the reserve\n   * @return scaledAmount amount scaled\n   *\n   */\n  function mint(\n    address user,\n    uint256 amount,\n    uint256 index\n  ) external onlyUTokenVault returns (uint256) {\n    // index is expressed in Ray, so:\n    uint256 amountScaled = amount.rayDiv(index);\n    if (amountScaled == 0) {\n      revert Errors.InvalidAmount();\n    }\n    super._mint(user, amountScaled);\n    return amountScaled;\n  }\n\n  /**\n   * @dev Burns user sharedToken\n   * -  Only callable by the UToken\n   * @param user The user whose is getting burned\n   * @param amount The amount getting burned\n   * @param index The variable index of the reserve\n   * @return scaledAmount amount scaled\n   *\n   */\n  function burn(\n    address user,\n    uint256 amount,\n    uint256 index\n  ) external onlyUTokenVault returns (uint256) {\n    uint256 amountScaled = amount.rayDiv(index);\n    if (amountScaled == 0) {\n      revert Errors.InvalidAmount();\n    }\n    super._burn(user, amountScaled);\n    return amountScaled;\n  }\n\n  /**\n   * @notice Checks authorization for UUPS upgrades\n   * @dev Only ACL manager is allowed to upgrade\n   */\n  function _authorizeUpgrade(address) internal override onlyAdmin {}\n}\n"
      },
      "src/libraries/utils/DelegateCall.sol": {
        "content": "// SPDX-License-Identifier: GNU AGPLv3\npragma solidity ^0.8.19;\n\n/**\n * @title DelegateCall\n * @author Unlockd\n * @notice Delegate call library\n * @dev fork from https://github.com/morpho-org/morpho-utils/blob/main/src/DelegateCall.sol\n */\nlibrary DelegateCall {\n  /// ERRORS ///\n\n  /// @notice Thrown when a low delegate call has failed without error message.\n  error LowLevelDelegateCallFailed();\n  bytes4 constant LowLevelDelegateCallFailedError = 0x06f7035e; // bytes4(keccak256(\"LowLevelDelegateCallFailed()\"))\n\n  /// INTERNAL ///\n\n  /// @dev Performs a low-level delegate call to the `_target` contract.\n  /// @dev Note: Unlike the OZ's library this function does not check if the `_target` is a contract. It is the responsibility of the caller to ensure that the `_target` is a contract.\n  /// @param _target The address of the target contract.\n  /// @param _data The data to pass to the function called on the target contract.\n  /// @return returnData The return data from the function called on the target contract.\n  function functionDelegateCall(\n    address _target,\n    bytes memory _data\n  ) internal returns (bytes memory returnData) {\n    assembly {\n      returnData := mload(0x40)\n\n      // The bytes size is found at the bytes pointer memory address - the bytes data is found a slot further.\n      if iszero(delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0)) {\n        // No error is returned, return the custom error.\n        if iszero(returndatasize()) {\n          mstore(returnData, LowLevelDelegateCallFailedError)\n          revert(returnData, 4)\n        }\n\n        // An error is returned and can be logged.\n        returndatacopy(returnData, 0, returndatasize())\n        revert(returnData, returndatasize())\n      }\n\n      // Copy data size and then the returned data to memory.\n      mstore(returnData, returndatasize())\n      let actualDataPtr := add(returnData, 0x20)\n      returndatacopy(actualDataPtr, 0, returndatasize())\n\n      // Update the free memory pointer.\n      mstore(0x40, add(actualDataPtr, returndatasize()))\n    }\n  }\n}\n"
      },
      "src/libraries/utils/tokens/ERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { Initializable } from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/// @notice Simple ERC20 implementation.\n/// @author Turing Consulting\n/// @author Modified from Solady \n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)\n///\n/// @dev Note:\n/// The ERC20 standard allows minting and transferring to and from the zero address,\n/// minting and transferring zero tokens, as well as self-approvals.\n/// For performance, this implementation WILL NOT revert for such actions.\n/// Please add any checks with overrides if desired.\n\ncontract ERC20Upgradeable is Initializable {\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                       CUSTOM ERRORS                        */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The total supply has overflowed.\n    error TotalSupplyOverflow();\n\n    /// @dev The allowance has overflowed.\n    error AllowanceOverflow();\n\n    /// @dev The allowance has underflowed.\n    error AllowanceUnderflow();\n\n    /// @dev Insufficient balance.\n    error InsufficientBalance();\n\n    /// @dev Insufficient allowance.\n    error InsufficientAllowance();\n\n    /// @dev The permit is invalid.\n    error InvalidPermit();\n\n    /// @dev The permit has expired.\n    error PermitExpired();\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                           EVENTS                           */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /// @dev `keccak256(bytes(\"Transfer(address,address,uint256)\"))`.\n    uint256 private constant _TRANSFER_EVENT_SIGNATURE =\n        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;\n\n    /// @dev `keccak256(bytes(\"Approval(address,address,uint256)\"))`.\n    uint256 private constant _APPROVAL_EVENT_SIGNATURE =\n        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                          STORAGE                           */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The storage slot for the total supply.\n    uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;\n\n    /// @dev The balance slot of `owner` is given by:\n    /// ```\n    ///     mstore(0x0c, _BALANCE_SLOT_SEED)\n    ///     mstore(0x00, owner)\n    ///     let balanceSlot := keccak256(0x0c, 0x20)\n    /// ```\n    uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;\n\n    /// @dev The allowance slot of (`owner`, `spender`) is given by:\n    /// ```\n    ///     mstore(0x20, spender)\n    ///     mstore(0x0c, _ALLOWANCE_SLOT_SEED)\n    ///     mstore(0x00, owner)\n    ///     let allowanceSlot := keccak256(0x0c, 0x34)\n    /// ```\n    uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;\n\n    /// @dev The nonce slot of `owner` is given by:\n    /// ```\n    ///     mstore(0x0c, _NONCES_SLOT_SEED)\n    ///     mstore(0x00, owner)\n    ///     let nonceSlot := keccak256(0x0c, 0x20)\n    /// ```\n    uint256 private constant _NONCES_SLOT_SEED = 0x38377508;\n\n    ////////////////////////////////////////////////////////////////\n    ///                     METADATA STORAGE                     ///\n    ////////////////////////////////////////////////////////////////\n\n    string private name_;// added immutable variables to name, symbol, decimals\n\n    string private symbol_;\n\n    // CONTEXT\n\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function __ERC20_init(string calldata _name, string calldata _symbol) internal onlyInitializing {\n        name_ = _name;\n        symbol_ = _symbol;\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                       ERC20 METADATA                       */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Returns the name of the token.\n    function name() public view returns (string memory) {\n        return name_;\n    }\n\n    /// @dev Returns the symbol of the token.\n    function symbol() public view returns (string memory) {\n        return symbol_;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless this function is\n     * overridden;\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                           ERC20                            */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Returns the amount of tokens in existence.\n    function totalSupply() public view virtual returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := sload(_TOTAL_SUPPLY_SLOT)\n        }\n    }\n\n    /// @dev Returns the amount of tokens owned by `owner`.\n    function balanceOf(address owner) public view virtual returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x0c, _BALANCE_SLOT_SEED)\n            mstore(0x00, owner)\n            result := sload(keccak256(0x0c, 0x20))\n        }\n    }\n\n    /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.\n    function allowance(address owner, address spender)\n        public\n        view\n        virtual\n        returns (uint256 result)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x20, spender)\n            mstore(0x0c, _ALLOWANCE_SLOT_SEED)\n            mstore(0x00, owner)\n            result := sload(keccak256(0x0c, 0x34))\n        }\n    }\n\n    /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n    ///\n    /// Emits a {Approval} event.\n    function approve(address spender, uint256 amount) public virtual returns (bool) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Compute the allowance slot and store the amount.\n            mstore(0x20, spender)\n            mstore(0x0c, _ALLOWANCE_SLOT_SEED)\n            mstore(0x00, caller())\n            sstore(keccak256(0x0c, 0x34), amount)\n            // Emit the {Approval} event.\n            mstore(0x00, amount)\n            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))\n        }\n        return true;\n    }\n\n    /// @dev Atomically increases the allowance granted to `spender` by the caller.\n    ///\n    /// Emits a {Approval} event.\n    function increaseAllowance(address spender, uint256 difference) public virtual returns (bool) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Compute the allowance slot and load its value.\n            mstore(0x20, spender)\n            mstore(0x0c, _ALLOWANCE_SLOT_SEED)\n            mstore(0x00, caller())\n            let allowanceSlot := keccak256(0x0c, 0x34)\n            let allowanceBefore := sload(allowanceSlot)\n            // Add to the allowance.\n            let allowanceAfter := add(allowanceBefore, difference)\n            // Revert upon overflow.\n            if lt(allowanceAfter, allowanceBefore) {\n                mstore(0x00, 0xf9067066) // `AllowanceOverflow()`.\n                revert(0x1c, 0x04)\n            }\n            // Store the updated allowance.\n            sstore(allowanceSlot, allowanceAfter)\n            // Emit the {Approval} event.\n            mstore(0x00, allowanceAfter)\n            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))\n        }\n        return true;\n    }\n\n    /// @dev Atomically decreases the allowance granted to `spender` by the caller.\n    ///\n    /// Emits a {Approval} event.\n    function decreaseAllowance(address spender, uint256 difference) public virtual returns (bool) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Compute the allowance slot and load its value.\n            mstore(0x20, spender)\n            mstore(0x0c, _ALLOWANCE_SLOT_SEED)\n            mstore(0x00, caller())\n            let allowanceSlot := keccak256(0x0c, 0x34)\n            let allowanceBefore := sload(allowanceSlot)\n            // Revert if will underflow.\n            if lt(allowanceBefore, difference) {\n                mstore(0x00, 0x8301ab38) // `AllowanceUnderflow()`.\n                revert(0x1c, 0x04)\n            }\n            // Subtract and store the updated allowance.\n            let allowanceAfter := sub(allowanceBefore, difference)\n            sstore(allowanceSlot, allowanceAfter)\n            // Emit the {Approval} event.\n            mstore(0x00, allowanceAfter)\n            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))\n        }\n        return true;\n    }\n\n    /// @dev Transfer `amount` tokens from the caller to `to`.\n    ///\n    /// Requirements:\n    /// - `from` must at least have `amount`.\n    ///\n    /// Emits a {Transfer} event.\n    function transfer(address to, uint256 amount) public virtual returns (bool) {\n        _beforeTokenTransfer(msg.sender, to, amount);\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Compute the balance slot and load its value.\n            mstore(0x0c, _BALANCE_SLOT_SEED)\n            mstore(0x00, caller())\n            let fromBalanceSlot := keccak256(0x0c, 0x20)\n            let fromBalance := sload(fromBalanceSlot)\n            // Revert if insufficient balance.\n            if gt(amount, fromBalance) {\n                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n                revert(0x1c, 0x04)\n            }\n            // Subtract and store the updated balance.\n            sstore(fromBalanceSlot, sub(fromBalance, amount))\n            // Compute the balance slot of `to`.\n            mstore(0x00, to)\n            let toBalanceSlot := keccak256(0x0c, 0x20)\n            // Add and store the updated balance of `to`.\n            // Will not overflow because the sum of all user balances\n            // cannot exceed the maximum uint256 value.\n            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))\n            // Emit the {Transfer} event.\n            mstore(0x20, amount)\n            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))\n        }\n        _afterTokenTransfer(msg.sender, to, amount);\n        return true;\n    }\n\n    /// @dev Transfers `amount` tokens from `from` to `to`.\n    ///\n    /// Note: Does not update the allowance if it is the maximum uint256 value.\n    ///\n    /// Requirements:\n    /// - `from` must at least have `amount`.\n    /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.\n    ///\n    /// Emits a {Transfer} event.\n    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {\n        _beforeTokenTransfer(from, to, amount);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let from_ := shl(96, from)\n            // Compute the allowance slot and load its value.\n            mstore(0x20, caller())\n            mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))\n            let allowanceSlot := keccak256(0x0c, 0x34)\n            let allowance_ := sload(allowanceSlot)\n            // If the allowance is not the maximum uint256 value.\n            if iszero(eq(allowance_, not(0))) {\n                // Revert if the amount to be transferred exceeds the allowance.\n                if gt(amount, allowance_) {\n                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.\n                    revert(0x1c, 0x04)\n                }\n                // Subtract and store the updated allowance.\n                sstore(allowanceSlot, sub(allowance_, amount))\n            }\n            // Compute the balance slot and load its value.\n            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))\n            let fromBalanceSlot := keccak256(0x0c, 0x20)\n            let fromBalance := sload(fromBalanceSlot)\n            // Revert if insufficient balance.\n            if gt(amount, fromBalance) {\n                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n                revert(0x1c, 0x04)\n            }\n            // Subtract and store the updated balance.\n            sstore(fromBalanceSlot, sub(fromBalance, amount))\n            // Compute the balance slot of `to`.\n            mstore(0x00, to)\n            let toBalanceSlot := keccak256(0x0c, 0x20)\n            // Add and store the updated balance of `to`.\n            // Will not overflow because the sum of all user balances\n            // cannot exceed the maximum uint256 value.\n            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))\n            // Emit the {Transfer} event.\n            mstore(0x20, amount)\n            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))\n        }\n        _afterTokenTransfer(from, to, amount);\n        return true;\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                  INTERNAL MINT FUNCTIONS                   */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Mints `amount` tokens to `to`, increasing the total supply.\n    ///\n    /// Emits a {Transfer} event.\n    function _mint(address to, uint256 amount) internal virtual {\n        _beforeTokenTransfer(address(0), to, amount);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)\n            let totalSupplyAfter := add(totalSupplyBefore, amount)\n            // Revert if the total supply overflows.\n            if lt(totalSupplyAfter, totalSupplyBefore) {\n                mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.\n                revert(0x1c, 0x04)\n            }\n            // Store the updated total supply.\n            sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)\n            // Compute the balance slot and load its value.\n            mstore(0x0c, _BALANCE_SLOT_SEED)\n            mstore(0x00, to)\n            let toBalanceSlot := keccak256(0x0c, 0x20)\n            // Add and store the updated balance.\n            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))\n            // Emit the {Transfer} event.\n            mstore(0x20, amount)\n            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))\n        }\n        _afterTokenTransfer(address(0), to, amount);\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                  INTERNAL BURN FUNCTIONS                   */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Burns `amount` tokens from `from`, reducing the total supply.\n    ///\n    /// Emits a {Transfer} event.\n    function _burn(address from, uint256 amount) internal virtual {\n        _beforeTokenTransfer(from, address(0), amount);\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Compute the balance slot and load its value.\n            mstore(0x0c, _BALANCE_SLOT_SEED)\n            mstore(0x00, from)\n            let fromBalanceSlot := keccak256(0x0c, 0x20)\n            let fromBalance := sload(fromBalanceSlot)\n            // Revert if insufficient balance.\n            if gt(amount, fromBalance) {\n                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n                revert(0x1c, 0x04)\n            }\n            // Subtract and store the updated balance.\n            sstore(fromBalanceSlot, sub(fromBalance, amount))\n            // Subtract and store the updated total supply.\n            sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))\n            // Emit the {Transfer} event.\n            mstore(0x00, amount)\n            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)\n        }\n        _afterTokenTransfer(from, address(0), amount);\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                INTERNAL TRANSFER FUNCTIONS                 */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Moves `amount` of tokens from `from` to `to`.\n    function _transfer(address from, address to, uint256 amount) internal virtual {\n        _beforeTokenTransfer(from, to, amount);\n        /// @solidity memory-safe-assembly\n        assembly {\n            let from_ := shl(96, from)\n            // Compute the balance slot and load its value.\n            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))\n            let fromBalanceSlot := keccak256(0x0c, 0x20)\n            let fromBalance := sload(fromBalanceSlot)\n            // Revert if insufficient balance.\n            if gt(amount, fromBalance) {\n                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n                revert(0x1c, 0x04)\n            }\n            // Subtract and store the updated balance.\n            sstore(fromBalanceSlot, sub(fromBalance, amount))\n            // Compute the balance slot of `to`.\n            mstore(0x00, to)\n            let toBalanceSlot := keccak256(0x0c, 0x20)\n            // Add and store the updated balance of `to`.\n            // Will not overflow because the sum of all user balances\n            // cannot exceed the maximum uint256 value.\n            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))\n            // Emit the {Transfer} event.\n            mstore(0x20, amount)\n            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))\n        }\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                INTERNAL ALLOWANCE FUNCTIONS                */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.\n    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Compute the allowance slot and load its value.\n            mstore(0x20, spender)\n            mstore(0x0c, _ALLOWANCE_SLOT_SEED)\n            mstore(0x00, owner)\n            let allowanceSlot := keccak256(0x0c, 0x34)\n            let allowance_ := sload(allowanceSlot)\n            // If the allowance is not the maximum uint256 value.\n            if iszero(eq(allowance_, not(0))) {\n                // Revert if the amount to be transferred exceeds the allowance.\n                if gt(amount, allowance_) {\n                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.\n                    revert(0x1c, 0x04)\n                }\n                // Subtract and store the updated allowance.\n                sstore(allowanceSlot, sub(allowance_, amount))\n            }\n        }\n    }\n\n    /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.\n    ///\n    /// Emits a {Approval} event.\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let owner_ := shl(96, owner)\n            // Compute the allowance slot and store the amount.\n            mstore(0x20, spender)\n            mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))\n            sstore(keccak256(0x0c, 0x34), amount)\n            // Emit the {Approval} event.\n            mstore(0x00, amount)\n            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                     HOOKS TO OVERRIDE                      */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Hook that is called before any transfer of tokens.\n    /// This includes minting and burning.\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n    /// @dev Hook that is called after any transfer of tokens.\n    /// This includes minting and burning.\n    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n}"
      },
      "src/protocol/UTokenVault.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\nimport {SafeCast} from '@openzeppelin/contracts/utils/math/SafeCast.sol';\nimport {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';\nimport {UUPSUpgradeable} from '@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol';\nimport {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol';\nimport {IStrategy} from '../interfaces/IStrategy.sol';\nimport {IACLManager} from '../interfaces/IACLManager.sol';\nimport {IUTokenVault} from '../interfaces/IUTokenVault.sol';\nimport {UVaultStorage} from '../libraries/storage/UVaultStorage.sol';\nimport {BaseEmergency} from '../libraries/base/BaseEmergency.sol';\nimport {MathUtils} from '../libraries/math/MathUtils.sol';\nimport {WadRayMath} from '../libraries/math/WadRayMath.sol';\nimport {PercentageMath} from '../libraries/math/PercentageMath.sol';\nimport {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';\nimport {ValidationLogic} from '../libraries/logic/ValidationLogic.sol';\nimport {ScaledToken} from '../libraries/tokens/ScaledToken.sol';\nimport {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';\nimport {Constants} from '../libraries/helpers/Constants.sol';\nimport {Errors} from '../libraries/helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\nimport {UnlockdUpgradeableProxy} from '../libraries/proxy/UnlockdUpgradeableProxy.sol';\n\n/**\n * @title Unlock Vault\n * @notice Provides functions to interact with the assets\n * @author Unlockd\n */\ncontract UTokenVault is Initializable, UUPSUpgradeable, UVaultStorage, BaseEmergency, IUTokenVault {\n  using ReserveLogic for DataTypes.ReserveData;\n  using SafeERC20 for IERC20;\n  using WadRayMath for uint256;\n  using WadRayMath for uint128;\n  using SafeCast for uint256;\n\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  //////////////////////////////////////////////////////\n\n  modifier onlyProtocol() {\n    if (!IACLManager(_aclManager).isProtocol(msg.sender)) {\n      revert Errors.ProtocolAccessDenied();\n    }\n    _;\n  }\n\n  modifier onlyAdmin() {\n    if (!IACLManager(_aclManager).isUTokenAdmin(msg.sender)) {\n      revert Errors.UTokenAccessDenied();\n    }\n    _;\n  }\n\n  /////////////////////////////////////////////////////\n\n  constructor(address aclManager) BaseEmergency(aclManager) {\n    if (aclManager == address(0)) revert Errors.ZeroAddress();\n    _disableInitializers();\n  }\n\n  function initialize(address sharesTokenImp) public initializer {\n    if (sharesTokenImp == address(0)) revert Errors.ZeroAddress();\n    _sharesTokenImp = sharesTokenImp;\n  }\n\n  /**\n    @notice Create new market\n    @param params IUTokenVault.CreateMarketParams struct to create the reserve\n    struct CreateMarketParams {\n      address interestRateAddress;\n      address strategyAddress;\n      uint16 reserveFactor;\n      address underlyingAsset;\n      Constants.ReserveType reserveType;\n      uint8 decimals;\n      string tokenName;\n      string tokenSymbol;\n    }\n  */\n  function createMarket(IUTokenVault.CreateMarketParams calldata params) external onlyAdmin {\n    if (reserves[params.underlyingAsset].lastUpdateTimestamp != 0) {\n      revert Errors.UnderlyingMarketAlreadyExist();\n    }\n    address sharesToken = _sharesToken(params.decimals, params.tokenName, params.tokenSymbol);\n    // Create Reserve Asset\n    reserves[params.underlyingAsset].init(\n      params.reserveType,\n      params.underlyingAsset,\n      sharesToken,\n      params.interestRateAddress,\n      params.strategyAddress,\n      params.decimals,\n      params.reserveFactor\n    );\n\n    emit MarketCreated(\n      params.underlyingAsset,\n      params.interestRateAddress,\n      params.strategyAddress,\n      sharesToken\n    );\n  }\n\n  /**\n    @notice Withdraw from the vault\n    @param underlyingAsset asset of the vault\n    @param amount amount to deposit\n    @param onBehalfOf address to recive the scaled tokens\n  */\n  function deposit(address underlyingAsset, uint256 amount, address onBehalfOf) external {\n    Errors.verifyNotZero(underlyingAsset);\n    Errors.verifyNotZero(onBehalfOf);\n    Errors.verifyNotZero(amount);\n\n    DataTypes.ReserveData storage reserve = reserves[underlyingAsset];\n    DataTypes.MarketBalance storage balance = balances[underlyingAsset];\n\n    ValidationLogic.validateVaultDeposit(reserve, amount);\n\n    reserve.updateState(balance);\n    reserve.updateInterestRates(balance.totalBorrowScaled, balance.totalSupplyAssets, amount, 0);\n\n    reserve.mintScaled(balance, msg.sender, onBehalfOf, amount);\n\n    reserve.strategyInvest(balance, amount);\n\n    emit Deposit(msg.sender, onBehalfOf, reserve.underlyingAsset, amount);\n  }\n\n  /**\n    @notice Withdraw from the vault\n    @param underlyingAsset asset of the vault\n    @param amount amount to borrow\n    @param to user to send the funds\n  */\n  function withdraw(address underlyingAsset, uint256 amount, address to) external {\n    Errors.verifyNotZero(underlyingAsset);\n    Errors.verifyNotZero(to);\n    Errors.verifyNotZero(amount);\n\n    DataTypes.ReserveData storage reserve = reserves[underlyingAsset];\n\n    DataTypes.MarketBalance storage balance = balances[underlyingAsset];\n\n    ValidationLogic.validateVaultWithdraw(reserve);\n\n    reserve.updateState(balance);\n    reserve.updateInterestRates(balance.totalBorrowScaled, balance.totalSupplyAssets, 0, amount);\n\n    reserve.strategyWithdraw(balance, amount);\n    // Burn scaled tokens\n    reserve.burnScaled(balance, msg.sender, to, amount);\n\n    emit Withdraw(msg.sender, to, reserve.underlyingAsset, amount);\n  }\n\n  /**\n    @notice Borrorw\n    @param underlyingAsset asset of the vault\n    @param loanId loan to asign the debt\n    @param amount amount to borrow\n    @param to user to send the funds\n    @param onBehalfOf address to repay on behalf of other user\n  */\n  function borrow(\n    address underlyingAsset,\n    bytes32 loanId,\n    uint256 amount,\n    address to,\n    address onBehalfOf\n  ) external onlyProtocol {\n    Errors.verifyNotZero(to);\n    Errors.verifyNotZero(amount);\n    Errors.verifyNotZero(onBehalfOf);\n\n    DataTypes.ReserveData storage reserve = reserves[underlyingAsset];\n\n    ValidationLogic.validateVaultBorrow(reserve, amount);\n\n    // Move amount to the pool\n    DataTypes.MarketBalance storage balance = balances[underlyingAsset];\n\n    uint256 availableLiquidity = this.totalAvailableSupply(underlyingAsset);\n    if (amount > availableLiquidity) {\n      revert Errors.NotEnoughLiquidity();\n    }\n\n    // Check if we have enought to withdraw\n    reserve.strategyWithdraw(balance, amount);\n\n    uint256 scaledAmount = reserve.increaseDebt(balance, amount);\n\n    // Update balances\n    borrowScaledBalanceByLoanId[underlyingAsset][loanId] += scaledAmount;\n    borrowScaledBalanceByUser[underlyingAsset][onBehalfOf] += scaledAmount;\n\n    IERC20(underlyingAsset).safeTransfer(to, amount);\n\n    reserve.updateState(balance);\n    // @dev Because we update the debt with increaseDebt, we don't need to pass the current amount into the calculation.\n    reserve.updateInterestRates(balance.totalBorrowScaled, balance.totalSupplyAssets, 0, 0);\n\n    emit Borrow(\n      msg.sender,\n      onBehalfOf,\n      underlyingAsset,\n      amount,\n      loanId,\n      reserve.currentVariableBorrowRate\n    );\n  }\n\n  /**\n    @notice Repay loan \n    @param underlyingAsset asset of the vault\n    @param loanId loanId to repay\n    @param amount amount to repay, if you send uint.max you repay all\n    @param from original user from the loan\n    @param onBehalfOf address to repay on behalf of other user\n  */\n  function repay(\n    address underlyingAsset,\n    bytes32 loanId,\n    uint256 amount,\n    address from,\n    address onBehalfOf\n  ) external onlyProtocol {\n    Errors.verifyNotZero(from);\n    Errors.verifyNotZero(amount);\n    Errors.verifyNotZero(onBehalfOf);\n\n    DataTypes.ReserveData storage reserve = reserves[underlyingAsset];\n\n    ValidationLogic.validateVaultRepay(reserve);\n    // Move amount to the pool\n    DataTypes.MarketBalance storage balance = balances[underlyingAsset];\n\n    uint256 scaledAmount = reserve.decreaseDebt(balance, amount);\n    uint256 currentDebt = borrowScaledBalanceByLoanId[underlyingAsset][loanId];\n\n    // User can't repay more thant the current debt\n    if (currentDebt == 0 || currentDebt < scaledAmount) revert Errors.AmountExceedsDebt();\n    // Update balances\n    borrowScaledBalanceByLoanId[underlyingAsset][loanId] -= scaledAmount;\n    borrowScaledBalanceByUser[underlyingAsset][onBehalfOf] -= scaledAmount;\n\n    IERC20(underlyingAsset).safeTransferFrom(from, address(this), amount);\n\n    reserve.updateState(balance);\n    // @dev Because we update the debt with increaseDebt, we don't need to pass the current amount into the calculation.\n    reserve.updateInterestRates(balance.totalBorrowScaled, balance.totalSupplyAssets, 0, 0);\n\n    reserve.strategyInvest(balance, amount);\n\n    emit Repay(\n      msg.sender,\n      onBehalfOf,\n      underlyingAsset,\n      amount,\n      loanId,\n      reserve.currentVariableBorrowRate\n    );\n  }\n\n  /////////////////////////////////////////////////////////\n  // Update\n  /////////////////////////////////////////////////////////\n\n  /**\n    @notice Update state of the reserve, recalculate index\n    @param underlyingAsset asset of the vault\n  */\n  function updateState(address underlyingAsset) external {\n    reserves[underlyingAsset].updateState(balances[underlyingAsset]);\n  }\n\n  /**\n    @notice Active reserve \n    @param underlyingAsset asset of the vault\n    @param isActive active true/false\n  */\n  function setActive(address underlyingAsset, bool isActive) external onlyEmergencyAdmin {\n    DataTypes.ReserveConfigurationMap memory currentConfig = reserves[underlyingAsset].config;\n    currentConfig.setActive(isActive);\n    reserves[underlyingAsset].config = currentConfig;\n    emit ActiveVault(underlyingAsset, isActive);\n  }\n\n  /**\n    @notice Frozen reserve \n    @param underlyingAsset asset of the vault\n    @param isFrozen frozen true/false\n  */\n  function setFrozen(address underlyingAsset, bool isFrozen) external onlyEmergencyAdmin {\n    DataTypes.ReserveConfigurationMap memory currentConfig = reserves[underlyingAsset].config;\n    currentConfig.setFrozen(isFrozen);\n    reserves[underlyingAsset].config = currentConfig;\n    emit FrozenVault(underlyingAsset, isFrozen);\n  }\n\n  /**\n    @notice Pause or Unpause reserve \n    @param underlyingAsset asset of the vault\n    @param isPaused pause true/false \n  */\n  function setPaused(address underlyingAsset, bool isPaused) external onlyEmergencyAdmin {\n    DataTypes.ReserveConfigurationMap memory currentConfig = reserves[underlyingAsset].config;\n    currentConfig.setPaused(isPaused);\n    reserves[underlyingAsset].config = currentConfig;\n    emit PausedVault(underlyingAsset, isPaused);\n  }\n\n  /**\n    @notice Update caps \n    @param underlyingAsset asset of the vault\n    @param minCap min cap\n    @param depositCap max deposit cap\n    @param borrowCap max borrow cap\n  */\n  function setCaps(\n    address underlyingAsset,\n    uint256 minCap,\n    uint256 depositCap,\n    uint256 borrowCap\n  ) external onlyEmergencyAdmin {\n    DataTypes.ReserveConfigurationMap memory currentConfig = reserves[underlyingAsset].config;\n    currentConfig.setMinCap(minCap);\n    currentConfig.setDepositCap(depositCap);\n    currentConfig.setBorrowCap(borrowCap);\n    reserves[underlyingAsset].config = currentConfig;\n\n    emit UpdateCaps(underlyingAsset, minCap, depositCap, borrowCap);\n  }\n\n  /**\n    @notice Withdraw and disable current strategy\n    @param underlyingAsset asset of the vault\n  */\n  function disableStrategy(address underlyingAsset) external onlyEmergencyAdmin {\n    if (reserves[underlyingAsset].strategyAddress != address(0)) {\n      reserves[underlyingAsset].strategyWithdrawAll(balances[underlyingAsset]);\n      reserves[underlyingAsset].updateState(balances[underlyingAsset]);\n      reserves[underlyingAsset].strategyAddress = address(0);\n      emit DisableReserveStrategy(underlyingAsset);\n    }\n  }\n\n  /**\n    @notice Update strategy on the reserve\n    @param underlyingAsset asset of the vault\n    @param newStrategy address of the new strategy\n  */\n  function updateReserveStrategy(\n    address underlyingAsset,\n    address newStrategy\n  ) external onlyEmergencyAdmin {\n    if (reserves[underlyingAsset].strategyAddress != address(0)) {\n      revert Errors.StrategyNotEmpty();\n    }\n    Errors.verifyNotZero(newStrategy);\n    reserves[underlyingAsset].strategyAddress = newStrategy;\n    emit UpdateReserveStrategy(underlyingAsset, newStrategy);\n  }\n\n  /////////////////////////////////////////////////////////\n  // GET\n  /////////////////////////////////////////////////////////\n\n  /**\n    @notice Validate if the configuration of the reserve allows to interact\n    @param currentReserveType reserve type\n    @param reserveType asset reserve type\n    @return bool true or false \n  */\n  function validateReserveType(\n    Constants.ReserveType currentReserveType,\n    Constants.ReserveType reserveType\n  ) external pure returns (bool) {\n    if (reserveType == Constants.ReserveType.DISABLED) return false;\n    if (currentReserveType == reserveType) return true;\n\n    if (\n      reserveType == Constants.ReserveType.ALL &&\n      currentReserveType != Constants.ReserveType.SPECIAL\n    ) return true;\n\n    return false;\n  }\n\n  /**\n    @notice Return reserve data from the vault\n    @param underlyingAsset asset of the reserve\n    @return reserveData ReserveData struct from the vault\n    struct ReserveData {\n        ReserveConfigurationMap config;\n        uint128 liquidityIndex;\n        uint128 variableBorrowIndex;\n        uint128 currentLiquidityRate;\n        uint128 currentVariableBorrowRate;\n        address underlyingAsset;\n        address scaledTokenAddress;\n        address interestRateAddress;\n        address strategyAddress;\n        uint40 lastUpdateTimestamp;\n    }\n  */\n  function getReserveData(\n    address underlyingAsset\n  ) external view returns (DataTypes.ReserveData memory) {\n    return reserves[underlyingAsset];\n  }\n\n  /**\n    @notice Return scaled token address\n    @param underlyingAsset asset of the reserve\n    @return scaledTokenAddress address of the scaled token\n  */\n  function getScaledToken(address underlyingAsset) external view returns (address) {\n    return reserves[underlyingAsset].scaledTokenAddress;\n  }\n\n  /**\n    @notice Return the current caps of the reserve\n    @param underlyingAsset asset of the reserve\n    @return borrowCap Max amount to borrow\n    @return depositCap Max amount to deposit\n    @return minCap Min amount to deposit and borrow\n     */\n  function getCaps(address underlyingAsset) external view returns (uint256, uint256, uint256) {\n    return reserves[underlyingAsset].config.getCaps();\n  }\n\n  /**\n    @notice Return the current state of the reserve\n    @param underlyingAsset asset of the reserve\n    @return active Reserve is active\n    @return frozen Reserve is frozen\n    @return paused Reserve is paused\n     */\n  function getFlags(address underlyingAsset) external view returns (bool, bool, bool) {\n    return reserves[underlyingAsset].config.getFlags();\n  }\n\n  /**\n    @notice Return decimals configured for the reserve\n    @param underlyingAsset asset of the reserve\n    @return decimals decimals of the reserve\n  */\n  function getDecimals(address underlyingAsset) external view returns (uint256) {\n    return reserves[underlyingAsset].config.getDecimals();\n  }\n\n  /**\n    @notice Return the type of the reserve\n    @param underlyingAsset asset of the reserve\n    @return reserveType reserve type\n  */\n  function getReserveType(address underlyingAsset) external view returns (Constants.ReserveType) {\n    return reserves[underlyingAsset].config.getReserveType();\n  }\n\n  /////////////////////////////////////////////////////////\n  // DEBT\n  /////////////////////////////////////////////////////////\n\n  /**\n    @notice Return scaled total debt market\n    @param underlyingAsset asset of the reserve\n    @return total Total amount scaled\n  */\n  function getScaledTotalDebtMarket(address underlyingAsset) external view returns (uint256) {\n    return\n      balances[underlyingAsset].totalBorrowScaled.rayMul(\n        reserves[underlyingAsset].getNormalizedDebt()\n      );\n  }\n\n  /**\n    @notice Return total debt from user\n    @param underlyingAsset asset of the reserve\n    @param user address from user\n    @return total Total amount \n  */\n  function getTotalDebtFromUser(\n    address underlyingAsset,\n    address user\n  ) external view returns (uint256) {\n    return borrowScaledBalanceByUser[underlyingAsset][user];\n  }\n\n  /**\n    @notice Return scaled total debt from user\n    @param underlyingAsset asset of the reserve\n    @param user address from user\n    @return total Total amount scaled\n  */\n  function getScaledTotalDebtFromUser(\n    address underlyingAsset,\n    address user\n  ) external view returns (uint256) {\n    return\n      borrowScaledBalanceByUser[underlyingAsset][user].rayMul(\n        reserves[underlyingAsset].getNormalizedDebt()\n      );\n  }\n\n  /**\n    @notice Return total debt from loanId\n    @param underlyingAsset asset of the reserve\n    @param loanId loanId assigned \n    @return total Total amount \n  */\n  function getDebtFromLoanId(\n    address underlyingAsset,\n    bytes32 loanId\n  ) external view returns (uint256) {\n    return borrowScaledBalanceByLoanId[underlyingAsset][loanId];\n  }\n\n  /**\n    @notice Return scaled total debt from loanId\n    @param underlyingAsset asset of the reserve\n    @param loanId loanId assigned \n    @return total Total amount scaled\n  */\n  function getScaledDebtFromLoanId(\n    address underlyingAsset,\n    bytes32 loanId\n  ) external view returns (uint256) {\n    return\n      borrowScaledBalanceByLoanId[underlyingAsset][loanId].rayMul(\n        reserves[underlyingAsset].getNormalizedDebt()\n      );\n  }\n\n  /////////////////////////////////////////////////////////\n  // SUPPLY\n  /////////////////////////////////////////////////////////\n\n  /**\n    @notice Return supply struct\n    @param underlyingAsset asset of the reserve\n    @return marketBalance DataTypes.MarketBalance\n    struct MarketBalance {\n        uint128 totalSupplyScaledNotInvested;   \n        uint128 totalSupplyAssets;\n        uint128 totalSupplyScaled;\n        uint128 totalBorrowScaled;\n        uint40 lastUpdateTimestamp;\n    }\n  */\n  function getBalances(\n    address underlyingAsset\n  ) external view returns (DataTypes.MarketBalance memory) {\n    return balances[underlyingAsset];\n  }\n\n  /**\n    @notice Return balance from user\n    @param underlyingAsset asset of the reserve\n    @param user address of the user\n    @return balance balance from user \n  */\n  function getBalanceByUser(address underlyingAsset, address user) external view returns (uint256) {\n    return ScaledToken(reserves[underlyingAsset].scaledTokenAddress).balanceOf(user);\n  }\n\n  /**\n    @notice Return scaled balance from user\n    @param underlyingAsset asset of the reserve\n    @param user address of the user\n    @return balance scaled balance from user \n  */\n  function getScaledBalanceByUser(\n    address underlyingAsset,\n    address user\n  ) external view returns (uint256) {\n    return\n      ScaledToken(reserves[underlyingAsset].scaledTokenAddress).balanceOf(user).rayMul(\n        reserves[underlyingAsset].getNormalizedIncome()\n      );\n  }\n\n  /**\n    @notice Return total supply of the pool\n    @param underlyingAsset asset of the reserve\n    @return totalSupply scaled total supply\n  */\n  function totalSupply(address underlyingAsset) external view returns (uint256) {\n    return\n      balances[underlyingAsset].totalSupplyScaled.rayMul(\n        reserves[underlyingAsset].getNormalizedIncome()\n      );\n  }\n\n  /**\n    @notice Available supply including the invested\n    @param underlyingAsset asset of the reserve\n    @return totalSupply supply \n  */\n  function totalAvailableSupply(address underlyingAsset) external view returns (uint256) {\n    uint256 totalSupplyAssets = IERC20(underlyingAsset).balanceOf(address(this));\n    if (reserves[underlyingAsset].strategyAddress != address(0)) {\n      totalSupplyAssets += IStrategy(reserves[underlyingAsset].strategyAddress).balanceOf(\n        address(this)\n      );\n    }\n    return totalSupplyAssets;\n  }\n\n  /**\n    @notice Available supply not invested in the estrategy\n    @param underlyingAsset asset of the reserve\n    @return totalSupply supply not invested\n  */\n  function totalSupplyNotInvested(address underlyingAsset) external view returns (uint256) {\n    // TotalSupplyNotInvested\n    uint256 balance = balances[underlyingAsset].totalSupplyScaledNotInvested;\n    return balance.rayMul(reserves[underlyingAsset].getNormalizedIncome());\n  }\n\n  /////////////////////////////////////////////////////////\n  // INTERNAL\n  /////////////////////////////////////////////////////////\n\n  function _sharesToken(\n    uint8 decimals,\n    string memory name,\n    string memory symbol\n  ) internal returns (address) {\n    // Deploy shares token\n    bytes memory data = abi.encodeWithSelector(\n      ScaledToken.initialize.selector,\n      _aclManager,\n      address(this),\n      decimals,\n      name,\n      symbol\n    );\n\n    UnlockdUpgradeableProxy scaledTokenProxy = new UnlockdUpgradeableProxy(\n      address(_sharesTokenImp),\n      data\n    );\n\n    return address(scaledTokenProxy);\n  }\n\n  /**\n   * @notice Checks authorization for UUPS upgrades\n   * @dev Only UTokenVault is allowed to upgrade\n   */\n  function _authorizeUpgrade(address) internal override onlyAdmin {}\n}\n"
      },
      "src/types/DataTypes.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\nimport {Constants} from '../libraries/helpers/Constants.sol';\n\n\nlibrary DataTypes {\n\n  ///////////////////////////////////////////////////////\n  // ASSET \n  ///////////////////////////////////////////////////////\n\n  struct MarketBalance {\n  // Total supply invested\n    uint128 totalSupplyScaledNotInvested;   \n    // Total supply\n    uint128 totalSupplyAssets;\n    uint128 totalSupplyScaled;\n    // Total supply borrowed\n    uint128 totalBorrowScaled;\n      // last update\n    uint40 lastUpdateTimestamp;\n  }\n\n  struct ReserveData {\n    ReserveConfigurationMap config;\n    //the liquidity index. Expressed in ray\n    uint128 liquidityIndex;\n    //variable borrow index. Expressed in ray\n    uint128 variableBorrowIndex;\n    //the current supply rate. Expressed in ray\n    uint128 currentLiquidityRate;\n    //the current variable borrow rate. Expressed in ray\n    uint128 currentVariableBorrowRate;\n    // address asset\n    address underlyingAsset;\n    // address scaled token\n    address scaledTokenAddress;\n    //address of the interest rate strategy\n    address interestRateAddress;\n    // address of the strategy\n    address strategyAddress;\n    // last update\n    uint40 lastUpdateTimestamp;\n  }\n  \n  struct ReserveConfigurationMap {\n    //bit 0-15: LTV\n    //bit 16-31: Liq. threshold\n    //bit 32-47: Liq. bonus\n    //bit 48-55: Decimals\n    //bit 56: reserve is active\n    //bit 57: reserve is frozen\n    //bit 58: borrowing is enabled\n    //bit 59: stable rate borrowing enabled\n    //bit 60: asset is paused\n    //bit 61: borrowing in isolation mode is enabled\n    //bit 62: siloed borrowing enabled\n    //bit 63: flashloaning enabled\n    //bit 64-79: reserve factor\n    //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n    //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n    //bit 152-167 liquidation protocol fee\n    //bit 168-175 eMode category\n    //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n    //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n    //bit 252-255 unused\n\n    uint256 data;\n  }\n\n   \n\n  ///////////////////////////////////////////////////////\n  // ORDER \n  ///////////////////////////////////////////////////////\n\n  struct OfferItem {\n    // Slot 0\n    bytes32 loanId;\n    // Slot 1\n    bytes32 assetId;\n    // Slot 2\n    uint128 startAmount;\n    uint128 endAmount; \n    // Slot 3\n    uint128 debtToSell;\n  }  \n\n  struct Timeframe {\n    // Slot 0\n    uint40 startTime;\n    uint40 endTime;\n  }\n\n  struct Bid {\n    // Slot 0\n    bytes32 loanId;\n    // Slot 1\n    address buyer;\n    // Slot 2\n    uint128 amountToPay;\n    uint128 amountOfDebt;\n  }\n\n  struct Order {\n    // Slot 0\n    bytes32 orderId;\n    // Slot 1\n    address owner;\n    Constants.OrderType orderType;\n    uint88 countBids;\n\n    uint256 bidderDebtPayed;\n    uint256 bidderBonus;\n    // Slot 2\n    OfferItem offer;\n    // Slot 3\n    Timeframe timeframe;\n    // Slot 4\n    Bid bid;\n  }\n\n  ///////////////////////////////////////////////////////\n  // LOAN \n  ///////////////////////////////////////////////////////\n\n  struct Loan {\n    // Slot 0\n    bytes32 loanId;\n    // Slot 1\n    uint88 totalAssets;\n    Constants.LoanState state;\n    // Slot 2\n    address underlyingAsset;\n    // Slot 3\n    address owner; \n  }\n\n\n  ///////////////////////////////////////////////////////\n  // Asset\n  ///////////////////////////////////////////////////////\n\n  struct Asset {\n    address collection;\n    uint256 tokenId;\n  }\n \n  ///////////////////////////////////////////////////////\n  // SIGNATURES \n  ///////////////////////////////////////////////////////\n\n  struct EIP712Signature {\n    uint8 v;\n    bytes32 r;\n    bytes32 s;\n    uint256 deadline;\n  }\n\n  struct SignLoanConfig {\n    bytes32 loanId;\n    uint256 aggLoanPrice;\n    uint256 aggLtv;\n    uint256 aggLiquidationThreshold;\n    uint88 totalAssets;\n    uint256 nonce;\n    uint256 deadline;\n  }\n\n  struct SignAsset {\n    bytes32 assetId;\n    address collection;\n    uint256 tokenId;\n    uint256 price;\n    uint256 nonce;\n    uint256 deadline;\n  }\n\n  struct SignBuyNow {\n    SignAsset asset;\n    uint256 assetLtv; // configuration asset\n    uint256 assetLiquidationThreshold; // configuration asset\n    // tx Data\n    address from;\n    address to;\n    bytes data;\n    uint256 value;\n    // Configuration\n    address marketAdapter;\n    address marketApproval; // Approval needed to make the buy\n    uint256 marketPrice; // Market Adapter Price (Reservoir, Opensea ...)\n    address underlyingAsset; // asset needed to buy\n    uint256 nonce;\n    uint256 deadline;\n  }\n\n  struct SignSellNow {\n    SignLoanConfig loan;\n    bytes32 assetId;\n    // approval\n    address marketAdapter;\n    address marketApproval;\n    uint256 marketPrice;\n    address underlyingAsset;\n    // sell data\n    address from;\n    address to;\n    bytes data;\n    uint256 value;\n  \n    // signature\n    uint256 nonce;\n    uint256 deadline;\n  }\n\n  struct SignAction {\n    SignLoanConfig loan;\n    bytes32[] assets;\n    address underlyingAsset;\n    uint256 nonce;\n    uint256 deadline;\n  }\n\n  struct SignMarket {\n    SignLoanConfig loan;\n    bytes32 assetId;\n    address collection;\n    uint256 tokenId;\n    uint256 assetPrice;\n    uint256 assetLtv;\n    uint256 nonce;\n    uint256 deadline;\n  }\n\n  struct SignAuction {\n    SignLoanConfig loan;\n    bytes32[] assets;\n    uint256 assetPrice;\n    uint256 assetLtv;\n    uint40 endTime; // @audit-info review this\n    uint256 nonce;\n    uint256 deadline;\n  }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "forge-std/=lib/forge-std/src/",
        "solady/=lib/solady/src/",
        "@openzeppelin/=lib/openzeppelin-contracts/",
        "@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
        "@chainlink/=lib/chainlink/",
        "@unlockd-wallet/=lib/unlockdv2-wallet/",
        "@solady/=lib/solady/src/",
        "@maxapy/=lib/maxapy/src/",
        "@gnosis.pm/safe-contracts/=lib/unlockdv2-wallet/lib/safe-contracts/",
        "chainlink/=lib/chainlink/",
        "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
        "maxapy/=lib/maxapy/",
        "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "openzeppelin/=lib/openzeppelin-contracts/contracts/",
        "safe-contracts/=lib/unlockdv2-wallet/lib/safe-contracts/contracts/",
        "unlockdv2-wallet/=lib/unlockdv2-wallet/src/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "libraries": {}
    },
    "language": "Solidity"
  }}