creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/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"
      },
      "@openzeppelin/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"
      },
      "@openzeppelin/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"
      },
      "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.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 *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\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 Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\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(\n        address newImplementation,\n        bytes memory data,\n        bool forceCall\n    ) 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(\n        address newImplementation,\n        bytes memory data,\n        bool forceCall\n    ) 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 Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\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 Emitted when the beacon is upgraded.\n     */\n    event BeaconUpgraded(address indexed beacon);\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(\n        address newBeacon,\n        bytes memory data,\n        bool forceCall\n    ) 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"
      },
      "@openzeppelin/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"
      },
      "@openzeppelin/contracts/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (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 * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\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"
      },
      "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/ERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n    mapping(address => uint256) private _balances;\n\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * The default value of {decimals} is 18. To select a different value for\n     * {decimals} you should overload it.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual override 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 override returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address to, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual override returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        uint256 currentAllowance = allowance(owner, spender);\n        require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n     * @dev Moves `amount` of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     */\n    function _transfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {\n        require(from != address(0), \"ERC20: transfer from the zero address\");\n        require(to != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, amount);\n\n        uint256 fromBalance = _balances[from];\n        require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n        unchecked {\n            _balances[from] = fromBalance - amount;\n            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n            // decrementing then incrementing.\n            _balances[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply += amount;\n        unchecked {\n            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n            _balances[account] += amount;\n        }\n        emit Transfer(address(0), account, amount);\n\n        _afterTokenTransfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        uint256 accountBalance = _balances[account];\n        require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n        unchecked {\n            _balances[account] = accountBalance - amount;\n            // Overflow not possible: amount <= accountBalance <= totalSupply.\n            _totalSupply -= amount;\n        }\n\n        emit Transfer(account, address(0), amount);\n\n        _afterTokenTransfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n     *\n     * Does not update the allowance amount in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Might emit an {Approval} event.\n     */\n    function _spendAllowance(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * has been transferred to `to`.\n     * - when `from` is zero, `amount` tokens have been minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface 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    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.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(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-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    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value\n    ) 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(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) 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    function safeIncreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 newAllowance = token.allowance(address(this), spender) + value;\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            uint256 newAllowance = oldAllowance - value;\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n        }\n    }\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        if (returndata.length > 0) {\n            // Return data is optional\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.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     *\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://diligence.consensys.net/posts/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.5.11/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(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/SafeMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)\n\npragma solidity ^0.8.0;\n\n// CAUTION\n// This version of SafeMath should only be used with Solidity 0.8 or later,\n// because it relies on the compiler's built in overflow checks.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations.\n *\n * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler\n * now has built in overflow checking.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a + b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a * b;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator.\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a % b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {trySub}.\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b <= a, errorMessage);\n            return a - b;\n        }\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b > 0, errorMessage);\n            return a / b;\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting with custom message when dividing by zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryMod}.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(\n        uint256 a,\n        uint256 b,\n        string memory errorMessage\n    ) internal pure returns (uint256) {\n        unchecked {\n            require(b > 0, errorMessage);\n            return a % b;\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\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 * ```\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`, and `uint256`._\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    /**\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"
      },
      "contracts/configuration/AddressStorage.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\ncontract AddressStorage {\r\n    mapping(bytes32 => address) private addresses;\r\n\r\n    function getAddress(bytes32 _key) public view returns (address) {\r\n        return addresses[_key];\r\n    }\r\n\r\n    function _setAddress(bytes32 _key, address _value) internal {\r\n        addresses[_key] = _value;\r\n    }\r\n}\r\n"
      },
      "contracts/configuration/LendingPoolAddressesProvider.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\r\nimport \"../proxys/UUPSProxy.sol\";\r\n\r\nimport \"./AddressStorage.sol\";\r\n\r\ncontract LendingPoolAddressesProvider is Ownable, AddressStorage {\r\n\r\n\r\n    bytes32 private constant LENDING_POOL = \"LENDING_POOL\";\r\n    bytes32 private constant LENDING_POOL_CORE = \"LENDING_POOL_CORE\";\r\n    bytes32 private constant LENDING_POOL_CONFIGURATOR = \"LENDING_POOL_CONFIGURATOR\";\r\n    bytes32 private constant LENDING_RATE_ORACLE = \"LENDING_RATE_ORACLE\";\r\n    bytes32 private constant PRICE_ORACLE = \"PRICE_ORACLE\";\r\n    bytes32 private constant FEE_PROVIDER = \"FEE_PROVIDER\";\r\n    bytes32 private constant DATA_PROVIDER = \"DATA_PROVIDER\";\r\n    bytes32 private constant LENDING_POOL_PARAMETERS_PROVIDER = \"PARAMETERS_PROVIDER\";\r\n    bytes32 private constant TOKEN_DISTRIBUTOR = \"TOKEN_DISTRIBUTOR\";\r\n    bytes32 private constant LENDING_POOL_LIQUIDATION_MANAGER = \"LIQUIDATION_MANAGER\";\r\n    bytes32 private constant LENDING_POOL_MANAGER = \"LENDING_POOL_MANAGER\";\r\n\r\n    event proxyCreated(bytes32 id, address indexed newAddress);\r\n    event LendingPoolUpdated(address indexed newAddress);\r\n    event LendingPoolCoreUpdated(address indexed newAddress);\r\n    event LendingPoolConfiguratorUpdated(address indexed newAddress);\r\n    event LendingRateOracleUpdated(address indexed newAddress);\r\n    event PriceOracleUpdated(address indexed newAddress);\r\n    event FeeProviderUpdated(address indexed newAddress);\r\n    event DataProviderUpdated(address indexed newAddress);\r\n    event LendingPoolParametersUpdated(address indexed newAddress);\r\n    event TokenDistributorUpdated(address indexed newAddress);\r\n    event LendingPoolLiquidationManagerUpdated(address indexed newAddress);\r\n    event LendingPoolManagerUpdated(address indexed newAddress);\r\n\r\n    function getLendingPool() public view returns(address) {\r\n        return getAddress(LENDING_POOL);\r\n    }\r\n\r\n    function setLendingPool(address _pool) public onlyOwner {\r\n        updateImplInternal(LENDING_POOL, _pool);\r\n        emit LendingPoolUpdated(_pool);\r\n    }\r\n\r\n    function getLendingPoolCore() public view returns(address) {\r\n        return getAddress(LENDING_POOL_CORE);\r\n    }\r\n\r\n    function setLendingPoolCore(address _core) public onlyOwner {\r\n        updateImplInternal(LENDING_POOL_CORE, _core);\r\n        emit LendingPoolCoreUpdated(_core);\r\n    }\r\n\r\n    function getLendingPoolConfigurator() public view returns(address) {\r\n        return getAddress(LENDING_POOL_CONFIGURATOR);\r\n    }\r\n\r\n    function setLendingPoolConfigurator(address _configurator) public onlyOwner {\r\n        updateImplInternal(LENDING_POOL_CONFIGURATOR, _configurator);\r\n        emit LendingPoolConfiguratorUpdated(_configurator);\r\n    }\r\n\r\n    function setFeeProvider(address _feeProvider) public onlyOwner {\r\n        updateImplInternal(FEE_PROVIDER, _feeProvider);\r\n        emit FeeProviderUpdated(_feeProvider);\r\n    }\r\n\r\n    function getLendingPoolDataProvider() public view returns (address) {\r\n        return getAddress(DATA_PROVIDER);\r\n    }\r\n    \r\n    function setLendingPoolDataProvider(address _dataProvider) public onlyOwner{\r\n        updateImplInternal(DATA_PROVIDER, _dataProvider);\r\n        emit DataProviderUpdated(_dataProvider);\r\n    }\r\n\r\n    function getLendingPoolParametersProvider() public view returns (address) {\r\n        return getAddress(LENDING_POOL_PARAMETERS_PROVIDER);\r\n    }\r\n\r\n    function setLendingPoolParametersProvider(address _parametersProvider) public onlyOwner{\r\n        updateImplInternal(LENDING_POOL_PARAMETERS_PROVIDER, _parametersProvider);\r\n        emit LendingPoolParametersUpdated(_parametersProvider);\r\n    }\r\n\r\n    function getTokenDistributor() public view returns (address) {\r\n        return getAddress(TOKEN_DISTRIBUTOR);\r\n    }\r\n\r\n    function setTokenDistributor(address _distributor) public onlyOwner {\r\n        _setAddress(TOKEN_DISTRIBUTOR, _distributor);\r\n        emit TokenDistributorUpdated(_distributor);\r\n    }\r\n\r\n    function getLendingPoolLiquidationManager() public view returns (address) {\r\n        return getAddress(LENDING_POOL_LIQUIDATION_MANAGER);\r\n    }\r\n\r\n    function setLendingPoolManager(address _lendingPoolManager) public onlyOwner {\r\n        _setAddress(LENDING_POOL_MANAGER, _lendingPoolManager);\r\n        emit LendingPoolManagerUpdated(_lendingPoolManager);\r\n    }\r\n\r\n    function getLendingPoolManager() public view returns (address) {\r\n        return getAddress(LENDING_POOL_MANAGER);\r\n    }\r\n\r\n    function setLendingPoolLiquidationManager(address _liquidationManager) public onlyOwner {\r\n        _setAddress(LENDING_POOL_LIQUIDATION_MANAGER, _liquidationManager);\r\n        emit LendingPoolLiquidationManagerUpdated(_liquidationManager);\r\n    }\r\n\r\n    function getLendingRateOracle() public view returns(address) {\r\n        return getAddress(LENDING_RATE_ORACLE);\r\n    }\r\n\r\n    function setLendingRateOracle(address _rateOracle) public onlyOwner {\r\n        _setAddress(LENDING_RATE_ORACLE, _rateOracle);\r\n        emit LendingRateOracleUpdated(_rateOracle);\r\n    } \r\n\r\n    function getPriceOracle() public view returns (address) {\r\n        return getAddress(PRICE_ORACLE);\r\n    }\r\n\r\n    function setPriceOracle(address _priceOracle) public onlyOwner {\r\n        _setAddress(PRICE_ORACLE, _priceOracle);\r\n        emit PriceOracleUpdated(_priceOracle);\r\n    }\r\n\r\n    function getFeeProvider() public view returns (address) {\r\n        return getAddress(FEE_PROVIDER);\r\n    }\r\n\r\n    function updateImplInternal(bytes32 id, address newImpl) internal {\r\n        address payable proxyAddress = payable(getAddress(id));\r\n\r\n        if(proxyAddress == address(0)) {\r\n            UUPSProxy proxy = new UUPSProxy(newImpl);\r\n            _setAddress(id, address(proxy));\r\n            emit proxyCreated(id, address(proxy));\r\n        } else {\r\n            UUPSProxy proxy = UUPSProxy(proxyAddress);\r\n            proxy.updateImpl(newImpl);\r\n        }\r\n    }\r\n}"
      },
      "contracts/configuration/LendingPoolParametersProvider.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\ncontract LendingPoolParametersProvider {\r\n\r\n    uint256 private constant MAX_STABLE_RATE_BORROW_SIZE_PERCENT = 25;\r\n    uint256 private constant REBALANCE_DOWN_RATE_DELTA = (1e27)/5;\r\n\r\n    function getMaxStableRateBorrowSizePercent() external pure returns (uint256) {\r\n        return MAX_STABLE_RATE_BORROW_SIZE_PERCENT;\r\n    }\r\n\r\n    function getRebalanceDownRateDelta() external pure returns (uint256) {\r\n        return REBALANCE_DOWN_RATE_DELTA;\r\n    }  \r\n\r\n}"
      },
      "contracts/interfaces/IFeeProvider.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\ninterface IFeeProvider {\r\n    function calculateLoanOriginationFee(address _user, uint256 _amount) external view returns (uint256);\r\n    function getLoanOriginationFeePercentage() external view returns (uint256);\r\n}"
      },
      "contracts/interfaces/ILendingRateOracle.sol": {
        "content": "pragma solidity ^0.8.9;\r\n\r\ninterface ILendingRateOracle {\r\n    function getMarketBorrowRate(address _asset) external view returns (uint256);\r\n\r\n    function setMarketBorrowRate(address _asset, uint256 _rate) external;\r\n}"
      },
      "contracts/interfaces/IPriceOracleGetter.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\ninterface IPriceOracleGetter {\r\n    function getAssetPrice(address _asset) external view returns (uint256);\r\n}"
      },
      "contracts/interfaces/IReserveInterestRateStrategy.sol": {
        "content": "pragma solidity ^0.8.9;\r\n\r\ninterface IReserveInterestRateStrategy {\r\n    function getBaseVariableBorrowRate() external view returns (uint256);\r\n\r\n    function calculateInterestRates(\r\n        address _reserve,\r\n        uint256 _availableLiquidity,//@note: _utilizationRate\r\n        uint256 _totalBorrowsStable,\r\n        uint256 _totalBorrowsVariable,\r\n        uint256 _averageStableBorrowRate\r\n    ) external view returns (\r\n        uint256 currentLiquidityRate,//@note: liquidityRate\r\n        uint256 currentStableBorrowRate,//@note: stableBorrowRate\r\n        uint256 currentVariableBorrowRate//@note: variableBorrowRate\r\n    );\r\n\r\n}"
      },
      "contracts/lendingpool/DefaultReserveInterestRateStrategy.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\nimport \"../interfaces/IReserveInterestRateStrategy.sol\";\r\nimport \"../libraries/WadRayMath.sol\";\r\nimport \"../configuration/LendingPoolAddressesProvider.sol\";\r\nimport \"./LendingPoolCore.sol\";\r\nimport \"../interfaces/ILendingRateOracle.sol\";\r\n\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\n\r\ncontract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy {\r\n    using WadRayMath for uint256;\r\n    using SafeMath for uint256;\r\n\r\n    /**\r\n    * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates\r\n    * expressed in ray\r\n    **/\r\n    uint256 public constant OPTIMAL_UTILIZATION_RATE = 0.8 * 1e27;\r\n\r\n    /**\r\n    * @dev this constant represents the excess utilization rate above the optimal. It's always equal to\r\n    * 1-optimal utilization rate. Added as a constant here for gas optimizations\r\n    * expressed in ray\r\n    **/\r\n    uint256 public constant EXCESS_UTILIZATION_RATE = 0.2 * 1e27;\r\n\r\n    LendingPoolAddressesProvider public addressesProvider;\r\n\r\n    //base variable borrow rate when Utilization rate = 0. Expressed in ray\r\n    uint256 public baseVariableBorrowRate;\r\n\r\n    //slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray\r\n    uint256 public variableRateSlope1;\r\n\r\n    //slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray\r\n    uint256 public variableRateSlope2;\r\n\r\n    //slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray\r\n    uint256 public stableRateSlope1;\r\n\r\n    //slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray\r\n    uint256 public stableRateSlope2;\r\n\r\n    address reserve;\r\n\r\n    constructor(\r\n        address _reserve,\r\n        LendingPoolAddressesProvider _provider,\r\n        uint256 _baseVariableBorrowRate,\r\n        uint256 _variableRateSlope1,\r\n        uint256 _variableRateSlope2,\r\n        uint256 _stableRateSlope1,\r\n        uint256 _stableRateSlope2\r\n    ) {\r\n        addressesProvider = _provider;\r\n        baseVariableBorrowRate = _baseVariableBorrowRate;\r\n        variableRateSlope1 = _variableRateSlope1;\r\n        variableRateSlope2 = _variableRateSlope2;\r\n        stableRateSlope1 = _stableRateSlope1;\r\n        stableRateSlope2 = _stableRateSlope2;\r\n        reserve = _reserve;\r\n    }\r\n\r\n    function getBaseVariableBorrowRate() external view returns (uint256) {\r\n        return baseVariableBorrowRate;\r\n    }\r\n\r\n    function getVariableRateSlope1() external view returns (uint256) {\r\n        return variableRateSlope1;\r\n    }\r\n\r\n    function getVariableRateSlope2() external view returns (uint256) {\r\n        return variableRateSlope2;\r\n    }\r\n\r\n    function getStableRateSlope1() external view returns (uint256) {\r\n        return stableRateSlope1;\r\n    }\r\n\r\n    function getStableRateSlope2() external view returns (uint256) {\r\n        return stableRateSlope2;\r\n    }\r\n\r\n    function calculateInterestRates(\r\n        address _reserve,\r\n        uint256 _availableLiquidity,\r\n        uint256 _totalBorrowsStable,\r\n        uint256 _totalBorrowsVariable,\r\n        uint256 _averageStableBorrowRate\r\n    ) external view returns (\r\n        uint256 currentLiquidityRate,\r\n        uint256 currentStableBorrowRate,\r\n        uint256 currentVariableBorrowRate\r\n    ) {\r\n        uint256 totalBorrows = _totalBorrowsStable.add(_totalBorrowsVariable);\r\n\r\n        uint256 utilizationRate = (totalBorrows == 0 && _availableLiquidity == 0)\r\n            ? 0\r\n            : totalBorrows.rayDiv(_availableLiquidity.add(totalBorrows));\r\n        \r\n        currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle())\r\n            .getMarketBorrowRate(_reserve);\r\n\r\n        if(utilizationRate > OPTIMAL_UTILIZATION_RATE) {\r\n            uint256 excessUtilizationRateRatio = utilizationRate\r\n                .sub(OPTIMAL_UTILIZATION_RATE)\r\n                .rayDiv(EXCESS_UTILIZATION_RATE);\r\n            \r\n            currentStableBorrowRate = currentStableBorrowRate\r\n                .add(stableRateSlope1)\r\n                .add(stableRateSlope2.rayMul(excessUtilizationRateRatio));\r\n            \r\n            currentVariableBorrowRate = baseVariableBorrowRate\r\n                .add(variableRateSlope1)\r\n                .add(variableRateSlope2.rayMul(excessUtilizationRateRatio));\r\n        } else {\r\n            currentStableBorrowRate = currentStableBorrowRate\r\n                .add(stableRateSlope1\r\n                        .rayMul(utilizationRate.rayDiv(\r\n                            OPTIMAL_UTILIZATION_RATE\r\n                        )));\r\n            \r\n            currentVariableBorrowRate = baseVariableBorrowRate.add(utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE).rayMul(variableRateSlope1));\r\n        }\r\n\r\n        currentLiquidityRate = getOverallBorrowRateInternal(\r\n            _totalBorrowsStable, \r\n            _totalBorrowsVariable, \r\n            currentVariableBorrowRate, \r\n            _averageStableBorrowRate\r\n        ).rayMul(utilizationRate);\r\n    }\r\n\r\n    function getOverallBorrowRateInternal(\r\n        uint256 _totalBorrowsStable,\r\n        uint256 _totalBorrowsVariable,\r\n        uint256 _currentVariableBorrowRate,\r\n        uint256 _currentAverageStableBorrowRate\r\n    ) internal pure returns (uint256) {\r\n        uint256 totalBorrows = _totalBorrowsStable.add(_totalBorrowsVariable);\r\n\r\n        if(totalBorrows == 0) return 0;\r\n\r\n        uint256 weightedVariableRate = _totalBorrowsVariable.wadToRay().rayMul(_currentVariableBorrowRate);\r\n\r\n        uint256 weightedStableRate = _totalBorrowsStable.wadToRay().rayMul(_currentAverageStableBorrowRate);\r\n\r\n        uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalBorrows.wadToRay());\r\n\r\n        return overallBorrowRate;\r\n    }\r\n}"
      },
      "contracts/lendingpool/LendingPool.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\nimport \"@openzeppelin/contracts/utils/Address.sol\";\r\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\r\n// import \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\r\nimport \"../proxys/InitializableWithSlot.sol\";\r\n\r\nimport \"../configuration/LendingPoolAddressesProvider.sol\";\r\nimport \"../configuration/LendingPoolParametersProvider.sol\";\r\nimport \"../tokenization/MToken.sol\";\r\nimport \"../libraries/CoreLibrary.sol\";\r\nimport \"../libraries/WadRayMath.sol\";\r\nimport \"../libraries/EthAddressLib.sol\";\r\nimport \"../interfaces/IFeeProvider.sol\";\r\nimport \"./LendingPoolCore.sol\";\r\nimport \"./LendingPoolLiquidationManager.sol\";\r\nimport \"./LendingPoolDataProvider.sol\";\r\n\r\ncontract LendingPool is ReentrancyGuard, InitializableWithSlot {\r\n    using SafeMath for uint256;\r\n    using WadRayMath for uint256;\r\n    using Address for address;\r\n\r\n    LendingPoolAddressesProvider public addressesProvider;\r\n    LendingPoolCore public core;\r\n    LendingPoolDataProvider public dataProvider;\r\n    LendingPoolParametersProvider public parametersProvider;\r\n    IFeeProvider feeProvider;\r\n\r\n    event Deposit(\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _amount,\r\n        uint16 indexed _referral,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    event RedeemUnderlying(\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _amount,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    event Borrow(\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _amount,\r\n        uint256 _borrowRateMode,\r\n        uint256 _borrowRate,\r\n        uint256 _originationFee,\r\n        uint256 _borrowBalanceIncrease,\r\n        uint16 indexed _referral,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    event Repay(\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        address indexed _repayer,\r\n        uint256 _amountMinusFees,\r\n        uint256 _fees,\r\n        uint256 _borrowBalanceIncrease,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    event Swap(\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _newRateMode,\r\n        uint256 _newRate,\r\n        uint256 _borrowBalanceIncrease,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    event ReserveUsedAsCollateralEnabled(address indexed _reserve, address indexed _user);\r\n\r\n    event ReserveUsedAsCollateralDisabled(address indexed _reserve, address indexed _user);\r\n\r\n    event RebalanceStableBorrowRate(\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _newStableRate,\r\n        uint256 _borrowBalanceIncrease,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    //@notice: event FlashLoan\r\n\r\n    event OriginationFeeLiquidated(\r\n        address indexed _collateral,\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _feeLiquidated,\r\n        uint256 _liquidatedCollateralForFee,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    event LiquidationCall(\r\n        address indexed _collateral,\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _purchaseAmount,\r\n        uint256 _liquidatedCollateralAmount,\r\n        uint256 _accruedBorrowInterest,\r\n        address _liquidator,\r\n        bool _receiveMToken,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    modifier onlyOverlyingMToken(address _reserve) {\r\n        require(\r\n            msg.sender == core.getReserveMTokenAddress(_reserve),\r\n            \"The caller of this function can only be the mToken contract of this reserve\"\r\n        );\r\n        _;\r\n    }\r\n\r\n    modifier onlyActiveReserve(address _reserve) {\r\n        requireReserveActiveInternal(_reserve);\r\n        _;\r\n    }\r\n\r\n    modifier onlyUnfreezedReserve(address _reserve) {\r\n        requireReserveNotFreezedInternal(_reserve);\r\n        _;\r\n    }\r\n\r\n    modifier onlyAmountGreaterThanZero(uint256 _amount) {\r\n        requireAmountGreaterThanZeroInternal(_amount);\r\n        _;\r\n    }\r\n\r\n    uint256 public constant UINT_MAX_VALUE = type(uint256).max;\r\n\r\n    function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {\r\n        addressesProvider = _addressesProvider;\r\n        core = LendingPoolCore(payable(addressesProvider.getLendingPoolCore()));\r\n        dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());\r\n        parametersProvider = LendingPoolParametersProvider(addressesProvider.getLendingPoolParametersProvider());\r\n        feeProvider = IFeeProvider(addressesProvider.getFeeProvider());\r\n    }\r\n\r\n\r\n    \r\n    function deposit(address _reserve, uint256 _amount, uint16 _referralCode)\r\n        external\r\n        payable\r\n        nonReentrant\r\n        onlyActiveReserve(_reserve)\r\n        onlyUnfreezedReserve(_reserve)\r\n        onlyAmountGreaterThanZero(_amount)\r\n    {\r\n        MToken mToken = MToken(core.getReserveMTokenAddress(_reserve));\r\n\r\n        bool isFirstDeposit = mToken.balanceOf(msg.sender) == 0;\r\n\r\n        core.updateStateOnDeposit(_reserve, msg.sender, _amount, isFirstDeposit);\r\n\r\n        mToken.mintOnDeposit(msg.sender, _amount);\r\n\r\n        core.transferToReserve{value: msg.value}(_reserve, payable(msg.sender), _amount);\r\n\r\n        emit Deposit(_reserve, msg.sender, _amount, _referralCode, block.timestamp);\r\n\r\n    }\r\n\r\n    function redeemUnderlying(\r\n        address _reserve,\r\n        address payable _user,\r\n        uint256 _amount,\r\n        uint256 _mTokenBalanceAfterRedeem\r\n    ) \r\n        external \r\n        nonReentrant \r\n        onlyOverlyingMToken(_reserve)\r\n        onlyActiveReserve(_reserve)\r\n        onlyAmountGreaterThanZero(_amount)\r\n    {\r\n        uint256 currentAvailableLiquidity = core.getReserveAvailableLiquidity(_reserve);\r\n        require(\r\n            currentAvailableLiquidity >= _amount,\r\n            \"There is not enough liquidity available to redeem\"\r\n        );\r\n\r\n        core.updateStateOnRedeem(_reserve, _user, _amount, _mTokenBalanceAfterRedeem == 0);\r\n\r\n        core.transferToUser(_reserve, _user, _amount);\r\n\r\n        emit RedeemUnderlying(_reserve, _user, _amount, block.timestamp);\r\n    }\r\n\r\n    struct BorrowLocalVars {\r\n        uint256 principalBorrowBalance;\r\n        uint256 currentLtv;\r\n        uint256 currentLiquidationThreshold;\r\n        uint256 borrowFee;\r\n        uint256 requestedBorrowAmountETH;\r\n        uint256 amountOfCollateralNeededETH;\r\n        uint256 userCollateralBalanceETH;\r\n        uint256 userBorrowBalanceETH;\r\n        uint256 userTotalFeesETH;\r\n        uint256 borrowBalanceIncrease;\r\n        uint256 currentReserveStableRate;\r\n        uint256 availableLiquidity;\r\n        uint256 reserveDecimals;\r\n        uint256 finalUserBorrowRate;\r\n        CoreLibrary.InterestRateMode rateMode;\r\n        bool healthFactorBelowThreshold;\r\n    }\r\n\r\n    function borrow(\r\n        address _reserve,\r\n        uint256 _amount,\r\n        uint256 _interestRateMode,\r\n        uint16 _referralCode\r\n    )\r\n        external\r\n        nonReentrant\r\n        onlyActiveReserve(_reserve)\r\n        onlyUnfreezedReserve(_reserve)\r\n        onlyAmountGreaterThanZero(_amount)\r\n    {\r\n        BorrowLocalVars memory vars;\r\n\r\n        require(core.isReserveBorrowingEnabled(_reserve), \"Reserve is not enable for borrowing\");\r\n\r\n        require(\r\n            uint256(CoreLibrary.InterestRateMode.VARIABLE) == _interestRateMode ||\r\n            uint256(CoreLibrary.InterestRateMode.STABLE) == _interestRateMode,\r\n            \"Invalid interest rate mode selected\"\r\n        );\r\n\r\n        vars.rateMode = CoreLibrary.InterestRateMode(_interestRateMode);\r\n\r\n        vars.availableLiquidity = core.getReserveAvailableLiquidity(_reserve);\r\n\r\n        require(vars.availableLiquidity >= _amount, \"There is not enough liquidity available in the reserve\");\r\n\r\n        (\r\n            ,\r\n            vars.userCollateralBalanceETH,\r\n            vars.userBorrowBalanceETH,\r\n            vars.userTotalFeesETH,\r\n            vars.currentLtv,\r\n            vars.currentLiquidationThreshold,\r\n            ,\r\n            vars.healthFactorBelowThreshold\r\n        ) = dataProvider.calculateUserGlobalData(msg.sender);\r\n\r\n        require(vars.userCollateralBalanceETH > 0, \"The collateral balance is 0\");\r\n\r\n        require(!vars.healthFactorBelowThreshold, \"The borrower can already be liquidated so he cannot borrow more\");\r\n\r\n        //calculating fees\r\n        vars.borrowFee = feeProvider.calculateLoanOriginationFee(msg.sender, _amount);\r\n        \r\n        require(vars.borrowFee > 0, \"The amount to borrow is too small\");\r\n\r\n        vars.amountOfCollateralNeededETH = dataProvider.calculateCollateralNeededInETH(\r\n            _reserve,\r\n            _amount,\r\n            vars.borrowFee,\r\n            vars.userBorrowBalanceETH,\r\n            vars.userTotalFeesETH,\r\n            vars.currentLtv\r\n        );\r\n\r\n        require(\r\n            vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,\r\n            \"There is not enough collateral to cover a new borrow\"\r\n        );\r\n\r\n        if(vars.rateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            require(\r\n                core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, _amount),\r\n                \"User cannot borrow the selected amount with a stable rate\"\r\n            );\r\n\r\n            uint256 maxLoanPercent = parametersProvider.getMaxStableRateBorrowSizePercent();\r\n            uint256 maxLoanSizeStable = vars.availableLiquidity.mul(maxLoanPercent).div(100);\r\n\r\n            require(\r\n                _amount <= maxLoanSizeStable,\r\n                \"User is trying to borrow too much liquidity at a stable rate\"\r\n            );\r\n        }\r\n\r\n        (vars.finalUserBorrowRate, vars.borrowBalanceIncrease) = core.updateStateOnBorrow(\r\n            _reserve,\r\n            msg.sender,\r\n            _amount,\r\n            vars.borrowFee,\r\n            vars.rateMode\r\n        );\r\n\r\n        core.transferToUser(_reserve, payable(msg.sender), _amount);\r\n\r\n        emit Borrow(\r\n            _reserve,\r\n            msg.sender,\r\n            _amount,\r\n            _interestRateMode,\r\n            vars.finalUserBorrowRate,\r\n            vars.borrowFee,\r\n            vars.borrowBalanceIncrease,\r\n            _referralCode,\r\n            //solium-disable-next-line\r\n            block.timestamp\r\n        );\r\n    }\r\n\r\n    struct RepayLocalVars {\r\n        uint256 principalBorrowBalance;\r\n        uint256 compoundedBorrowBalance;\r\n        uint256 borrowBalanceIncrease;\r\n        bool isETH;\r\n        uint256 paybackAmount;\r\n        uint256 paybackAmountMinusFees;\r\n        uint256 currentStableRate;\r\n        uint256 originationFee;\r\n    }\r\n\r\n    function repay(address _reserve, uint256 _amount, address payable _onBehalfOf)\r\n        external\r\n        payable \r\n        nonReentrant \r\n        onlyActiveReserve(_reserve)\r\n        onlyAmountGreaterThanZero(_amount)\r\n    {\r\n\r\n        RepayLocalVars memory vars;\r\n        uint256 feeValue;\r\n\r\n        (\r\n            vars.principalBorrowBalance,\r\n            vars.compoundedBorrowBalance,\r\n            vars.borrowBalanceIncrease\r\n        ) = core.getUserBorrowBalances(_reserve, _onBehalfOf);\r\n\r\n        vars.originationFee = core.getUserOriginationFee(_reserve, _onBehalfOf);\r\n        vars.isETH = EthAddressLib.ethAddress() == _reserve;\r\n\r\n        require(vars.compoundedBorrowBalance > 0, \"The user does not have any borrow pending\");\r\n\r\n        require(\r\n            _amount != UINT_MAX_VALUE || msg.sender == _onBehalfOf,\r\n            \"To repay on behalf of an user an explicit amount to repay is needed\"\r\n        );\r\n\r\n        //default to max amount\r\n        vars.paybackAmount = vars.compoundedBorrowBalance.add(vars.originationFee);\r\n\r\n        if(_amount != UINT_MAX_VALUE && _amount < vars.paybackAmount) {\r\n            vars.paybackAmount = _amount;\r\n        }\r\n\r\n        require(\r\n            !vars.isETH || msg.value >= vars.paybackAmount,\r\n            \"Invalid msg.value sent for the repayment\"\r\n        );\r\n\r\n        //if the amount is smaller than the origination fee, just transfer the amount to the fee destination address\r\n        if(vars.paybackAmount <= vars.originationFee) {\r\n            core.updateStateOnRepay(\r\n                _reserve,\r\n                _onBehalfOf,\r\n                0,\r\n                vars.paybackAmount,\r\n                vars.borrowBalanceIncrease,\r\n                false\r\n            );\r\n\r\n            feeValue = vars.isETH ? vars.paybackAmount : 0;\r\n\r\n            core.transferToFeeCollectionAddress{value: feeValue}(\r\n                _reserve, \r\n                _onBehalfOf, \r\n                vars.paybackAmount, \r\n                addressesProvider.getTokenDistributor()\r\n            );\r\n\r\n            emit Repay(\r\n                _reserve,\r\n                _onBehalfOf,\r\n                msg.sender,\r\n                0,\r\n                vars.paybackAmount,\r\n                vars.borrowBalanceIncrease,\r\n                //solium-disable-next-line\r\n                block.timestamp\r\n            );\r\n            return;\r\n        }\r\n\r\n        vars.paybackAmountMinusFees = vars.paybackAmount.sub(vars.originationFee);\r\n\r\n        core.updateStateOnRepay(\r\n            _reserve,\r\n            _onBehalfOf,\r\n            vars.paybackAmountMinusFees,\r\n            vars.originationFee,\r\n            vars.borrowBalanceIncrease,\r\n            vars.compoundedBorrowBalance == vars.paybackAmountMinusFees\r\n        );\r\n\r\n        //if the user didn't repay the origination fee, transfer the fee to the fee collection address\r\n        if(vars.originationFee > 0) {\r\n            feeValue = vars.isETH ? vars.originationFee : 0;\r\n\r\n            core.transferToFeeCollectionAddress{value: feeValue}(\r\n                _reserve,\r\n                msg.sender,\r\n                vars.originationFee,\r\n                addressesProvider.getTokenDistributor()\r\n            );\r\n        }\r\n        //sending the total msg.value if the transfer is ETH.\r\n        //the transferToReserve() function will take care of sending the\r\n        //excess ETH back to the caller\r\n        feeValue = vars.isETH ? msg.value.sub(vars.originationFee) : 0;\r\n        core.transferToReserve{value: feeValue}(_reserve, payable(msg.sender), vars.paybackAmountMinusFees);\r\n\r\n        emit Repay(\r\n            _reserve,\r\n            _onBehalfOf,\r\n            msg.sender,\r\n            vars.paybackAmountMinusFees,\r\n            vars.originationFee,\r\n            vars.borrowBalanceIncrease,\r\n            //solium-disable-next-line\r\n            block.timestamp\r\n        );\r\n    }\r\n\r\n    function swapBorrowRateMode(address _reserve) \r\n        external\r\n        nonReentrant\r\n        onlyActiveReserve(_reserve)\r\n        onlyUnfreezedReserve(_reserve)\r\n    {\r\n        (uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core\r\n            .getUserBorrowBalances(_reserve, msg.sender);\r\n\r\n        require(compoundedBorrowBalance > 0, \"User does not have a borrow in progress on this reserve\");\r\n\r\n        CoreLibrary.InterestRateMode currentRateMode = core.getUserCurrentBorrowRateMode(_reserve, msg.sender);\r\n\r\n        if(currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {\r\n            /**\r\n            * user wants to swap to stable, before swapping we need to ensure that\r\n            * 1. stable borrow rate is enabled on the reserve\r\n            * 2. user is not trying to abuse the reserve by depositing\r\n            * more collateral than he is borrowing, artificially lowering\r\n            * the interest rate, borrowing at variable, and switching to stable\r\n            **/\r\n            require(\r\n                core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, compoundedBorrowBalance),\r\n                \"User cannot borrow the selected amount at stable\"\r\n            );\r\n        }\r\n\r\n        (CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core\r\n            .updateStateOnSwapRate(\r\n                _reserve,\r\n                msg.sender,\r\n                principalBorrowBalance,\r\n                compoundedBorrowBalance,\r\n                borrowBalanceIncrease,\r\n                currentRateMode\r\n            );\r\n        \r\n        emit Swap(\r\n            _reserve,\r\n            msg.sender,\r\n            uint256(newRateMode),\r\n            newBorrowRate,\r\n            borrowBalanceIncrease,\r\n            //solium-disable-next-line\r\n            block.timestamp\r\n        );\r\n    }\r\n\r\n    //@todo:rebalanceStableBorrowRate\r\n    function rebalanceStableBorrowRate(address _reserve, address _user)\r\n        external\r\n        nonReentrant\r\n        onlyActiveReserve(_reserve)\r\n    {\r\n        (\r\n            ,\r\n            uint256 compoundedBalance,\r\n            uint256 borrowBalanceIncrease\r\n        ) = core.getUserBorrowBalances(_reserve, _user);\r\n\r\n        //step 1: user must be borrowing on _reserve at a stable rate\r\n        require(compoundedBalance > 0, \"User does not have any borrow for this reserve\");\r\n\r\n        require(\r\n            core.getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.STABLE,\r\n            \"The user borrow is variable and cannot be rebalanced\"\r\n        );\r\n\r\n        uint256 userCurrentStableRate = core.getUserCurrentStableBorrowRate(_reserve, _user);\r\n        uint256 liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);\r\n        uint256 reserveCurrentStableRate = core.getReserveCurrentStableBorrowRate(_reserve);\r\n        uint256 rebalanceDownRateThreshold = reserveCurrentStableRate\r\n            .rayMul(\r\n                WadRayMath.ray().add(parametersProvider.getRebalanceDownRateDelta())\r\n            );\r\n        \r\n        //step 2: we have two possible situations to rebalance:\r\n\r\n        //1. user stable borrow rate is below the current liquidity rate. The loan needs to be rebalanced,\r\n        //as this situation can be abused (user putting back the borrowed liquidity in the same reserve to earn on it)\r\n        //2. user stable rate is above the market avg borrow rate of a certain delta, and utilization rate is low.\r\n        //In this case, the user is paying an interest that is too high, and needs to be rescaled down.\r\n        if(\r\n            userCurrentStableRate < liquidityRate ||\r\n            userCurrentStableRate > rebalanceDownRateThreshold\r\n        ) {\r\n            uint256 newStableRate = core.updateStateOnRebalance(\r\n                _reserve,\r\n                _user,\r\n                borrowBalanceIncrease\r\n            );\r\n\r\n            emit RebalanceStableBorrowRate(\r\n                _reserve,\r\n                _user,\r\n                newStableRate,\r\n                borrowBalanceIncrease,\r\n                //solium-disable-next-line\r\n                block.timestamp\r\n            );\r\n\r\n            return ;\r\n        }\r\n\r\n        revert(\"Interest rate rebalance conditions were not met\");\r\n    }\r\n\r\n    function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral)\r\n        external\r\n        nonReentrant\r\n        onlyActiveReserve(_reserve)\r\n        onlyUnfreezedReserve(_reserve)\r\n    {\r\n        uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender);\r\n\r\n        require(underlyingBalance > 0, \"User does not have any liquidity deposited\");\r\n\r\n        require(\r\n            dataProvider.balanceDecreaseAllowed(_reserve, msg.sender, underlyingBalance),\r\n            \"User deposit is already being used as collateral\"\r\n        );\r\n\r\n        core.setUserUseReserveAsCollateral(_reserve, msg.sender, _useAsCollateral);\r\n\r\n        if(_useAsCollateral) {\r\n            emit ReserveUsedAsCollateralEnabled(_reserve, msg.sender);\r\n        } else {\r\n            emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender);\r\n        }\r\n    }\r\n\r\n    function liquidationCall(\r\n        address _collateral,\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _purchaseAmount,\r\n        bool _receiveMToken\r\n    ) \r\n        external \r\n        payable \r\n        nonReentrant \r\n        onlyActiveReserve(_reserve) \r\n        onlyActiveReserve(_collateral)\r\n    {\r\n        address liquidationManager = addressesProvider.getLendingPoolLiquidationManager();\r\n\r\n        (\r\n            bool success,\r\n            bytes memory result \r\n        ) = liquidationManager.delegatecall(\r\n            abi.encodeWithSignature(\r\n                \"liquidationCall(address,address,address,uint256,bool)\", \r\n                _collateral,\r\n                _reserve,\r\n                _user,\r\n                _purchaseAmount,\r\n                _receiveMToken\r\n            )\r\n        );\r\n        require(success, \"Liquidation call failed\");\r\n\r\n        (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));\r\n\r\n        if(returnCode != 0) {\r\n            revert(string(abi.encodePacked(\"Liquidation failed: \", returnMessage)));\r\n        }\r\n    }\r\n\r\n    //@todo: function flashLoan\r\n\r\n    function getReserveConfigurationData(address _reserve)\r\n        external\r\n        view\r\n        returns(\r\n            uint256 ltv,\r\n            uint256 liquidationThreshold,\r\n            uint256 liquidationBonus,\r\n            address interestRateStrategyAddress,\r\n            bool usageAsCollateralEnabled,\r\n            bool borrowingEnabled,\r\n            bool stableBorrowRateEnabled,\r\n            bool isActive\r\n        )\r\n    {\r\n        return dataProvider.getReserveConfigurationData(_reserve);\r\n    }\r\n\r\n    function getReserveData(address _reserve)\r\n        external\r\n        view\r\n        returns (\r\n            LendingPoolDataProvider.Reserve memory\r\n        )\r\n    {\r\n        return dataProvider.getReserveData(_reserve);\r\n    }\r\n\r\n    function getUserAccountData(address _user)\r\n        external\r\n        view\r\n        returns (\r\n            uint256 totalLiquidityETH,\r\n            uint256 totalCollateralETH,\r\n            uint256 totalBorrowsETH,\r\n            uint256 totalFeesETH,\r\n            uint256 availableBorrowsETH,\r\n            uint256 currentLiquidationThreshold,\r\n            uint256 ltv,\r\n            uint256 healthFactor\r\n        )\r\n    {\r\n        return dataProvider.getUserAccountData(_user);\r\n    }\r\n\r\n    function getUserReserveData(address _reserve, address _user)\r\n        external\r\n        view\r\n        returns (\r\n            uint256 currentMTokenBalance,\r\n            uint256 currentBorrowBalance,\r\n            uint256 principalBorrowBalance,\r\n            uint256 borrowRateMode,\r\n            uint256 borrowRate,\r\n            uint256 liquidityRate,\r\n            uint256 originationFee,\r\n            uint256 variableBorrowIndex,\r\n            uint256 lastUpdateTimestamp,\r\n            bool usageAsCollateralEnabled\r\n        )\r\n    {\r\n        return dataProvider.getUserReserveData(_reserve, _user);\r\n    }\r\n\r\n    function getReserves() external view returns (address[] memory) {\r\n        return core.getReserves();\r\n    }\r\n\r\n    function requireReserveActiveInternal(address _reserve) internal view {\r\n        require(core.getReserveIsActive(_reserve), \"Action requires an active reserve\");\r\n    }\r\n\r\n    function requireReserveNotFreezedInternal(address _reserve) internal view {\r\n        require(!core.getReserveIsFreezed(_reserve), \"Action requires an unfreezed reserve\");\r\n    }\r\n\r\n    function requireAmountGreaterThanZeroInternal(uint256 _amount) internal pure {\r\n        require(_amount > 0, \"Amount must greater than 0\");\r\n    }\r\n}\r\n"
      },
      "contracts/lendingpool/LendingPoolCore.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\r\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\r\nimport \"@openzeppelin/contracts/utils/Address.sol\";\r\nimport \"../proxys/InitializableWithSlot.sol\";\r\n\r\nimport \"../libraries/CoreLibrary.sol\";\r\nimport \"../libraries/EthAddressLib.sol\";\r\nimport \"../libraries/WadRayMath.sol\";\r\nimport \"../configuration/LendingPoolAddressesProvider.sol\";\r\nimport \"../tokenization/MToken.sol\";\r\nimport \"../interfaces/ILendingRateOracle.sol\";\r\nimport \"../interfaces/IReserveInterestRateStrategy.sol\";\r\n\r\ncontract LendingPoolCore is InitializableWithSlot {\r\n    using WadRayMath for uint256;\r\n    using SafeMath for uint256;\r\n    using CoreLibrary for CoreLibrary.ReserveData;\r\n    using CoreLibrary for CoreLibrary.UserReserveData;\r\n    using SafeERC20 for ERC20;\r\n    using Address for address payable;\r\n\r\n    event ReserveUpdate(\r\n        address indexed reserve,\r\n        uint256 liquidityRate,\r\n        uint256 stableBorrowRate,\r\n        uint256 variableBorrowRate,\r\n        uint256 liquidtyIndex,\r\n        uint256 variableBorrowIndex\r\n    );\r\n    \r\n    address public lendingPoolAddress;\r\n\r\n    LendingPoolAddressesProvider public addressesProvider;\r\n\r\n    modifier onlyLendingPool {\r\n        require(lendingPoolAddress == msg.sender, \"The caller must be a lending pool contract\");\r\n        _;\r\n    }\r\n\r\n    modifier onlyLendingPoolConfigurator {\r\n        require(\r\n            addressesProvider.getLendingPoolConfigurator() == msg.sender,\r\n            \"The caller must be a lending pool configurator contract\"\r\n        );\r\n        _;\r\n    }\r\n\r\n    mapping(address => CoreLibrary.ReserveData) internal reserves;\r\n    mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData;\r\n\r\n    address[] public reservesList;\r\n\r\n    function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {\r\n        addressesProvider = _addressesProvider;\r\n    }\r\n\r\n    function updateStateOnDeposit(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _amount,\r\n        bool _isFirstDeposit\r\n    ) external onlyLendingPool {\r\n        reserves[_reserve].updateCumulativeIndexes();\r\n        updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0);\r\n\r\n        if(_isFirstDeposit) {\r\n            setUserUseReserveAsCollateral(_reserve, _user, true);\r\n        }\r\n    }\r\n\r\n    function updateStateOnRedeem(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _amountRedeemed,\r\n        bool _userRedeemedEverything\r\n    ) external onlyLendingPool {\r\n        reserves[_reserve].updateCumulativeIndexes();\r\n        updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed);\r\n\r\n        if(_userRedeemedEverything) {\r\n            setUserUseReserveAsCollateral(_reserve, _user, false);\r\n        }\r\n    }\r\n\r\n    function updateStateOnBorrow(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _amountBorrowed,\r\n        uint256 _borrowFee,\r\n        CoreLibrary.InterestRateMode _rateMode\r\n    ) external onlyLendingPool returns(uint256, uint256) {\r\n        (\r\n            uint256 principalBorrowBalance,\r\n            ,\r\n            uint256 balanceIncrease\r\n        ) = getUserBorrowBalances(_reserve, _user);\r\n\r\n        \r\n        updateReserveStateOnBorrowInternal(\r\n            _reserve,\r\n            _user,\r\n            principalBorrowBalance,\r\n            balanceIncrease,\r\n            _amountBorrowed,\r\n            _rateMode\r\n        );\r\n\r\n        updateUserStateOnBorrowInternal(\r\n            _reserve,\r\n            _user,\r\n            _amountBorrowed,\r\n            balanceIncrease,\r\n            _borrowFee,\r\n            _rateMode\r\n        );\r\n        updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed);\r\n\r\n        return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease);\r\n    }\r\n\r\n    function updateStateOnRepay (\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _paybackAmountMinusFees,\r\n        uint256 _originationFeeRepaid,\r\n        uint256 _balanceIncrease,\r\n        bool _repaidWholeLoan\r\n    ) external onlyLendingPool {\r\n        updateReserveStateOnRepayInternal(\r\n            _reserve,\r\n            _user,\r\n            _paybackAmountMinusFees,\r\n            _balanceIncrease\r\n        );\r\n        updateUserStateOnRepayInternal(\r\n            _reserve,\r\n            _user,\r\n            _paybackAmountMinusFees,\r\n            _originationFeeRepaid,\r\n            _balanceIncrease,\r\n            _repaidWholeLoan\r\n        );\r\n\r\n        updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0);\r\n    }\r\n\r\n    function updateStateOnSwapRate(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _principalBorrowBalance,\r\n        uint256 _compoundedBorrowBalance,\r\n        uint256 _balanceIncrease,\r\n        CoreLibrary.InterestRateMode _currentRateMode\r\n    ) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) {\r\n        updateReserveStateOnSwapRateInternal(\r\n            _reserve,\r\n            _user,\r\n            _principalBorrowBalance,\r\n            _compoundedBorrowBalance,\r\n            _currentRateMode\r\n        );\r\n\r\n        CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal(\r\n            _reserve,\r\n            _user,\r\n            _balanceIncrease,\r\n            _currentRateMode\r\n        );\r\n\r\n        updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);\r\n\r\n        return (newRateMode, getUserCurrentBorrowRate(_reserve, _user));\r\n    }\r\n\r\n    function updateStateOnLiquidation(\r\n        address _principalReserve,\r\n        address _collateralReserve,\r\n        address _user,\r\n        uint256 _amountToLiquidate,\r\n        uint256 _collateralToLiquidate,\r\n        uint256 _feeLiquidated,\r\n        uint256 _liquidatedCollateralForFee,\r\n        uint256 _balanceIncrease,\r\n        bool _liquidatorReceivesMtoken\r\n    ) external onlyLendingPool {\r\n        updatePrincipalReserveStateOnLiquidationInternal(\r\n            _principalReserve,\r\n            _user,\r\n            _amountToLiquidate,\r\n            _balanceIncrease\r\n        );\r\n\r\n        updateCollateralReserveStateOnLiquidationInternal(\r\n            _collateralReserve\r\n        );\r\n\r\n        updateUserStateOnLiquidationInternal(\r\n            _principalReserve,\r\n            _user,\r\n            _amountToLiquidate,\r\n            _feeLiquidated,\r\n            _balanceIncrease\r\n        );\r\n\r\n        updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0);\r\n\r\n        if(!_liquidatorReceivesMtoken) {\r\n            updateReserveInterestRatesAndTimestampInternal(\r\n                _collateralReserve,\r\n                0,\r\n                _collateralToLiquidate.add(_liquidatedCollateralForFee)\r\n            );\r\n        }\r\n    }\r\n\r\n    function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease)\r\n        external\r\n        onlyLendingPool\r\n        returns (uint256)\r\n    {\r\n        updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);\r\n\r\n        updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);\r\n        updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);\r\n\r\n        return usersReserveData[_user][_reserve].stableBorrowRate;\r\n    }\r\n\r\n    function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral)\r\n        public\r\n        onlyLendingPool\r\n    {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        user.useAsCollateral = _useAsCollateral;\r\n    }\r\n\r\n    //@notice ETH/token transfer function\r\n    \r\n    //only contracts can send ETH to the core\r\n    fallback() external payable {\r\n        require(msg.sender.code.length > 0, \"Only contracts can send ether to the Lending pool core!\");\r\n    }\r\n\r\n    receive() external payable {}\r\n\r\n    function transferToUser(address _reserve, address payable _user, uint256 _amount) \r\n        external\r\n        onlyLendingPool\r\n    {\r\n        if(_reserve != EthAddressLib.ethAddress()) {\r\n            ERC20(_reserve).safeTransfer(_user, _amount);\r\n        } else {\r\n            (bool result, ) = _user.call{value: _amount, gas: 20000}(\"\");\r\n            require(result, \"Transfer of ETH failed\");\r\n        }\r\n    }\r\n\r\n    function transferToFeeCollectionAddress(\r\n        address _token,\r\n        address _user,\r\n        uint256 _amount,\r\n        address _destination\r\n    ) external payable onlyLendingPool {\r\n        address payable feeAddress = payable(_destination);\r\n\r\n        if(_token != EthAddressLib.ethAddress()) {\r\n            require(msg.value == 0, \"User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction!\");\r\n            ERC20(_token).safeTransferFrom(_user, feeAddress, _amount);\r\n        } else {\r\n            require(msg.value >= _amount, \"The amount and the value sent to deposit do not match\");\r\n\r\n            (bool result, ) = feeAddress.call{value: _amount, gas: 20000}(\"\");\r\n            require(result, \"Transfer of ETH failed\");\r\n        }\r\n    }\r\n\r\n    function liquidateFee(\r\n        address _token,\r\n        uint256 _amount,\r\n        address _destination\r\n    ) external payable onlyLendingPool {\r\n        address payable feeAddress = payable(_destination);\r\n        require(msg.value == 0, \"Fee liquidation does not require any transfer of value\");\r\n\r\n        if(_token != EthAddressLib.ethAddress()) {\r\n            ERC20(_token).safeTransfer(feeAddress, _amount);\r\n        } else {\r\n            (bool result, ) = feeAddress.call{value: _amount, gas: 20000}(\"\");\r\n            require(result, \"Transfer of ETH failed\");\r\n        }\r\n    }\r\n\r\n    function transferToReserve(\r\n        address _reserve,\r\n        address payable _user,\r\n        uint256 _amount\r\n    ) external payable onlyLendingPool {\r\n        if(_reserve != EthAddressLib.ethAddress()) {\r\n            require(msg.value == 0, \"User is sending ETH along with the ERC20 transfer!\");\r\n            ERC20(_reserve).safeTransferFrom(_user, address(this), _amount);\r\n        } else {\r\n            require(msg.value >= _amount, \"The amount and the value sent to deposit do not match\");\r\n\r\n            if(msg.value > _amount) {\r\n                uint256 excessAmount = msg.value.sub(_amount);\r\n\r\n                (bool result, ) = _user.call{value: excessAmount, gas:20000}(\"\");\r\n                require(result, \"Transfer of ETH failed\");\r\n            }\r\n        }\r\n    }\r\n    //@notice data access function\r\n\r\n    \r\n    // avoid stack too deep\r\n    function getReserveData(address _reserve) external view returns (CoreLibrary.ReserveData memory) {\r\n        return reserves[_reserve];\r\n    }\r\n\r\n    //return user's balance, fee accrued, reserve enabled/disabled as collateral\r\n\r\n    function getUserBasicReserveData(address _reserve, address _user)\r\n        external view returns (uint256, uint256, uint256, bool)\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user);\r\n\r\n        if(user.principalBorrowBalance == 0) {\r\n            return (underlyingBalance, 0, 0, user.useAsCollateral);\r\n        }\r\n\r\n        return (\r\n            underlyingBalance,\r\n            user.getCompoundedBorrowBalance(reserve),\r\n            user.originationFee,\r\n            user.useAsCollateral\r\n        );\r\n    }\r\n\r\n    function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount)\r\n        external\r\n        view\r\n        returns (bool)\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        if(!reserve.isStableBorrowRateEnabled) {\r\n            return false;\r\n        }\r\n\r\n        return \r\n            !user.useAsCollateral ||\r\n            !reserve.usageAsCollateralEnabled ||\r\n            _amount > getUserUnderlyingAssetBalance(_reserve, _user);\r\n    }\r\n\r\n    function getUserUnderlyingAssetBalance(address _reserve, address _user)\r\n        public \r\n        view\r\n        returns (uint256)\r\n    {\r\n        MToken mToken = MToken(reserves[_reserve].mTokenAddress);\r\n        return mToken.balanceOf(_user);\r\n    }\r\n\r\n    function getReserveInterestRateStrategyAddress(address _reserve)\r\n        public view returns (address)\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.interestRateStrategyAddress;\r\n    }\r\n\r\n    function getReserveMTokenAddress(address _reserve)\r\n        public \r\n        view\r\n        returns (address)\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.mTokenAddress;\r\n    }\r\n\r\n    function getReserveAvailableLiquidity(address _reserve) public view returns(uint256) {\r\n        uint256 balance = 0;\r\n\r\n        if(_reserve == EthAddressLib.ethAddress()) {\r\n            balance = address(this).balance;\r\n        } else {\r\n            balance = IERC20(_reserve).balanceOf(address(this));\r\n        }\r\n        return balance;\r\n    }\r\n\r\n    function getReserveTotalLiquidity(address _reserve) public view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows());\r\n    }\r\n\r\n    function getReserveNormalizedIncome(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.getNormalizedIncome();\r\n    }\r\n\r\n    function getReserveTotalBorrows(address _reserve) public view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.getTotalBorrows();\r\n    }\r\n\r\n    function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.totalBorrowsStable;\r\n    }\r\n\r\n    function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.totalBorrowsVariable;\r\n    }\r\n\r\n    function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.liquidationThreshold;\r\n    }\r\n\r\n    function getReserveLiquidationBonus(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.liquidationBonus;\r\n    }\r\n\r\n    function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n        if(reserve.currentVariableBorrowRate == 0) {\r\n            return \r\n                IReserveInterestRateStrategy(reserve.interestRateStrategyAddress)\r\n                .getBaseVariableBorrowRate();\r\n        }\r\n        return reserve.currentVariableBorrowRate;\r\n    }\r\n\r\n    function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle());\r\n\r\n        if(reserve.currentStableBorrowRate == 0) {\r\n            return oracle.getMarketBorrowRate(_reserve);\r\n        }\r\n\r\n        return reserve.currentStableBorrowRate;\r\n    }\r\n\r\n    function getReserveCurrentAverageStableBorrowRate(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.currentAverageStableBorrowRate;\r\n    }\r\n\r\n    function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.currentLiquidityRate;\r\n    }\r\n\r\n    function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.lastLiquidityCumulativeIndex;\r\n    }\r\n\r\n    function getReserveVariableBorrowsCumulativeIndex(address _reserve)\r\n        external\r\n        view\r\n        returns (uint256)\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.lastVariableBorrowCumulativeIndex;\r\n    }\r\n\r\n    function getReserveConfiguration(address _reserve)\r\n        external\r\n        view \r\n        returns(\r\n            uint256, uint256, uint256, bool\r\n        )\r\n    {\r\n        uint256 decimals;\r\n        uint256 baseLTVasCollateral;\r\n        uint256 liquidationThreshold;\r\n        bool usageAsCollateralEnabled;\r\n\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        decimals = reserve.decimals;\r\n        baseLTVasCollateral = reserve.baseLTVasCollateral;\r\n        liquidationThreshold = reserve.liquidationThreshold;\r\n        usageAsCollateralEnabled = reserve.usageAsCollateralEnabled;\r\n        \r\n        return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled);\r\n    }\r\n\r\n    function getReserveDecimals(address _reserve) external view returns (uint256) {\r\n        return reserves[_reserve].decimals;\r\n    }\r\n\r\n    function isReserveBorrowingEnabled(address _reserve) external view returns (bool) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.borrowingEnabled;\r\n    }\r\n\r\n    function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.usageAsCollateralEnabled;\r\n    }\r\n    \r\n    function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.isStableBorrowRateEnabled;\r\n    }\r\n\r\n    function getReserveIsActive(address _reserve) external view returns (bool) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.isActive;\r\n    }\r\n\r\n    function getReserveIsFreezed(address _reserve) external view returns (bool) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        return reserve.isFreezed;\r\n    }\r\n\r\n    function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        timestamp = reserve.lastUpdateTimestamp;\r\n    }\r\n\r\n    function getReserveUtilizationRate(address _reserve) public view returns (uint256) {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n        uint256 totalBorrows = reserve.getTotalBorrows();\r\n\r\n        if(totalBorrows == 0) {\r\n            return 0;\r\n        }\r\n\r\n        uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve);\r\n\r\n        return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows));\r\n    } \r\n\r\n    function getReserves() external view returns (address[] memory) {\r\n        return reservesList;\r\n    }\r\n\r\n    function isUserUseReserveAsCollateralEnabled(address _reserve, address _user) external view returns(bool) {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        return user.useAsCollateral;\r\n    }\r\n\r\n    function getUserOriginationFee(address _reserve, address _user) \r\n        external \r\n        view\r\n        returns(uint256)\r\n    {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        return user.originationFee;\r\n    }\r\n\r\n    function getUserCurrentBorrowRateMode(address _reserve, address _user)\r\n        public\r\n        view\r\n        returns(CoreLibrary.InterestRateMode)\r\n    {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        if(user.principalBorrowBalance == 0) {\r\n            return CoreLibrary.InterestRateMode.NONE;\r\n        }\r\n\r\n        return user.stableBorrowRate > 0 ? CoreLibrary.InterestRateMode.STABLE : CoreLibrary.InterestRateMode.VARIABLE;\r\n    }\r\n\r\n    function getUserCurrentBorrowRate(address _reserve, address _user) \r\n        internal\r\n        view\r\n        returns(uint256)\r\n    {\r\n        CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user);\r\n        if(rateMode == CoreLibrary.InterestRateMode.NONE) {\r\n            return 0;\r\n        }\r\n        return \r\n            rateMode == CoreLibrary.InterestRateMode.STABLE\r\n            ? usersReserveData[_user][_reserve].stableBorrowRate\r\n            : reserves[_reserve].currentVariableBorrowRate;\r\n    }\r\n\r\n\r\n    function getUserCurrentStableBorrowRate(address _reserve, address _user)\r\n        external\r\n        view\r\n        returns(uint256)\r\n    {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        return user.stableBorrowRate;\r\n    }\r\n\r\n    function getUserBorrowBalances(address _reserve, address _user)\r\n        public\r\n        view\r\n        returns(uint256, uint256, uint256)\r\n    {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        if(user.principalBorrowBalance == 0) {\r\n            return (0, 0, 0);\r\n        }\r\n        \r\n        uint256 principal = user.principalBorrowBalance;\r\n        uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance(user, reserves[_reserve]);\r\n\r\n        return (principal, compoundedBalance, compoundedBalance.sub(principal));\r\n    }\r\n\r\n    function getUserVariableBorrowCumulativeIndex(address _reserve, address _user)\r\n        external\r\n        view\r\n        returns(uint256)\r\n    {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        return user.lastVariableBorrowCumulativeIndex;\r\n    }\r\n\r\n    function getUserLastUpdate(address _reserve, address _user)\r\n        external \r\n        view \r\n        returns (uint256)\r\n    {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        return uint256(user.lastUpdateTimestamp); \r\n    }\r\n\r\n    function refreshConfiguration() external onlyLendingPoolConfigurator {\r\n        refreshConfigInternal();\r\n    }\r\n\r\n    function initReserve(address _reserve, address _mTokenAddress, uint256 _decimals, address _interestRateStrategyAddress)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        reserves[_reserve].init(_mTokenAddress, _decimals, _interestRateStrategyAddress);\r\n        addReserveToListInternal(_reserve);\r\n    }\r\n\r\n    function removeLastAddedReserve(address _reserveToRemove) external onlyLendingPoolConfigurator {\r\n        address lastReserve = reservesList[reservesList.length - 1];\r\n\r\n        require(lastReserve == _reserveToRemove, \"Reserve being removed is different than the reserve requrest\");\r\n\r\n        require(getReserveTotalBorrows(lastReserve) == 0, \"Cannot remove a reserve with liquidity deposited\");\r\n\r\n        reserves[lastReserve].isActive = false;\r\n        reserves[lastReserve].mTokenAddress = address(0);\r\n        reserves[lastReserve].decimals = 0;\r\n        reserves[lastReserve].lastLiquidityCumulativeIndex = 0;\r\n        reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0;\r\n        reserves[lastReserve].borrowingEnabled = false;\r\n        reserves[lastReserve].usageAsCollateralEnabled = false;\r\n        reserves[lastReserve].baseLTVasCollateral = 0;\r\n        reserves[lastReserve].liquidationThreshold = 0;\r\n        reserves[lastReserve].liquidationBonus = 0;\r\n        reserves[lastReserve].interestRateStrategyAddress = address(0);\r\n\r\n        reservesList.pop();\r\n    }\r\n\r\n    function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress;\r\n    }\r\n\r\n    function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled);\r\n    }\r\n\r\n    function disableBorrowingOnReserve(address _reserve)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        reserves[_reserve].disableBorrowing();\r\n    }\r\n\r\n    function enableReserveAsCollateral(\r\n        address _reserve,\r\n        uint256 _baseLTVasCollateral,\r\n        uint256 _liquidationThreshold,\r\n        uint256 _liquidationBonus\r\n    ) external onlyLendingPoolConfigurator {\r\n        reserves[_reserve].enableAsCollateral(\r\n            _baseLTVasCollateral,\r\n            _liquidationThreshold,\r\n            _liquidationBonus\r\n        );\r\n    }\r\n\r\n    function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator {\r\n        reserves[_reserve].disableAsCollateral();\r\n    }\r\n\r\n    function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.isStableBorrowRateEnabled = true;\r\n    }\r\n\r\n    function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.isStableBorrowRateEnabled = false;\r\n    }\r\n\r\n    function activateReserve(address _reserve) external onlyLendingPoolConfigurator {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n        require(\r\n            reserve.lastLiquidityCumulativeIndex > 0 &&\r\n                reserve.lastVariableBorrowCumulativeIndex > 0,\r\n            \"Reserve has not been initialized yet\"\r\n        );\r\n        reserve.isActive = true;\r\n    }\r\n\r\n    function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.isActive = false;\r\n    }\r\n\r\n    function freezeReserve(address _reserve) external onlyLendingPoolConfigurator {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.isFreezed = true;\r\n    }\r\n\r\n    function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.isFreezed = false;\r\n    }\r\n\r\n    function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.baseLTVasCollateral = _ltv;\r\n    }\r\n\r\n    function setReserveLiquidationThreshold(address _reserve, uint256 _threshold)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.liquidationThreshold = _threshold;\r\n    }\r\n\r\n    function setReserveLiquidationBonus(address _reserve, uint256 _bonus)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.liquidationBonus = _bonus;\r\n    }\r\n\r\n    function setReserveDecimals(address _reserve, uint256 _decimals)\r\n        external\r\n        onlyLendingPoolConfigurator\r\n    {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        reserve.decimals = _decimals;\r\n    }\r\n\r\n    //@notice: internal functions\r\n    \r\n    function updateReserveStateOnBorrowInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _principalBorrowBalance,\r\n        uint256 _balanceIncrease,\r\n        uint256 _amountBorrowed,\r\n        CoreLibrary.InterestRateMode _rateMode\r\n    ) internal {\r\n        reserves[_reserve].updateCumulativeIndexes();\r\n\r\n        updateReserveTotalBorrowsByRateModeInternal(\r\n            _reserve,\r\n            _user,\r\n            _principalBorrowBalance,\r\n            _balanceIncrease,\r\n            _amountBorrowed,\r\n            _rateMode\r\n        );\r\n    }\r\n\r\n    function updateUserStateOnBorrowInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _amountBorrowed,\r\n        uint256 _balanceIncrease,\r\n        uint256 _fee,\r\n        CoreLibrary.InterestRateMode _rateMode\r\n    ) internal {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        if(_rateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            user.stableBorrowRate = reserve.currentStableBorrowRate;\r\n            user.lastVariableBorrowCumulativeIndex = 0;\r\n        } else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) {\r\n            user.stableBorrowRate = 0;\r\n            user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;\r\n        } else {\r\n            revert(\"Invalid borrow rate mode\");\r\n        }\r\n\r\n        user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add(_balanceIncrease);\r\n\r\n        user.originationFee = user.originationFee.add(_fee);\r\n\r\n        user.lastUpdateTimestamp = uint40(block.timestamp);\r\n    }\r\n\r\n    function updateReserveStateOnRepayInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _paybackAmountMinusFees,\r\n        uint256 _balanceIncrease\r\n    ) internal {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user);\r\n\r\n        reserves[_reserve].updateCumulativeIndexes();\r\n\r\n        if(borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            reserve.increaseTotalBorrowsStableAndUpdateAverageRate(\r\n                _balanceIncrease,\r\n                user.stableBorrowRate\r\n            );\r\n            reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(\r\n                _paybackAmountMinusFees,\r\n                user.stableBorrowRate\r\n            );\r\n        } else {\r\n            reserve.increaseTotalBorrowsVariable(_balanceIncrease);\r\n            reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees);\r\n        }\r\n    }\r\n\r\n    function updateUserStateOnRepayInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _paybackAmountMinusFees,\r\n        uint256 _originationFeeRepaid,\r\n        uint256 _balanceIncrease,\r\n        bool _repaidWholeLoan\r\n    ) internal {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(_paybackAmountMinusFees);\r\n        user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;\r\n\r\n        if(_repaidWholeLoan) {\r\n            user.stableBorrowRate = 0;\r\n            user.lastVariableBorrowCumulativeIndex = 0;\r\n        }\r\n        user.originationFee = user.originationFee.sub(_originationFeeRepaid);\r\n\r\n        user.lastUpdateTimestamp = uint40(block.timestamp);\r\n    }\r\n\r\n    function updateReserveStateOnSwapRateInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _principalBorrowBalance,\r\n        uint256 _compoundedBorrowBalance,\r\n        CoreLibrary.InterestRateMode _currentRateMode\r\n    ) internal {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        reserve.updateCumulativeIndexes();\r\n\r\n        if(_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            uint256 userCurrentStableRate = user.stableBorrowRate;\r\n\r\n            reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(\r\n                _principalBorrowBalance,\r\n                userCurrentStableRate\r\n            );\r\n            reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance);\r\n        } else if(_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE){\r\n            uint256 currentStableRate = reserve.currentStableBorrowRate;\r\n            reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance);\r\n            reserve.increaseTotalBorrowsStableAndUpdateAverageRate(\r\n                _compoundedBorrowBalance,\r\n                currentStableRate\r\n            );\r\n        } else {\r\n            revert(\"Invalid rate mode received\");\r\n        }\r\n    }\r\n\r\n    function updateUserStateOnSwapRateInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _balanceIncrease,\r\n        CoreLibrary.InterestRateMode _currentRateMode\r\n    ) internal returns(CoreLibrary.InterestRateMode) {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n        CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE;\r\n\r\n        if(_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {\r\n            newMode = CoreLibrary.InterestRateMode.STABLE;\r\n            user.stableBorrowRate = reserve.currentStableBorrowRate;\r\n            user.lastVariableBorrowCumulativeIndex = 0;\r\n        } else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            newMode = CoreLibrary.InterestRateMode.VARIABLE;\r\n            user.stableBorrowRate = 0;\r\n            user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;\r\n        } else {\r\n            revert(\"Invalid interest rate mode received\");\r\n        }\r\n\r\n        user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);\r\n        user.lastUpdateTimestamp = uint40(block.timestamp);\r\n\r\n        return newMode;\r\n    }\r\n\r\n    function updatePrincipalReserveStateOnLiquidationInternal(\r\n        address _principalReserve,\r\n        address _user,\r\n        uint256 _amountToLiquidate,\r\n        uint256 _balanceIncrease\r\n    ) internal {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_principalReserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve];\r\n\r\n        reserve.updateCumulativeIndexes();\r\n\r\n        CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(\r\n            _principalReserve,\r\n            _user\r\n        );\r\n\r\n        if(borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            reserve.increaseTotalBorrowsStableAndUpdateAverageRate(_balanceIncrease, user.stableBorrowRate);\r\n\r\n            reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(_amountToLiquidate, user.stableBorrowRate);\r\n        } else {\r\n            reserve.increaseTotalBorrowsVariable(_balanceIncrease);\r\n\r\n            reserve.decreaseTotalBorrowsVariable(_amountToLiquidate);\r\n        }\r\n    }\r\n\r\n    function updateCollateralReserveStateOnLiquidationInternal(\r\n        address _collateralReserve\r\n    ) internal {\r\n        reserves[_collateralReserve].updateCumulativeIndexes();\r\n    }\r\n\r\n    function updateUserStateOnLiquidationInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _amountToLiquidate,\r\n        uint256 _feeLiquidate,\r\n        uint256 _balanceIncrease\r\n    ) internal {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n        user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(_amountToLiquidate);\r\n\r\n        if(getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE) {\r\n            user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;\r\n        }\r\n\r\n        if(_feeLiquidate > 0) {\r\n            user.originationFee = user.originationFee.sub(_feeLiquidate);\r\n        }\r\n\r\n        user.lastUpdateTimestamp = uint40(block.timestamp);\r\n    }\r\n\r\n    function updateReserveStateOnRebalanceInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _balanceIncrease\r\n    ) internal {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n        reserve.updateCumulativeIndexes();\r\n\r\n        reserve.increaseTotalBorrowsStableAndUpdateAverageRate(\r\n            _balanceIncrease,\r\n            user.stableBorrowRate\r\n        );\r\n    }\r\n\r\n    function updateUserStateOnRebalanceInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _balanceIncrease\r\n    ) internal {\r\n        CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n        user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);\r\n        user.stableBorrowRate = reserve.currentStableBorrowRate;\r\n\r\n        user.lastUpdateTimestamp = uint40(block.timestamp);\r\n    }\r\n\r\n    function updateReserveTotalBorrowsByRateModeInternal(\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _principalBalance,\r\n        uint256 _balanceIncrease,\r\n        uint256 _amountBorrowed,\r\n        CoreLibrary.InterestRateMode _newBorrowRateMode\r\n    ) internal {\r\n        CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode(_reserve, _user);\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n        if(previousRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n            reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(\r\n                _principalBalance,\r\n                user.stableBorrowRate\r\n            );\r\n        } else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) {\r\n            reserve.decreaseTotalBorrowsVariable(_principalBalance);\r\n        }\r\n\r\n        uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed);\r\n        if(_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n            reserve.increaseTotalBorrowsStableAndUpdateAverageRate(\r\n                newPrincipalAmount,\r\n                reserve.currentStableBorrowRate\r\n            );\r\n        } else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) {\r\n            reserve.increaseTotalBorrowsVariable(newPrincipalAmount);\r\n        } else {\r\n            revert(\"Invalid new borrow rate mode\");\r\n        }\r\n    }\r\n\r\n    function updateReserveInterestRatesAndTimestampInternal(\r\n        address _reserve,\r\n        uint256 _liquidityAdded,\r\n        uint256 _liquidityTaken\r\n    ) internal {\r\n        CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n        (\r\n            uint256 newLiquidityRate,\r\n            uint256 newStableRate,\r\n            uint256 newVariableRate\r\n        ) = IReserveInterestRateStrategy(\r\n            reserve.interestRateStrategyAddress\r\n        )\r\n        .calculateInterestRates(\r\n            _reserve,\r\n            getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken),\r\n            reserve.totalBorrowsStable,\r\n            reserve.totalBorrowsVariable,\r\n            reserve.currentAverageStableBorrowRate\r\n        );\r\n        \r\n        reserve.currentLiquidityRate = newLiquidityRate;\r\n        reserve.currentStableBorrowRate = newStableRate;\r\n        reserve.currentVariableBorrowRate = newVariableRate;\r\n\r\n        reserve.lastUpdateTimestamp = uint40(block.timestamp);\r\n\r\n        emit ReserveUpdate(\r\n            _reserve,\r\n            newLiquidityRate,\r\n            newStableRate,\r\n            newVariableRate,\r\n            reserve.lastLiquidityCumulativeIndex,\r\n            reserve.lastVariableBorrowCumulativeIndex\r\n        );\r\n    }\r\n\r\n\r\n    function refreshConfigInternal() internal {\r\n        lendingPoolAddress = addressesProvider.getLendingPool();\r\n    }\r\n\r\n    function addReserveToListInternal(address _reserve) internal {\r\n        bool reserveAlreadyAdded = false;\r\n        for(uint256 i = 0; i < reservesList.length; i++) {\r\n            if(reservesList[i] == _reserve) {\r\n                reserveAlreadyAdded = true;\r\n            }\r\n        }\r\n        if(!reserveAlreadyAdded) reservesList.push(_reserve);\r\n    }\r\n}"
      },
      "contracts/lendingpool/LendingPoolDataProvider.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\nimport \"../proxys/InitializableWithSlot.sol\";\r\n\r\nimport \"../libraries/CoreLibrary.sol\";\r\nimport \"../libraries/WadRayMath.sol\";\r\nimport \"../configuration/LendingPoolAddressesProvider.sol\";\r\nimport \"../interfaces/IPriceOracleGetter.sol\";\r\nimport \"../interfaces/IFeeProvider.sol\";\r\nimport \"../tokenization/MToken.sol\";\r\n\r\nimport \"./LendingPoolCore.sol\";\r\n\r\ncontract LendingPoolDataProvider is InitializableWithSlot {\r\n    using SafeMath for uint256;\r\n    using WadRayMath for uint256;\r\n\r\n    LendingPoolCore public core;\r\n    LendingPoolAddressesProvider public addressesProvider;\r\n\r\n    uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;\r\n    \r\n    function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {\r\n        addressesProvider = _addressesProvider;\r\n        core = LendingPoolCore(payable(_addressesProvider.getLendingPoolCore()));\r\n    }\r\n\r\n    struct UserGlobalDataLocalVars {\r\n        uint256 reserveUnitPrice;\r\n        uint256 tokenUnit;\r\n        uint256 compoundedLiquidityBalance;\r\n        uint256 compoundedBorrowBalance;\r\n        uint256 reserveDecimals;\r\n        uint256 baseLtv;\r\n        uint256 liquidationThreshold;\r\n        uint256 originationFee;\r\n        bool usageAsCollateralEnabled;\r\n        bool userUsesReserveAsCollateral;\r\n        address currentReserve;\r\n    }\r\n\r\n    function calculateUserGlobalData(address _user)\r\n        public \r\n        view\r\n        returns (\r\n            uint256 totalLiquidityBalanceETH,\r\n            uint256 totalCollateralBalanceETH,\r\n            uint256 totalBorrowBalanceETH,\r\n            uint256 totalFeesETH,\r\n            uint256 currentLtv,\r\n            uint256 currentLiquidationThreshold,\r\n            uint256 healthFactor,\r\n            bool healthFactorBelowThreshold\r\n        )\r\n    {\r\n        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());\r\n\r\n        UserGlobalDataLocalVars memory vars;\r\n\r\n        address[] memory reserves = core.getReserves();\r\n\r\n        for (uint256 i = 0; i < reserves.length; i++) {\r\n            vars.currentReserve = reserves[i];\r\n\r\n            (\r\n                vars.compoundedLiquidityBalance,\r\n                vars.compoundedBorrowBalance,\r\n                vars.originationFee,\r\n                vars.userUsesReserveAsCollateral\r\n            ) = core.getUserBasicReserveData(vars.currentReserve, _user);\r\n\r\n            if(vars.compoundedLiquidityBalance == 0 && vars.compoundedBorrowBalance == 0) {\r\n                continue;\r\n            }\r\n\r\n            (\r\n                vars.reserveDecimals,\r\n                vars.baseLtv,\r\n                vars.liquidationThreshold,\r\n                vars.usageAsCollateralEnabled\r\n            ) = core.getReserveConfiguration(vars.currentReserve);\r\n\r\n            vars.tokenUnit = 10 ** vars.reserveDecimals;\r\n            vars.reserveUnitPrice = oracle.getAssetPrice(vars.currentReserve);\r\n\r\n            //liquidity and collateral balance\r\n            if(vars.compoundedLiquidityBalance > 0) {\r\n                uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit);\r\n                totalLiquidityBalanceETH = totalLiquidityBalanceETH.add(liquidityBalanceETH);\r\n\r\n                if(vars.usageAsCollateralEnabled && vars.userUsesReserveAsCollateral) {\r\n                    totalCollateralBalanceETH = totalCollateralBalanceETH.add(liquidityBalanceETH);\r\n                    currentLtv = currentLtv.add(liquidityBalanceETH.mul(vars.baseLtv));\r\n                    currentLiquidationThreshold = currentLiquidationThreshold.add(liquidityBalanceETH.mul(vars.liquidationThreshold));\r\n                }\r\n            }\r\n\r\n            if(vars.compoundedBorrowBalance > 0) {\r\n                totalBorrowBalanceETH = totalBorrowBalanceETH.add(vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit));\r\n                totalFeesETH = totalFeesETH.add(vars.originationFee.mul(vars.reserveUnitPrice).div(vars.tokenUnit));\r\n            }\r\n        }\r\n\r\n        currentLtv = totalCollateralBalanceETH > 0 ? currentLtv.div(totalCollateralBalanceETH) : 0;\r\n        currentLiquidationThreshold = totalCollateralBalanceETH > 0\r\n            ? currentLiquidationThreshold.div(totalCollateralBalanceETH)\r\n            : 0;\r\n        \r\n        healthFactor = calculateHealthFactorFromBalancesInternal(\r\n            totalCollateralBalanceETH,\r\n            totalBorrowBalanceETH,\r\n            totalFeesETH,\r\n            currentLiquidationThreshold\r\n        );\r\n        healthFactorBelowThreshold = healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD;\r\n    }\r\n\r\n    struct balanceDecreaseAllowedLocalVars {\r\n        uint256 decimals;\r\n        uint256 collateralBalanceETH;\r\n        uint256 borrowBalanceETH;\r\n        uint256 totalFeesETH;\r\n        uint256 currentLiquidationThreshold;\r\n        uint256 reserveLiquidationThreshold;\r\n        uint256 amountToDecreaseETH;\r\n        uint256 collateralBalanceAfterDecrease;\r\n        uint256 liquidationThresholdAfterDecrease;\r\n        uint256 healthFactorAfterDecrease;\r\n        bool reserveUsageAsCollateralEnabled;\r\n    }\r\n\r\n    function balanceDecreaseAllowed(address _reserve, address _user, uint256 _amount)\r\n        external\r\n        view \r\n        returns (bool)\r\n    {\r\n        balanceDecreaseAllowedLocalVars memory vars;\r\n\r\n        (\r\n            vars.decimals,\r\n            ,\r\n            vars.reserveLiquidationThreshold,\r\n            vars.reserveUsageAsCollateralEnabled\r\n        ) = core.getReserveConfiguration(_reserve);\r\n\r\n        if (!vars.reserveUsageAsCollateralEnabled || !core.isUserUseReserveAsCollateralEnabled(_reserve, _user)) {\r\n            return true; //if reserve is not used to collateral, no reasons to block the transfer\r\n        }\r\n\r\n        (\r\n            ,\r\n            vars.collateralBalanceETH,\r\n            vars.borrowBalanceETH,\r\n            vars.totalFeesETH,\r\n            ,\r\n            vars.currentLiquidationThreshold,\r\n            ,\r\n        ) = calculateUserGlobalData(_user);\r\n\r\n        if(vars.borrowBalanceETH == 0) {\r\n            return true; //no borrows - no reasons to block the transfer\r\n        }\r\n\r\n        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());\r\n\r\n        vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div(10 ** vars.decimals);\r\n\r\n        vars.collateralBalanceAfterDecrease = vars.collateralBalanceETH.sub(vars.amountToDecreaseETH);\r\n\r\n        //if there is a borrow, there can't be 0 collateral\r\n        if(vars.collateralBalanceAfterDecrease == 0) {\r\n            return false;\r\n        }\r\n\r\n        vars.liquidationThresholdAfterDecrease = vars\r\n            .collateralBalanceETH\r\n            .mul(vars.currentLiquidationThreshold)\r\n            .sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold))\r\n            .div(vars.collateralBalanceAfterDecrease);\r\n\r\n        uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal(\r\n            vars.collateralBalanceAfterDecrease,\r\n            vars.borrowBalanceETH,\r\n            vars.totalFeesETH,\r\n            vars.liquidationThresholdAfterDecrease\r\n        );\r\n\r\n        return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD;\r\n    }\r\n\r\n    function calculateCollateralNeededInETH(\r\n        address _reserve,\r\n        uint256 _amount,\r\n        uint256 _fee,\r\n        uint256 _userCurrentBorrowBalanceTH,\r\n        uint256 _userCurrentFeesETH,\r\n        uint256 _userCurrentLtv\r\n    ) external view returns (uint256) {\r\n        uint256 reserveDecimals = core.getReserveDecimals(_reserve);\r\n        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());\r\n\r\n        uint256 requrestedBorrowAmountETH = oracle\r\n            .getAssetPrice(_reserve)\r\n            .mul(_amount.add(_fee))\r\n            .div(10 ** reserveDecimals); // price in ether\r\n\r\n        uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH\r\n            .add(_userCurrentFeesETH)\r\n            .add(requrestedBorrowAmountETH)\r\n            .mul(100)\r\n            .div(_userCurrentLtv);\r\n\r\n        return collateralNeededInETH;\r\n    }\r\n\r\n\r\n\r\n    //@notice: internal functions\r\n\r\n    function calculateAvailableBorrowsETHInternal(\r\n        uint256 collateralBalanceETH,\r\n        uint256 borrowBalanceETH,\r\n        uint256 totalFeesETH,\r\n        uint256 ltv\r\n    ) internal view returns (uint256) {\r\n        uint256 availableBorrowsETH = collateralBalanceETH.mul(ltv).div(100); //ltv is in percentage\r\n\r\n        if(availableBorrowsETH < borrowBalanceETH) {\r\n            return 0;\r\n        }\r\n\r\n        availableBorrowsETH = availableBorrowsETH.sub(borrowBalanceETH.add(totalFeesETH));\r\n        //calculate fee\r\n        uint256 borrowFee = IFeeProvider(addressesProvider.getFeeProvider())\r\n            .calculateLoanOriginationFee(msg.sender, availableBorrowsETH);\r\n        return availableBorrowsETH.sub(borrowFee);\r\n    }\r\n\r\n    function calculateHealthFactorFromBalancesInternal(\r\n        uint256 collateralBalanceETH,\r\n        uint256 borrowBalanceETH,\r\n        uint256 totalFeesETH,\r\n        uint256 liquidationThreshold\r\n    ) internal pure returns (uint256) {\r\n        if(borrowBalanceETH == 0) {\r\n            return type(uint256).max;\r\n        }\r\n\r\n        return (collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv(borrowBalanceETH.add(totalFeesETH));\r\n    }\r\n\r\n    function getHealthFactorLiquidationThreshold() public pure returns (uint256) {\r\n        return HEALTH_FACTOR_LIQUIDATION_THRESHOLD;\r\n    }\r\n\r\n    function getReserveConfigurationData(address _reserve)\r\n        external\r\n        view\r\n        returns (\r\n            uint256 ltv,\r\n            uint256 liquidationThreshold,\r\n            uint256 liquidationBonus,\r\n            address rateStrategyAddress,\r\n            bool usageAsCollateralEnabled,\r\n            bool borrowingEnabled,\r\n            bool stableBorrowRateEnabled,\r\n            bool isActive\r\n        )\r\n    {\r\n        (, ltv, liquidationThreshold, usageAsCollateralEnabled) = core.getReserveConfiguration(\r\n            _reserve\r\n        );\r\n        stableBorrowRateEnabled = core.getReserveIsStableBorrowRateEnabled(_reserve);\r\n        borrowingEnabled = core.isReserveBorrowingEnabled(_reserve);\r\n        isActive = core.getReserveIsActive(_reserve);\r\n        liquidationBonus = core.getReserveLiquidationBonus(_reserve);\r\n\r\n        rateStrategyAddress = core.getReserveInterestRateStrategyAddress(_reserve);\r\n    }\r\n\r\n    struct Reserve {\r\n        uint256 totalLiquidity;\r\n        uint256 availableLiquidity;\r\n        uint256 totalBorrowsStable;\r\n        uint256 totalBorrowsVariable;\r\n        uint256 liquidityRate;\r\n        uint256 variableBorrowRate;\r\n        uint256 stableBorrowRate;\r\n        uint256 averageStableBorrowRate;\r\n        uint256 utilizationRate;\r\n        uint256 liquidityIndex;\r\n        uint256 variableBorrowIndex;\r\n        address mTokenAddress;\r\n        uint40 lastUpdateTimestamp;\r\n    }\r\n\r\n    function getReserveData(address _reserve)\r\n        external \r\n        view \r\n        returns (\r\n            Reserve memory\r\n        )\r\n    {\r\n        // return core.getReserveData(_reserve);\r\n        Reserve memory data;\r\n        data.totalLiquidity = core.getReserveTotalLiquidity(_reserve);\r\n        data.availableLiquidity = core.getReserveAvailableLiquidity(_reserve);\r\n        data.totalBorrowsStable = core.getReserveTotalBorrowsStable(_reserve);\r\n        data.totalBorrowsVariable = core.getReserveTotalBorrowsVariable(_reserve);\r\n        data.liquidityRate = core.getReserveCurrentLiquidityRate(_reserve);\r\n        data.variableBorrowRate = core.getReserveCurrentVariableBorrowRate(_reserve);\r\n        data.stableBorrowRate = core.getReserveCurrentStableBorrowRate(_reserve);\r\n        data.averageStableBorrowRate = core.getReserveCurrentAverageStableBorrowRate(_reserve);\r\n        data.utilizationRate = core.getReserveUtilizationRate(_reserve);\r\n        data.liquidityIndex = core.getReserveLiquidityCumulativeIndex(_reserve);\r\n        data.variableBorrowIndex = core.getReserveVariableBorrowsCumulativeIndex(_reserve);\r\n        data.mTokenAddress = core.getReserveMTokenAddress(_reserve);\r\n        data.lastUpdateTimestamp = core.getReserveLastUpdate(_reserve);\r\n\r\n        return data;\r\n    }\r\n\r\n    function getUserAccountData(address _user)\r\n        external\r\n        view\r\n        returns (\r\n            uint256 totalLiquidityETH,\r\n            uint256 totalCollateralETH,\r\n            uint256 totalBorrowsETH,\r\n            uint256 totalFeesETH,\r\n            uint256 availableBorrowsETH,\r\n            uint256 currentLiquidationThreshold,\r\n            uint256 ltv,\r\n            uint256 healthFactor\r\n        )\r\n    {\r\n        (\r\n            totalLiquidityETH,\r\n            totalCollateralETH,\r\n            totalBorrowsETH,\r\n            totalFeesETH,\r\n            ltv,\r\n            currentLiquidationThreshold,\r\n            healthFactor,\r\n\r\n        ) = calculateUserGlobalData(_user);\r\n\r\n        availableBorrowsETH = calculateAvailableBorrowsETHInternal(\r\n            totalCollateralETH,\r\n            totalBorrowsETH,\r\n            totalFeesETH,\r\n            ltv\r\n        );\r\n    }\r\n\r\n    function getUserReserveData(address _reserve, address _user) \r\n        external\r\n        view \r\n        returns (\r\n            uint256 currentMTokenBalance,\r\n            uint256 currentBorrowBalance,\r\n            uint256 principalBorrowBalance,\r\n            uint256 borrowRateMode,\r\n            uint256 borrowRate,\r\n            uint256 liquidityRate,\r\n            uint256 originationFee,\r\n            uint256 variableBorrowIndex,\r\n            uint256 lastUpdateTimestamp,\r\n            bool usageAsCollateralEnabled\r\n        )\r\n    {\r\n        currentMTokenBalance = MToken(core.getReserveMTokenAddress(_reserve)).balanceOf(_user);\r\n        CoreLibrary.InterestRateMode mode = core.getUserCurrentBorrowRateMode(_reserve, _user);\r\n        (principalBorrowBalance, currentBorrowBalance, ) = core.getUserBorrowBalances(_reserve, _user);\r\n\r\n        //default is 0, if mode == CoreLibrary.InterestRateMode.NONE\r\n        if(mode == CoreLibrary.InterestRateMode.STABLE) {\r\n            borrowRate = core.getUserCurrentStableBorrowRate(_reserve, _user);\r\n        } else if (mode == CoreLibrary.InterestRateMode.VARIABLE) {\r\n            borrowRate = core.getReserveCurrentVariableBorrowRate(_reserve);\r\n        }\r\n\r\n        borrowRateMode = uint256(mode);\r\n        liquidityRate = core.getReserveCurrentLiquidityRate(_reserve); \r\n        originationFee = core.getUserOriginationFee(_reserve, _user);\r\n        variableBorrowIndex = core.getUserVariableBorrowCumulativeIndex(_reserve, _user);\r\n        lastUpdateTimestamp = core.getUserLastUpdate(_reserve, _user);\r\n        usageAsCollateralEnabled = core.isUserUseReserveAsCollateralEnabled(_reserve, _user);\r\n    }\r\n}\r\n"
      },
      "contracts/lendingpool/LendingPoolLiquidationManager.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\r\nimport \"@openzeppelin/contracts/utils/Address.sol\";\r\n\r\nimport \"../proxys/InitializableWithSlot.sol\";\r\nimport \"../configuration/LendingPoolAddressesProvider.sol\";\r\nimport \"../configuration/LendingPoolParametersProvider.sol\";\r\nimport \"../tokenization/MToken.sol\";\r\nimport \"../libraries/CoreLibrary.sol\";\r\nimport \"../libraries/WadRayMath.sol\";\r\nimport \"../interfaces/IPriceOracleGetter.sol\";\r\nimport \"./LendingPoolCore.sol\";\r\nimport \"./LendingPoolDataProvider.sol\";\r\n\r\ncontract LendingPoolLiquidationManager is ReentrancyGuard, InitializableWithSlot {\r\n    using SafeMath for uint256;\r\n    using WadRayMath for uint256;\r\n    using Address for address;\r\n\r\n    LendingPoolAddressesProvider public addressesProvider;\r\n    LendingPoolCore core;\r\n    LendingPoolDataProvider dataProvider;\r\n    LendingPoolParametersProvider parametersProvider;\r\n    IFeeProvider feeProvider;\r\n    address ethereumAddress;\r\n\r\n    uint256 constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 50;\r\n\r\n    event OriginationFeeLiquidated(\r\n        address indexed _collateral,\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _feeLiquidated,\r\n        uint256 _liquidatedCollateralForFee,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    event LiquidationCall(\r\n        address indexed _collateral,\r\n        address indexed _reserve,\r\n        address indexed _user,\r\n        uint256 _purchaseAmount,\r\n        uint256 _liquidatedCollateralAmount,\r\n        uint256 _accruedBorrowInterest,\r\n        address _liquidator,\r\n        bool _receiveMToken,\r\n        uint256 _timestamp\r\n    );\r\n\r\n    enum LiquidationErrors {\r\n        NO_ERROR,\r\n        NO_COLLATERAL_AVAILABLE,\r\n        COLLATERAL_CANNOT_BE_LIQUIDATED,\r\n        CURRRENCY_NOT_BORROWED,\r\n        HEALTH_FACTOR_ABOVE_THRESHOLD,\r\n        NOT_ENOUGH_LIQUIDITY\r\n    }\r\n\r\n    struct LiquidationCallLocalVars {\r\n        uint256 userCollateralBalance;\r\n        uint256 userCompoundedBorrowBalance;\r\n        uint256 borrowBalanceIncrease;\r\n        uint256 maxPrincipalAmountToLiquidate;\r\n        uint256 actualAmountToLiquidate;\r\n        uint256 liquidationRatio;\r\n        uint256 collateralPrice;\r\n        uint256 principalCurrencyPrice;\r\n        uint256 maxAmountCollateralToLiquidate;\r\n        uint256 originationFee;\r\n        uint256 feeLiquidated;\r\n        uint256 liquidatedCollateralForFee;\r\n        CoreLibrary.InterestRateMode borrowRateMode;\r\n        uint256 userStableRate;\r\n        bool isCollateralEnabled;\r\n        bool healthFactorBelowThreshold;\r\n    }\r\n\r\n    function liquidationCall(\r\n        address _collateral,\r\n        address _reserve,\r\n        address _user,\r\n        uint256 _purchaseAmount,\r\n        bool _receiveMToken\r\n    ) external payable returns (uint256, string memory) {\r\n        LiquidationCallLocalVars memory vars;\r\n\r\n        (, , , , , , , vars.healthFactorBelowThreshold) = dataProvider.calculateUserGlobalData(_user);\r\n\r\n        if(!vars.healthFactorBelowThreshold) {\r\n            return (\r\n                uint256(LiquidationErrors.HEALTH_FACTOR_ABOVE_THRESHOLD),\r\n                \"Health factor is not below the threshold\"\r\n            );\r\n        }\r\n\r\n        vars.userCollateralBalance = core.getUserUnderlyingAssetBalance(_collateral, _user);\r\n\r\n        //if _user hasn't deposited this specific collateral, nothing can be liquidated\r\n        if(vars.userCollateralBalance == 0) {\r\n            return (\r\n                uint256(LiquidationErrors.NO_COLLATERAL_AVAILABLE),\r\n                \"Invalid collateral to liquidate\"\r\n            );\r\n        }\r\n\r\n        vars.isCollateralEnabled = \r\n            core.isReserveUsageAsCollateralEnabled(_collateral) &&\r\n            core.isUserUseReserveAsCollateralEnabled(_collateral, _user);\r\n\r\n        //if _collateral isn't enabled as collateral by _user, it cannot be liquidated\r\n        if(!vars.isCollateralEnabled) {\r\n            return (\r\n                uint256(LiquidationErrors.COLLATERAL_CANNOT_BE_LIQUIDATED),\r\n                \"The collateral chosen cannot be liquidated\"\r\n            );\r\n        }\r\n\r\n        //if the user hasn't borrowed the specific currency defined by _reserve, it cannot be liquidated\r\n        (, vars.userCompoundedBorrowBalance, vars.borrowBalanceIncrease) = core\r\n            .getUserBorrowBalances(_reserve, _user);\r\n\r\n        if(vars.userCompoundedBorrowBalance == 0) {\r\n            return (\r\n                uint256(LiquidationErrors.CURRRENCY_NOT_BORROWED),\r\n                \"User did not borrow the specified currency\"\r\n            );\r\n        }\r\n\r\n        //all clear - calculate the max principal amount that can be liquidated\r\n        vars.maxPrincipalAmountToLiquidate = vars\r\n            .userCompoundedBorrowBalance\r\n            .mul(LIQUIDATION_CLOSE_FACTOR_PERCENT)\r\n            .div(100);\r\n\r\n        vars.actualAmountToLiquidate = _purchaseAmount > vars.maxPrincipalAmountToLiquidate\r\n            ? vars.maxPrincipalAmountToLiquidate\r\n            : _purchaseAmount;\r\n        \r\n        (uint256 maxCollateralToLiquidate, uint256 principalAmountNeeded) = calculateAvailableCollateralToLiquidate(\r\n            _collateral,\r\n            _reserve,\r\n            vars.actualAmountToLiquidate,\r\n            vars.userCollateralBalance\r\n        );\r\n\r\n        vars.originationFee = core.getUserOriginationFee(_reserve, _user);\r\n\r\n        //if there is a fee to liquidate, calculate the maximum amount of fee that can be liquidated\r\n        if(vars.originationFee > 0) {\r\n            (\r\n                vars.liquidatedCollateralForFee,\r\n                vars.feeLiquidated\r\n            ) = calculateAvailableCollateralToLiquidate(\r\n                _collateral,\r\n                _reserve,\r\n                vars.originationFee,\r\n                vars.userCollateralBalance.sub(maxCollateralToLiquidate)\r\n            );\r\n        }\r\n\r\n        //if principalAmountNeeded < vars.ActualAmountToLiquidate, there isn't enough\r\n        //of _collateral to cover the actual amount that is being liquidated, hence we liquidate\r\n        //a smaller amount\r\n        if(principalAmountNeeded < vars.actualAmountToLiquidate) {\r\n            vars.actualAmountToLiquidate = principalAmountNeeded;\r\n        }\r\n\r\n        //if liquidator reclaims the underlying asset, we make sure there is enough available collateral in the reserve\r\n        if(!_receiveMToken) {\r\n            uint256 currentAvailableCollateral = core.getReserveAvailableLiquidity(_collateral);\r\n            if(currentAvailableCollateral < maxCollateralToLiquidate) {\r\n                return (\r\n                    uint256(LiquidationErrors.NOT_ENOUGH_LIQUIDITY),\r\n                    \"There isn't enough liquidity available to liquidate\"\r\n                );\r\n            }\r\n        }\r\n\r\n        core.updateStateOnLiquidation(\r\n            _reserve,\r\n            _collateral,\r\n            _user,\r\n            vars.actualAmountToLiquidate,\r\n            maxCollateralToLiquidate,\r\n            vars.feeLiquidated,\r\n            vars.liquidatedCollateralForFee,\r\n            vars.borrowBalanceIncrease,\r\n            _receiveMToken\r\n        );\r\n\r\n        MToken collateralMtoken = MToken(core.getReserveMTokenAddress(_collateral));\r\n\r\n        //if liquidator reclaims the mToken, he receives the equivalent mtoken amount\r\n        if(_receiveMToken) {\r\n            collateralMtoken.transferOnLiquidation(_user, msg.sender, maxCollateralToLiquidate);\r\n        } else {\r\n            //otherwise receives the underlying asset\r\n            //burn the equivalent amount of mtoken\r\n            collateralMtoken.burnOnLiquidation(_user, maxCollateralToLiquidate);\r\n            core.transferToUser(_collateral, payable(msg.sender), maxCollateralToLiquidate);\r\n        }\r\n\r\n        core.transferToReserve{value: msg.value}(_reserve, payable(msg.sender), vars.actualAmountToLiquidate);//@notice:Maybe there is a {value: msg.value}\r\n\r\n        if(vars.feeLiquidated > 0) {\r\n            //if there is enough collateral to liquidate the fee, first transfer burn an equivalent amount of\r\n            //mTokens of the user\r\n            collateralMtoken.burnOnLiquidation(_user, vars.liquidatedCollateralForFee);\r\n\r\n            //then liquidate the fee by transferring it to the fee collection address\r\n            core.liquidateFee(\r\n                _collateral, \r\n                vars.liquidatedCollateralForFee,\r\n                addressesProvider.getTokenDistributor()\r\n            );\r\n\r\n            emit OriginationFeeLiquidated(\r\n                _collateral,\r\n                _reserve,\r\n                _user,\r\n                vars.feeLiquidated,\r\n                vars.liquidatedCollateralForFee,\r\n                //solium-disable-next-line\r\n                block.timestamp\r\n            );\r\n        }\r\n        emit LiquidationCall(\r\n            _collateral,\r\n            _reserve,\r\n            _user,\r\n            vars.actualAmountToLiquidate,\r\n            maxCollateralToLiquidate,\r\n            vars.borrowBalanceIncrease,\r\n            msg.sender,\r\n            _receiveMToken,\r\n            //solium-disable-next-line\r\n            block.timestamp\r\n        );\r\n\r\n        return (uint256(LiquidationErrors.NO_ERROR), \"No errors\");\r\n    }\r\n\r\n    struct AvailableCollateralToLiquidateLocalVars {\r\n        uint256 userCompoundedBorrowBalance;\r\n        uint256 liquidationBonus;\r\n        uint256 collateralPrice;\r\n        uint256 principalCurrencyPrice;\r\n        uint256 maxAmountCollateralToLiquidate;\r\n    }\r\n\r\n    function calculateAvailableCollateralToLiquidate(\r\n        address _collateral,\r\n        address _principal,\r\n        uint256 _purchaseAmount,\r\n        uint256 _userCollateralBalance\r\n    ) internal view returns (uint256 collateralAmount, uint256 principalAmountNeeded) {\r\n        collateralAmount = 0;\r\n        principalAmountNeeded = 0;\r\n        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());\r\n\r\n        // Usage of a memory struct of vars to avoid \"Stack too deep\" errors due to local variables\r\n        AvailableCollateralToLiquidateLocalVars memory vars;\r\n\r\n        vars.collateralPrice = oracle.getAssetPrice(_collateral);\r\n        vars.principalCurrencyPrice = oracle.getAssetPrice(_principal);\r\n        vars.liquidationBonus = core.getReserveLiquidationBonus(_collateral);\r\n\r\n        //this is the maximum possible amount of the selected collateral that can be liquidated, given the\r\n        //max amount of principal currency that is available for liquidation.\r\n        vars.maxAmountCollateralToLiquidate = vars\r\n            .principalCurrencyPrice\r\n            .mul(_purchaseAmount)\r\n            .div(vars.collateralPrice)\r\n            .mul(vars.liquidationBonus)\r\n            .div(100);\r\n\r\n        if(vars.maxAmountCollateralToLiquidate > _userCollateralBalance) {\r\n            collateralAmount = _userCollateralBalance;\r\n            principalAmountNeeded = vars\r\n                .collateralPrice\r\n                .mul(collateralAmount)\r\n                .div(vars.principalCurrencyPrice)\r\n                .mul(100)\r\n                .div(vars.liquidationBonus);\r\n        } else {\r\n            collateralAmount = vars.maxAmountCollateralToLiquidate;\r\n            principalAmountNeeded = _purchaseAmount;\r\n        }\r\n\r\n        return (collateralAmount, principalAmountNeeded);\r\n    }\r\n}"
      },
      "contracts/libraries/CoreLibrary.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\nimport \"./WadRayMath.sol\";\r\n\r\nlibrary CoreLibrary {\r\n    using SafeMath for uint256;\r\n    using WadRayMath for uint256;\r\n\r\n    enum InterestRateMode {NONE, STABLE, VARIABLE}\r\n\r\n    uint256 internal constant SECONDS_PER_YEAR = 365 days;\r\n\r\n    struct UserReserveData {\r\n        //principal amount borrowed by the user.\r\n        uint256 principalBorrowBalance;\r\n        //cumulated variable borrow index for the user. Expressed in ray\r\n        uint256 lastVariableBorrowCumulativeIndex;\r\n        //origination fee cumulated by the user\r\n        uint256 originationFee;\r\n        // stable borrow rate at which the user has borrowed. Expressed in ray\r\n        uint256 stableBorrowRate;\r\n        uint40 lastUpdateTimestamp;\r\n        //defines if a specific deposit should or not be used as a collateral in borrows\r\n        bool useAsCollateral;\r\n    }\r\n\r\n    struct ReserveData {\r\n        /**\r\n        * @dev refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.\r\n        **/\r\n        //the liquidity index. Expressed in ray\r\n        uint256 lastLiquidityCumulativeIndex;\r\n        //the current supply rate. Expressed in ray\r\n        uint256 currentLiquidityRate;\r\n        //the total borrows of the reserve at a stable rate. Expressed in the currency decimals\r\n        uint256 totalBorrowsStable;\r\n        //the total borrows of the reserve at a variable rate. Expressed in the currency decimals\r\n        uint256 totalBorrowsVariable;\r\n        //the current variable borrow rate. Expressed in ray\r\n        uint256 currentVariableBorrowRate;\r\n        //the current stable borrow rate. Expressed in ray\r\n        uint256 currentStableBorrowRate;\r\n        //the current average stable borrow rate (weighted average of all the different stable rate loans). Expressed in ray\r\n        uint256 currentAverageStableBorrowRate;\r\n        //variable borrow index. Expressed in ray\r\n        uint256 lastVariableBorrowCumulativeIndex;\r\n        //the ltv of the reserve. Expressed in percentage (0-100)\r\n        uint256 baseLTVasCollateral;\r\n        //the liquidation threshold of the reserve. Expressed in percentage (0-100)\r\n        uint256 liquidationThreshold;\r\n        //the liquidation bonus of the reserve. Expressed in percentage\r\n        uint256 liquidationBonus;\r\n        //the decimals of the reserve asset\r\n        uint256 decimals;\r\n        /**\r\n        * @dev address of the mToken representing the asset\r\n        **/\r\n        address mTokenAddress;\r\n        /**\r\n        * @dev address of the interest rate strategy contract\r\n        **/\r\n        address interestRateStrategyAddress;\r\n        uint40 lastUpdateTimestamp;\r\n        // borrowingEnabled = true means users can borrow from this reserve\r\n        bool borrowingEnabled;\r\n        // usageAsCollateralEnabled = true means users can use this reserve as collateral\r\n        bool usageAsCollateralEnabled;\r\n        // isStableBorrowRateEnabled = true means users can borrow at a stable rate\r\n        bool isStableBorrowRateEnabled;\r\n        // isActive = true means the reserve has been activated and properly configured\r\n        bool isActive;\r\n        // isFreezed = true means the reserve only allows repays and redeems, but not deposits, new borrowings or rate swap\r\n        bool isFreezed;\r\n    }\r\n\r\n    function getNormalizedIncome(CoreLibrary.ReserveData storage _reserve) \r\n        internal\r\n        view\r\n        returns (uint256)\r\n    {\r\n        uint256 cumulated = calculateLinearInterest(\r\n            _reserve.currentLiquidityRate,\r\n            _reserve.lastUpdateTimestamp\r\n        ).rayMul(_reserve.lastLiquidityCumulativeIndex);\r\n        return cumulated;\r\n    }\r\n\r\n    function updateCumulativeIndexes(ReserveData storage _self) internal {\r\n        uint256 totalBorrows = getTotalBorrows(_self);\r\n\r\n        if(totalBorrows > 0) {\r\n            uint256 cumulatedLiquidityInterest = calculateLinearInterest(\r\n                _self.currentLiquidityRate,\r\n                _self.lastUpdateTimestamp\r\n            );\r\n\r\n            _self.lastLiquidityCumulativeIndex = cumulatedLiquidityInterest.rayMul(\r\n                _self.lastLiquidityCumulativeIndex\r\n            );\r\n\r\n            uint256 cumulatedVariableBorrowInterest = calculateCompoundedInterest(\r\n                _self.currentVariableBorrowRate,\r\n                _self.lastUpdateTimestamp\r\n            );\r\n            _self.lastVariableBorrowCumulativeIndex = cumulatedVariableBorrowInterest.rayMul(\r\n                _self.lastVariableBorrowCumulativeIndex\r\n            );\r\n        }\r\n    }\r\n\r\n    function cumulateToLiquidityIndex(\r\n        ReserveData storage _self,\r\n        uint256 _totalLiquidity,\r\n        uint256 _amount\r\n    ) internal {\r\n        uint256 amountToLiquidityRatio = _amount.wadToRay().rayDiv(_totalLiquidity.wadToRay());\r\n\r\n        uint256 cumulatedLiquidity = amountToLiquidityRatio.add(WadRayMath.ray());\r\n\r\n        _self.lastLiquidityCumulativeIndex = cumulatedLiquidity.rayMul(\r\n            _self.lastLiquidityCumulativeIndex\r\n        );\r\n    }\r\n\r\n    function init(\r\n        ReserveData storage _self,\r\n        address _mTokenAddress,\r\n        uint256 _decimals,\r\n        address _interestRateStrategyAddress\r\n    ) external {\r\n        require(_self.mTokenAddress == address(0), \"Reserve has already been initialized!\");\r\n\r\n        if(_self.lastLiquidityCumulativeIndex == 0) {\r\n            _self.lastLiquidityCumulativeIndex = WadRayMath.ray();\r\n        }\r\n\r\n        if(_self.lastVariableBorrowCumulativeIndex == 0) {\r\n            _self.lastVariableBorrowCumulativeIndex = WadRayMath.ray();\r\n        }\r\n\r\n        _self.mTokenAddress = _mTokenAddress;\r\n        _self.decimals = _decimals;\r\n\r\n        _self.interestRateStrategyAddress = _interestRateStrategyAddress;\r\n        _self.isActive = true;\r\n        _self.isFreezed = false;\r\n    }\r\n\r\n    function enableBorrowing(ReserveData storage _self, bool _stableBorrowRateEnabled) external {\r\n        require(_self.borrowingEnabled == false, \"Reserve is already enabled!\");\r\n\r\n        _self.borrowingEnabled = true;\r\n        _self.isStableBorrowRateEnabled = _stableBorrowRateEnabled;\r\n    }\r\n\r\n    function disableBorrowing(ReserveData storage _self) external {\r\n        _self.borrowingEnabled = false;\r\n    }\r\n\r\n    function enableAsCollateral(\r\n        ReserveData storage _self,\r\n        uint256 _baseLTVasCollateral,\r\n        uint256 _liquidationThreshold,\r\n        uint256 _liquidationBonus\r\n    ) external {\r\n        require(\r\n            _self.usageAsCollateralEnabled == false,\r\n            \"Reserve is already enabled as collateral\"\r\n        );\r\n        \r\n        _self.usageAsCollateralEnabled = true;\r\n        _self.baseLTVasCollateral = _baseLTVasCollateral;\r\n        _self.liquidationThreshold = _liquidationThreshold;\r\n        _self.liquidationBonus = _liquidationBonus;\r\n\r\n        if(_self.lastLiquidityCumulativeIndex == 0) {\r\n            _self.lastLiquidityCumulativeIndex = WadRayMath.ray();\r\n        }\r\n    }\r\n\r\n    function disableAsCollateral(ReserveData storage _self) external {\r\n        _self.usageAsCollateralEnabled = false;\r\n    }\r\n\r\n    function getCompoundedBorrowBalance(\r\n        CoreLibrary.UserReserveData storage _self,\r\n        CoreLibrary.ReserveData storage _reserve\r\n    ) internal view returns (uint256) {\r\n        if (_self.principalBorrowBalance == 0) {\r\n            return 0;\r\n        }\r\n\r\n        uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay();\r\n        uint256 compoundedBalance = 0;\r\n        uint256 cumulatedInterest = 0;\r\n\r\n        if(_self.stableBorrowRate > 0) {\r\n            cumulatedInterest = calculateCompoundedInterest(\r\n                _self.stableBorrowRate,\r\n                _self.lastUpdateTimestamp\r\n            );\r\n        } else {\r\n            cumulatedInterest = calculateCompoundedInterest(\r\n                _reserve.currentVariableBorrowRate,\r\n                _reserve.lastUpdateTimestamp\r\n            )\r\n            .rayMul(_reserve.lastVariableBorrowCumulativeIndex)\r\n            .rayDiv(_self.lastVariableBorrowCumulativeIndex);\r\n        }\r\n\r\n        compoundedBalance = principalBorrowBalanceRay.rayMul(cumulatedInterest).rayToWad();\r\n\r\n        if(compoundedBalance == _self.principalBorrowBalance) {\r\n            if(_self.lastUpdateTimestamp != block.timestamp) {\r\n                //no interest cumulation because of the rounding - we add 1 wei\r\n                //as symbolic cumulated interest to avoid interest free loans.\r\n\r\n                return _self.principalBorrowBalance.add(1 wei);\r\n            }\r\n        }\r\n\r\n        return compoundedBalance;\r\n    }\r\n\r\n    function increaseTotalBorrowsStableAndUpdateAverageRate(\r\n        ReserveData storage _reserve,\r\n        uint256 _amount,\r\n        uint256 _rate\r\n    ) internal {\r\n        uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;\r\n\r\n        _reserve.totalBorrowsStable = _reserve.totalBorrowsStable.add(_amount);\r\n\r\n        uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate);\r\n        uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul(\r\n            _reserve.currentAverageStableBorrowRate\r\n        );\r\n\r\n        _reserve.currentAverageStableBorrowRate = weightedLastBorrow\r\n            .add(weightedPreviousTotalBorrows)\r\n            .rayDiv(_reserve.totalBorrowsStable.wadToRay());\r\n    }\r\n\r\n    function decreaseTotalBorrowsStableAndUpdateAverageRate(\r\n        ReserveData storage _reserve,\r\n        uint256 _amount,\r\n        uint256 _rate\r\n    ) internal {\r\n        require(_reserve.totalBorrowsStable >= _amount, \"Invalid amount to decrease\");\r\n\r\n        uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;\r\n\r\n        _reserve.totalBorrowsStable = _reserve.totalBorrowsStable.sub(_amount);\r\n\r\n        if(_reserve.totalBorrowsStable == 0) {\r\n            _reserve.currentAverageStableBorrowRate = 0;\r\n            return;\r\n        }\r\n\r\n        uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate);\r\n        uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul(\r\n            _reserve.currentAverageStableBorrowRate\r\n        );\r\n\r\n        require(\r\n            weightedPreviousTotalBorrows >= weightedLastBorrow,\r\n            \"The amount to subtract don't match!\"\r\n        );\r\n\r\n        _reserve.currentAverageStableBorrowRate = weightedPreviousTotalBorrows\r\n            .sub(weightedLastBorrow)\r\n            .rayDiv(_reserve.totalBorrowsStable.wadToRay());\r\n    }\r\n\r\n    function increaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal {\r\n        _reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.add(_amount);\r\n    }\r\n\r\n    function decreaseTotalBorrowsVariable(ReserveData storage _reserve, uint256 _amount) internal {\r\n        require(\r\n            _reserve.totalBorrowsVariable >= _amount,\r\n            \"The amount that is being subtracted from the variable total borrows is incorrect!\"\r\n        );\r\n        _reserve.totalBorrowsVariable = _reserve.totalBorrowsVariable.sub(_amount);\r\n    }\r\n\r\n    function calculateLinearInterest(uint256 _rate, uint40 _lastUpdateTimestamp)\r\n        internal\r\n        view\r\n        returns (uint256)\r\n    {\r\n        uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp));\r\n        \r\n        uint256 timeDelta = timeDifference.wadToRay().rayDiv(SECONDS_PER_YEAR.wadToRay());\r\n        \r\n        return _rate.rayMul(timeDelta).add(WadRayMath.ray());\r\n    }\r\n\r\n    function calculateCompoundedInterest(uint256 _rate, uint40 _lastUpdateTimestamp)\r\n        internal\r\n        view\r\n        returns (uint256)\r\n    {\r\n        uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp));\r\n        \r\n        uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR);\r\n\r\n        return (ratePerSecond.add(WadRayMath.ray())).rayPow(timeDifference);\r\n    }\r\n\r\n    function getTotalBorrows(CoreLibrary.ReserveData storage _reserve)\r\n        internal\r\n        view\r\n        returns (uint256)\r\n    {\r\n        return _reserve.totalBorrowsStable.add(_reserve.totalBorrowsVariable);\r\n    }\r\n}"
      },
      "contracts/libraries/EthAddressLib.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\nlibrary EthAddressLib {\r\n    function ethAddress() internal pure returns (address) {\r\n        return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\r\n    }\r\n}"
      },
      "contracts/libraries/WadRayMath.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\n\r\nlibrary WadRayMath {\r\n    using SafeMath for uint256;\r\n\r\n    uint256 internal constant WAD = 1e18;\r\n    uint256 internal constant halfWAD = WAD / 2;\r\n\r\n    uint256 internal constant RAY = 1e27;\r\n    uint256 internal constant halfRAY = RAY / 2;\r\n\r\n    uint256 internal constant WAD_RAY_RATIO = 1e9;\r\n\r\n    function ray() internal pure returns (uint256) {\r\n        return RAY;\r\n    }\r\n\r\n    function wad() internal pure returns (uint256) {\r\n        return WAD;\r\n    }\r\n\r\n    function halfRay() internal pure returns (uint256) {\r\n        return halfRAY;\r\n    }\r\n\r\n    function halfWad() internal pure returns (uint256) {\r\n        return halfWAD;\r\n    }\r\n\r\n    function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        return halfWAD.add(a.mul(b)).div(WAD);\r\n    }\r\n\r\n    function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        uint256 halfB = b / 2;\r\n\r\n        return halfB.add(a.mul(WAD)).div(b);\r\n    }\r\n\r\n    function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        return halfRAY.add(a.mul(b)).div(RAY);\r\n    }\r\n\r\n    function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {\r\n        uint256 halfB = b / 2;\r\n        \r\n        return halfB.add(a.mul(RAY)).div(b);\r\n    }\r\n\r\n    function rayToWad(uint256 a) internal pure returns (uint256) {\r\n        uint256 halfRatio = WAD_RAY_RATIO / 2;\r\n\r\n        return halfRatio.add(a).div(WAD_RAY_RATIO);\r\n    }\r\n\r\n    function wadToRay(uint256 a) internal pure returns (uint256) {\r\n        return a.mul(WAD_RAY_RATIO);\r\n    }\r\n\r\n    function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {\r\n        z = n % 2 != 0 ? x : RAY;\r\n\r\n        for(n /= 2; n != 0; n /= 2) {\r\n            x = rayMul(x, x);\r\n\r\n            if (n % 2 != 0) {\r\n                z = rayMul(z, x);\r\n            }\r\n        }\r\n    }\r\n}"
      },
      "contracts/proxys/InitializableWithSlot.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\r\n\r\ncontract InitializableWithSlot is Initializable {\r\n    uint256[50] private ______gap;\r\n}"
      },
      "contracts/proxys/UUPSProxy.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol\";\r\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\r\n\r\ncontract UUPSProxy is ERC1967Proxy {\r\n\r\n    // address public owner;\r\n\r\n    modifier onlyAdmin() {\r\n        require(msg.sender == _getAdmin(), \"You are not the admin\");\r\n        _;\r\n    }\r\n\r\n    constructor(address implementAddress) ERC1967Proxy(implementAddress, msg.data) {\r\n        _changeAdmin(msg.sender);\r\n    }\r\n\r\n    function updateImpl(address newImpl) public onlyAdmin {\r\n        _upgradeTo(newImpl);\r\n    }\r\n\r\n    function getImplementation() public view returns(address) {\r\n        return _implementation();\r\n    }\r\n\r\n    function getAdmin() public view returns(address) {\r\n        return _getAdmin();\r\n    }\r\n}"
      },
      "contracts/tokenization/MToken.sol": {
        "content": "//SPDX-License-Identifier:MIT\r\n\r\npragma solidity ^0.8.9;\r\n\r\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\r\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\r\n\r\nimport \"../configuration/LendingPoolAddressesProvider.sol\";\r\nimport \"../lendingpool/LendingPool.sol\";\r\nimport \"../lendingpool/LendingPoolDataProvider.sol\";\r\nimport \"../lendingpool/LendingPoolCore.sol\";\r\nimport \"../libraries/WadRayMath.sol\";\r\n\r\n\r\ncontract MToken is ERC20 {\r\n    using WadRayMath for uint256;\r\n    using SafeMath for uint256;\r\n\r\n    uint256 public constant UINT_MAX_VALUE = type(uint256).max;\r\n\r\n    event Redeem(\r\n        address indexed _from,\r\n        uint256 _value,\r\n        uint256 _fromBalanceIncrease,\r\n        uint256 _fromIndex\r\n    );\r\n\r\n    event MintOnDeposit(\r\n        address indexed _from,\r\n        uint256 _value,\r\n        uint256 _fromBalanceIncrease,\r\n        uint256 _fromIndex\r\n    );\r\n\r\n    event BurnOnLiquidation(\r\n        address indexed _from,\r\n        uint256 _value,\r\n        uint256 _fromBalanceIncrease,\r\n        uint256 _fromIndex\r\n    );\r\n\r\n    event BalanceTransfer(\r\n        address indexed _from,\r\n        address indexed _to,\r\n        uint256 _value,\r\n        uint256 _fromBalanceIncrease,\r\n        uint256 _toBalanceIncrease,\r\n        uint256 _fromIndex,\r\n        uint256 _toIndex\r\n    );\r\n\r\n    event InterestStreamRedirected(\r\n        address indexed _from,\r\n        address indexed _to,\r\n        uint256 _redirectedBalance,\r\n        uint256 _fromBalanceIncrease,\r\n        uint256 _fromIndex\r\n    );\r\n\r\n    event RedirectedBalanceUpdated(\r\n        address indexed _targetAddress,\r\n        uint256 _targetBalanceIncrease,\r\n        uint256 _targetIndex,\r\n        uint256 _redirectedBalanceAdded,\r\n        uint256 _redirectedBalanceRemoved\r\n    );\r\n\r\n    address public underlyingAssetAddress;\r\n    uint8 public underlyingAssetDecimals;\r\n\r\n    mapping (address => uint256) private userIndexes;\r\n\r\n    LendingPoolAddressesProvider private addressesProvider;\r\n    LendingPoolCore private core;\r\n    LendingPool private pool;\r\n    LendingPoolDataProvider private dataProvider;\r\n\r\n    modifier onlyLendingPool {\r\n        require (msg.sender == address(pool), \"The caller of this function must be a lending pool\");\r\n        _;\r\n    }\r\n\r\n    modifier whenTransferAllowed(address _from, uint256 _amount) {\r\n        require(isTransferAllowed(_from, _amount));\r\n        _;\r\n    }\r\n\r\n    constructor(\r\n        LendingPoolAddressesProvider _addressesProvider,\r\n        address _underlyingAsset,\r\n        uint8 _underlyingAssetDecimals,\r\n        string memory _name,\r\n        string memory _symbol\r\n    ) ERC20(_name, _symbol) {\r\n        addressesProvider = _addressesProvider;\r\n        core = LendingPoolCore(payable(addressesProvider.getLendingPoolCore()));\r\n        pool = LendingPool(addressesProvider.getLendingPool());\r\n        dataProvider = LendingPoolDataProvider(addressesProvider.getLendingPoolDataProvider());\r\n        underlyingAssetDecimals = _underlyingAssetDecimals;\r\n        underlyingAssetAddress = _underlyingAsset;\r\n    }\r\n\r\n    function decimals() public view override returns(uint8){\r\n        return underlyingAssetDecimals;\r\n    }\r\n\r\n    function _transfer(address _from, address _to, uint256 _amount) \r\n        internal \r\n        override \r\n        whenTransferAllowed(_from, _amount)\r\n    {\r\n        executeTransferInternal(_from, _to, _amount);\r\n    }\r\n\r\n\r\n    function redeem(uint256 _amount) external {\r\n        \r\n        require(_amount > 0, \"Amount to redeem needs to be greater than zero\");\r\n\r\n        (\r\n            ,\r\n            uint256 currentBalance,\r\n            uint256 balanceIncrease,\r\n            uint256 index \r\n        ) = cumulateBalanceInternal(msg.sender);\r\n\r\n        uint256 amountToRedeem = _amount;\r\n\r\n        if(_amount == UINT_MAX_VALUE) {\r\n            amountToRedeem = currentBalance;\r\n        }\r\n\r\n        require(amountToRedeem <= currentBalance, \"User cannot redeem more than the available balance\");\r\n\r\n        require(isTransferAllowed(msg.sender, amountToRedeem), \"Transfer cannot be allowed\");\r\n\r\n        //if the user is redirecting his interest towards someone else,\r\n        //we update the redirected balance of the redirection address by adding the accrued interest,\r\n        //and removing the amount to redeem\r\n        // updateRedirectedBalanceOfRedirectionAddressInternal(msg.sender, balanceIncrease, amountToRedeem);\r\n        \r\n        _burn(msg.sender, amountToRedeem);\r\n\r\n        bool userIndexReset = false;\r\n\r\n        if(currentBalance.sub(amountToRedeem) == 0) {\r\n            userIndexReset = resetDataOnZeroBalanceInternal(msg.sender);\r\n        }\r\n\r\n        pool.redeemUnderlying(\r\n            underlyingAssetAddress,\r\n            payable(msg.sender),\r\n            amountToRedeem,\r\n            currentBalance.sub(amountToRedeem)\r\n        );\r\n\r\n        emit Redeem(msg.sender, amountToRedeem, balanceIncrease, userIndexReset ? 0 : index);\r\n    }\r\n\r\n    function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool {\r\n\r\n        (\r\n            ,\r\n            ,\r\n            uint256 balanceIncrease,\r\n            uint256 index \r\n        ) = cumulateBalanceInternal(_account);\r\n        \r\n        //if the user is redirecting his interest towards someone else,\r\n        //we update the redirected balance of the redirection address by adding the accrued interest\r\n        //and the amount deposited\r\n        // updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);\r\n        \r\n        _mint(_account, _amount);\r\n\r\n        emit MintOnDeposit(_account, _amount, balanceIncrease, index);\r\n    }\r\n\r\n    function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool {\r\n\r\n        (\r\n            ,\r\n            uint256 accountBalance,\r\n            uint256 balanceIncrease,\r\n            uint256 index\r\n        ) = cumulateBalanceInternal(_account);\r\n\r\n        //adds the accrued interest and substracts the burned amount to\r\n        //the redirected balance\r\n        // updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value);\r\n\r\n        _burn(_account, _value);\r\n\r\n        bool userIndexReset = false;\r\n\r\n        if(accountBalance.sub(_value) == 0) {\r\n            userIndexReset = resetDataOnZeroBalanceInternal(_account);\r\n        }\r\n\r\n        emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index);\r\n    }\r\n\r\n    //transferOnLiquidation\r\n    function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool {\r\n        executeTransferInternal(_from, _to, _value);\r\n    }\r\n\r\n    function principalBalanceOf(address _user) external view returns(uint256) {\r\n        return super.balanceOf(_user);\r\n    }\r\n\r\n    function totalSupply() public override view returns(uint256) {\r\n        \r\n        uint256 currentSupplyPrincipal = super.totalSupply();\r\n\r\n        if(currentSupplyPrincipal == 0) {\r\n            return 0;\r\n        }\r\n\r\n        return currentSupplyPrincipal\r\n            .wadToRay()\r\n            .rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))\r\n            .rayToWad();\r\n    }\r\n\r\n    function isTransferAllowed(address _user, uint256 _amount) public view returns (bool) {\r\n        return dataProvider.balanceDecreaseAllowed(underlyingAssetAddress, _user, _amount);\r\n    }\r\n\r\n    function getUserIndex(address _user) external view returns(uint256) {\r\n        return userIndexes[_user];\r\n    }\r\n\r\n\r\n    function cumulateBalanceInternal(address _user)\r\n        internal\r\n        returns(uint256, uint256, uint256, uint256)\r\n    {\r\n        uint256 previousPrincipalBalance = super.balanceOf(_user);\r\n\r\n        //calculate the accrued interest since the last accumulation\r\n        uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);\r\n        //mints an amount of tokens equivalent to the amount accumulated\r\n        _mint(_user, balanceIncrease);\r\n        //updates the user index\r\n        uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);\r\n        return (\r\n            previousPrincipalBalance,\r\n            previousPrincipalBalance.add(balanceIncrease),\r\n            balanceIncrease,\r\n            index\r\n        );\r\n    }    \r\n\r\n    function calculateCumulatedBalanceInternal(\r\n        address _user,\r\n        uint256 _balance\r\n    ) internal view returns (uint256) {\r\n        return _balance\r\n            .wadToRay()\r\n            .rayMul(core.getReserveNormalizedIncome(underlyingAssetAddress))\r\n            .rayDiv(userIndexes[_user])\r\n            .rayToWad();\r\n    }\r\n\r\n    function executeTransferInternal(\r\n        address _from,\r\n        address _to,\r\n        uint256 _value\r\n    ) internal {\r\n        require(_value > 0, \"Transferred amount needs to be greater than zero\");\r\n\r\n        //cumulate the balance of the sender\r\n        (\r\n            ,\r\n            uint256 fromBalance,\r\n            uint256 fromBalanceIncrease,\r\n            uint256 fromIndex\r\n        ) = cumulateBalanceInternal(_from);\r\n\r\n        //cumulate the balance of the receiver\r\n        (\r\n            ,\r\n            ,\r\n            uint256 toBalanceIncrease,\r\n            uint256 toIndex\r\n        ) = cumulateBalanceInternal(_to);\r\n\r\n        //if the sender is redirecting his interest towards someone else,\r\n        //adds to the redirected balance the accrued interest and removes the amount\r\n        //being transferred\r\n        // updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value);\r\n\r\n        //if the receiver is redirecting his interest towards someone else,\r\n        //adds to the redirected balance the accrued interest and the amount\r\n        //being transferred\r\n        // updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0);\r\n\r\n        //performs the transfer\r\n        super._transfer(_from, _to, _value);\r\n\r\n        bool fromIndexReset = false;\r\n        //reset the user data if the remaining balance is 0\r\n        if(fromBalance.sub(_value) == 0) {\r\n            fromIndexReset = resetDataOnZeroBalanceInternal(_from);\r\n        }\r\n\r\n        emit BalanceTransfer(\r\n            _from,\r\n            _to,\r\n            _value,\r\n            fromBalanceIncrease,\r\n            toBalanceIncrease,\r\n            fromIndexReset ? 0 : fromIndex,\r\n            toIndex\r\n        );\r\n    }\r\n\r\n    function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) {\r\n        userIndexes[_user] = 0;\r\n        return true;\r\n    }\r\n\r\n    function balanceOf(address _user) public override view returns (uint256) {\r\n        uint256 currentPrincipalBalance = super.balanceOf(_user);\r\n        if (currentPrincipalBalance == 0) {\r\n            return 0;\r\n        }\r\n        return calculateCumulatedBalanceInternal(_user, currentPrincipalBalance);\r\n    }\r\n}"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 1000
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}