zellic-audit
Initial commit
f998fcd
raw
history blame
183 kB
{
"language": "Solidity",
"sources": {
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n /**\n * @dev 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 `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, 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 `sender` to `recipient` 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 sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\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"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n 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-upgradeable/token/ERC721/IERC721Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size > 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 functionCall(target, data, \"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 require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(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 require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason 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 // 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\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}\n"
},
"@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n */\nlibrary CountersUpgradeable {\n struct Counter {\n // This variable should never be directly accessed by users of the library: interactions must be restricted to\n // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n // this feature: see https://github.com/ethereum/solidity/issues/4637\n uint256 _value; // default: 0\n }\n\n function current(Counter storage counter) internal view returns (uint256) {\n return counter._value;\n }\n\n function increment(Counter storage counter) internal {\n unchecked {\n counter._value += 1;\n }\n }\n\n function decrement(Counter storage counter) internal {\n uint256 value = counter._value;\n require(value > 0, \"Counter: decrement overflow\");\n unchecked {\n counter._value = value - 1;\n }\n }\n\n function reset(Counter storage counter) internal {\n counter._value = 0;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (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 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 `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, 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 `sender` to `recipient` 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 sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\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"
},
"contracts/interfaces/IDebtToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {ILendPoolAddressesProvider} from \"../interfaces/ILendPoolAddressesProvider.sol\";\nimport {IIncentivesController} from \"./IIncentivesController.sol\";\nimport {IScaledBalanceToken} from \"./IScaledBalanceToken.sol\";\n\nimport {IERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport {IERC20MetadataUpgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/**\n * @title IDebtToken\n * @author Unlockd\n * @notice Defines the basic interface for a debt token.\n **/\ninterface IDebtToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable {\n /**\n * @dev Emitted when a debt token is initialized\n * @param underlyingAsset The address of the underlying asset\n * @param pool The address of the associated lend pool\n * @param incentivesController The address of the incentives controller\n * @param debtTokenDecimals the decimals of the debt token\n * @param debtTokenName the name of the debt token\n * @param debtTokenSymbol the symbol of the debt token\n **/\n event Initialized(\n address indexed underlyingAsset,\n address indexed pool,\n address incentivesController,\n uint8 debtTokenDecimals,\n string debtTokenName,\n string debtTokenSymbol\n );\n\n /**\n * @dev Initializes the debt token.\n * @param addressProvider The address of the lend pool\n * @param underlyingAsset The address of the underlying asset\n * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's\n * @param debtTokenName The name of the token\n * @param debtTokenSymbol The symbol of the token\n */\n function initialize(\n ILendPoolAddressesProvider addressProvider,\n address underlyingAsset,\n uint8 debtTokenDecimals,\n string memory debtTokenName,\n string memory debtTokenSymbol\n ) external;\n\n /**\n * @dev Emitted after the mint action\n * @param from The address performing the mint\n * @param value The amount to be minted\n * @param index The last index of the reserve\n **/\n event Mint(address indexed from, uint256 value, uint256 index);\n\n /**\n * @dev Mints debt token to the `user` address\n * @param user The address receiving the borrowed underlying\n * @param onBehalfOf The beneficiary of the mint\n * @param amount The amount of debt being minted\n * @param index The variable debt index of the reserve\n * @return `true` if the the previous balance of the user is 0\n **/\n function mint(\n address user,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) external returns (bool);\n\n /**\n * @dev Emitted when variable debt is burnt\n * @param user The user which debt has been burned\n * @param amount The amount of debt being burned\n * @param index The index of the user\n **/\n event Burn(address indexed user, uint256 amount, uint256 index);\n\n /**\n * @dev Burns user variable debt\n * @param user The user which debt is burnt\n * @param amount The amount to be burnt\n * @param index The variable debt index of the reserve\n **/\n function burn(\n address user,\n uint256 amount,\n uint256 index\n ) external;\n\n /**\n * @dev Returns the address of the incentives controller contract\n **/\n function getIncentivesController() external view returns (IIncentivesController);\n\n /**\n * @dev delegates borrowing power to a user on the specific debt token\n * @param delegatee the address receiving the delegated borrowing power\n * @param amount the maximum amount being delegated. Delegation will still\n * respect the liquidation constraints (even if delegated, a delegatee cannot\n * force a delegator HF to go below 1)\n **/\n function approveDelegation(address delegatee, uint256 amount) external;\n\n /**\n * @dev returns the borrow allowance of the user\n * @param fromUser The user to giving allowance\n * @param toUser The user to give allowance to\n * @return the current allowance of toUser\n **/\n function borrowAllowance(address fromUser, address toUser) external view returns (uint256);\n}\n"
},
"contracts/interfaces/IIncentivesController.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\ninterface IIncentivesController {\n /**\n * @dev Called by the corresponding asset on any update that affects the rewards distribution\n * @param asset The address of the user\n * @param totalSupply The total supply of the asset in the lending pool\n * @param userBalance The balance of the user of the asset in the lending pool\n **/\n function handleAction(\n address asset,\n uint256 totalSupply,\n uint256 userBalance\n ) external;\n}\n"
},
"contracts/interfaces/IInterestRate.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\n/**\n * @title IInterestRate interface\n * @dev Interface for the calculation of the interest rates\n * @author Unlockd\n */\ninterface IInterestRate {\n /**\n * @dev Get the variable borrow rate\n * @return the base variable borrow rate\n **/\n function baseVariableBorrowRate() external view returns (uint256);\n\n /**\n * @dev Get the maximum variable borrow rate\n * @return the maximum variable borrow rate\n **/\n function getMaxVariableBorrowRate() external view returns (uint256);\n\n /**\n * @dev Calculates the interest rates depending on the reserve's state and configurations\n * @param reserve The address of the reserve\n * @param availableLiquidity The available liquidity for the reserve\n * @param totalVariableDebt The total borrowed from the reserve at a variable rate\n * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market\n **/\n function calculateInterestRates(\n address reserve,\n uint256 availableLiquidity,\n uint256 totalVariableDebt,\n uint256 reserveFactor\n ) external view returns (uint256, uint256);\n\n /**\n * @dev Calculates the interest rates depending on the reserve's state and configurations\n * @param reserve The address of the reserve\n * @param uToken The uToken address\n * @param liquidityAdded The liquidity added during the operation\n * @param liquidityTaken The liquidity taken during the operation\n * @param totalVariableDebt The total borrowed from the reserve at a variable rate\n * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market\n **/\n function calculateInterestRates(\n address reserve,\n address uToken,\n uint256 liquidityAdded,\n uint256 liquidityTaken,\n uint256 totalVariableDebt,\n uint256 reserveFactor\n ) external view returns (uint256 liquidityRate, uint256 variableBorrowRate);\n}\n"
},
"contracts/interfaces/ILendPool.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {ILendPoolAddressesProvider} from \"./ILendPoolAddressesProvider.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC721Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\n\nimport {DataTypes} from \"../libraries/types/DataTypes.sol\";\n\ninterface ILendPool {\n /**\n * @dev Emitted when _rescuer is modified in the LendPool\n * @param newRescuer The address of the new rescuer\n **/\n event RescuerChanged(address indexed newRescuer);\n\n /**\n * @dev Emitted on deposit()\n * @param user The address initiating the deposit\n * @param amount The amount deposited\n * @param reserve The address of the underlying asset of the reserve\n * @param onBehalfOf The beneficiary of the deposit, receiving the uTokens\n * @param referral The referral code used\n **/\n event Deposit(\n address user,\n address indexed reserve,\n uint256 amount,\n address indexed onBehalfOf,\n uint16 indexed referral\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param user The address initiating the withdrawal, owner of uTokens\n * @param reserve The address of the underlyng asset being withdrawn\n * @param amount The amount to be withdrawn\n * @param to Address that will receive the underlying\n **/\n event Withdraw(address indexed user, address indexed reserve, uint256 amount, address indexed to);\n\n /**\n * @dev Emitted on borrow() when loan needs to be opened\n * @param user The address of the user initiating the borrow(), receiving the funds\n * @param reserve The address of the underlying asset being borrowed\n * @param amount The amount borrowed out\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token id of the underlying NFT used as collateral\n * @param onBehalfOf The address that will be getting the loan\n * @param referral The referral code used\n * @param nftConfigFee an estimated gas cost fee for configuring the NFT\n **/\n event Borrow(\n address user,\n address indexed reserve,\n uint256 amount,\n address nftAsset,\n uint256 nftTokenId,\n address indexed onBehalfOf,\n uint256 borrowRate,\n uint256 loanId,\n uint16 indexed referral,\n uint256 nftConfigFee\n );\n\n /**\n * @dev Emitted on repay()\n * @param user The address of the user initiating the repay(), providing the funds\n * @param reserve The address of the underlying asset of the reserve\n * @param amount The amount repaid\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token id of the underlying NFT used as collateral\n * @param borrower The beneficiary of the repayment, getting his debt reduced\n * @param loanId The loan ID of the NFT loans\n **/\n event Repay(\n address user,\n address indexed reserve,\n uint256 amount,\n address indexed nftAsset,\n uint256 nftTokenId,\n address indexed borrower,\n uint256 loanId\n );\n\n /**\n * @dev Emitted when a borrower's loan is auctioned.\n * @param user The address of the user initiating the auction\n * @param reserve The address of the underlying asset of the reserve\n * @param bidPrice The price of the underlying reserve given by the bidder\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token id of the underlying NFT used as collateral\n * @param onBehalfOf The address that will be getting the NFT\n * @param loanId The loan ID of the NFT loans\n **/\n event Auction(\n address user,\n address indexed reserve,\n uint256 bidPrice,\n address indexed nftAsset,\n uint256 nftTokenId,\n address onBehalfOf,\n address indexed borrower,\n uint256 loanId\n );\n\n /**\n * @dev Emitted on redeem()\n * @param user The address of the user initiating the redeem(), providing the funds\n * @param reserve The address of the underlying asset of the reserve\n * @param borrowAmount The borrow amount repaid\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token id of the underlying NFT used as collateral\n * @param loanId The loan ID of the NFT loans\n **/\n event Redeem(\n address user,\n address indexed reserve,\n uint256 borrowAmount,\n uint256 fineAmount,\n address indexed nftAsset,\n uint256 nftTokenId,\n address indexed borrower,\n uint256 loanId\n );\n\n /**\n * @dev Emitted when a borrower's loan is liquidated.\n * @param user The address of the user initiating the auction\n * @param reserve The address of the underlying asset of the reserve\n * @param repayAmount The amount of reserve repaid by the liquidator\n * @param remainAmount The amount of reserve received by the borrower\n * @param loanId The loan ID of the NFT loans\n **/\n event Liquidate(\n address user,\n address indexed reserve,\n uint256 repayAmount,\n uint256 remainAmount,\n address indexed nftAsset,\n uint256 nftTokenId,\n address indexed borrower,\n uint256 loanId\n );\n\n /**\n * @dev Emitted when a borrower's loan is liquidated on NFTX.\n * @param reserve The address of the underlying asset of the reserve\n * @param repayAmount The amount of reserve repaid by the liquidator\n * @param remainAmount The amount of reserve received by the borrower\n * @param loanId The loan ID of the NFT loans\n **/\n event LiquidateNFTX(\n address indexed reserve,\n uint256 repayAmount,\n uint256 remainAmount,\n address indexed nftAsset,\n uint256 nftTokenId,\n address indexed borrower,\n uint256 loanId\n );\n /**\n * @dev Emitted when an NFT configuration is triggered.\n * @param user The NFT holder\n * @param nftAsset The NFT collection address\n * @param nftTokenId The NFT token Id\n **/\n event ValuationApproved(address indexed user, address indexed nftAsset, uint256 indexed nftTokenId);\n /**\n * @dev Emitted when the pause is triggered.\n */\n event Paused();\n\n /**\n * @dev Emitted when the pause is lifted.\n */\n event Unpaused();\n\n /**\n * @dev Emitted when the pause time is updated.\n */\n event PausedTimeUpdated(uint256 startTime, uint256 durationTime);\n\n /**\n * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared\n * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,\n * the event will actually be fired by the LendPool contract. The event is therefore replicated here so it\n * gets added to the LendPool ABI\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The new liquidity rate\n * @param variableBorrowRate The new variable borrow rate\n * @param liquidityIndex The new liquidity index\n * @param variableBorrowIndex The new variable borrow index\n **/\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n @dev Emitted after the address of the interest rate strategy contract has been updated\n */\n event ReserveInterestRateAddressChanged(address indexed asset, address indexed rateAddress);\n\n /**\n @dev Emitted after setting the configuration bitmap of the reserve as a whole\n */\n event ReserveConfigurationChanged(address indexed asset, uint256 configuration);\n\n /**\n @dev Emitted after setting the configuration bitmap of the NFT collection as a whole\n */\n event NftConfigurationChanged(address indexed asset, uint256 configuration);\n\n /**\n @dev Emitted after setting the configuration bitmap of the NFT as a whole\n */\n event NftConfigurationByIdChanged(address indexed asset, uint256 indexed nftTokenId, uint256 configuration);\n\n /**\n @dev Emitted after setting the new safe health factor value for redeems\n */\n event SafeHealthFactorUpdated(uint256 indexed newSafeHealthFactor);\n\n /**\n @dev Emitted after setting the new treasury address on the specified uToken\n */\n event TreasuryAddressUpdated(address indexed uToken, address indexed treasury);\n\n /**\n * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying uTokens.\n * - E.g. User deposits 100 USDC and gets in return 100 uusdc\n * @param reserve The address of the underlying asset to deposit\n * @param amount The amount to be deposited\n * @param onBehalfOf The address that will receive the uTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of uTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function deposit(address reserve, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n\n /**\n * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent uTokens owned\n * E.g. User has 100 uusdc, calls withdraw() and receives 100 USDC, burning the 100 uusdc\n * @param reserve The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole uToken balance\n * @param to Address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n **/\n function withdraw(address reserve, uint256 amount, address to) external returns (uint256);\n\n /**\n * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already deposited enough collateral\n * - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet\n * and lock collateral asset in contract\n * @param reserveAsset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n * @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function borrow(\n address reserveAsset,\n uint256 amount,\n address nftAsset,\n uint256 nftTokenId,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned\n * - E.g. User repays 100 USDC, burning loan and receives collateral asset\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n * @param amount The amount to repay\n * @return The final amount repaid, loan is burned or not\n **/\n function repay(address nftAsset, uint256 nftTokenId, uint256 amount) external returns (uint256, bool);\n\n /**\n * @dev Function to auction a non-healthy position collateral-wise\n * - The caller (liquidator) want to buy collateral asset of the user getting liquidated\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n * @param bidPrice The bid price of the liquidator want to buy the underlying NFT\n * @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of NFT\n * is a different wallet\n **/\n function auction(address nftAsset, uint256 nftTokenId, uint256 bidPrice, address onBehalfOf) external;\n\n /**\n * @notice Redeem a NFT loan which state is in Auction\n * - E.g. User repays 100 USDC, burning loan and receives collateral asset\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n * @param amount The amount to repay the debt\n * @param bidFine The amount of bid fine\n **/\n function redeem(address nftAsset, uint256 nftTokenId, uint256 amount, uint256 bidFine) external returns (uint256);\n\n /**\n * @dev Function to liquidate a non-healthy position collateral-wise\n * - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives\n * the collateral asset\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n **/\n function liquidate(address nftAsset, uint256 nftTokenId, uint256 amount) external returns (uint256);\n\n /**\n * @dev Function to liquidate a non-healthy position collateral-wise\n * - The collateral asset is sold on NFTX & Sushiswap\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n **/\n function liquidateNFTX(address nftAsset, uint256 nftTokenId, uint256 amountOutMin) external returns (uint256);\n\n /**\n * @dev Function to liquidate a non-healthy position collateral-wise\n * - The collateral asset is sold on NFTX & Sushiswap\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n **/\n function liquidateSudoSwap(\n address nftAsset,\n uint256 nftTokenId,\n uint256 amountOutMin,\n address LSSVMPair,\n uint256 amountOutMinSudoswap\n ) external returns (uint256);\n\n /**\n * @dev Approves valuation of an NFT for a user\n * @dev Just the NFT holder can trigger the configuration\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n **/\n function approveValuation(address nftAsset, uint256 nftTokenId) external payable;\n\n /**\n * @dev Validates and finalizes an uToken transfer\n * - Only callable by the overlying uToken of the `asset`\n * @param asset The address of the underlying asset of the uToken\n * @param from The user from which the uTokens are transferred\n * @param to The user receiving the uTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The uToken balance of the `from` user before the transfer\n * @param balanceToBefore The uToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external view;\n\n /**\n * @dev Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n **/\n function getReserveConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @dev Returns the configuration of the NFT\n * @param asset The address of the asset of the NFT\n * @return The configuration of the NFT\n **/\n function getNftConfiguration(address asset) external view returns (DataTypes.NftConfigurationMap memory);\n\n /**\n * @dev Returns the configuration of the NFT\n * @param asset The address of the asset of the NFT\n * @param tokenId the Token Id of the NFT\n * @return The configuration of the NFT\n **/\n function getNftConfigByTokenId(\n address asset,\n uint256 tokenId\n ) external view returns (DataTypes.NftConfigurationMap memory);\n\n /**\n * @dev Returns the normalized income normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset) external view returns (uint256);\n\n /**\n * @dev Returns the normalized variable debt per unit of asset\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);\n\n /**\n * @dev Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state of the reserve\n **/\n function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);\n\n /**\n * @dev Returns the list of the initialized reserves\n * @return the list of initialized reserves\n **/\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @dev Returns the state and configuration of the nft\n * @param asset The address of the underlying asset of the nft\n * @return The status of the nft\n **/\n function getNftData(address asset) external view returns (DataTypes.NftData memory);\n\n /**\n * @dev Returns the configuration of the nft asset\n * @param asset The address of the underlying asset of the nft\n * @param tokenId NFT asset ID\n * @return The configuration of the nft asset\n **/\n function getNftAssetConfig(\n address asset,\n uint256 tokenId\n ) external view returns (DataTypes.NftConfigurationMap memory);\n\n /**\n * @dev Returns the loan data of the NFT\n * @param nftAsset The address of the NFT\n * @param reserveAsset The address of the Reserve\n * @return totalCollateralInETH the total collateral in ETH of the NFT\n * @return totalCollateralInReserve the total collateral in Reserve of the NFT\n * @return availableBorrowsInETH the borrowing power in ETH of the NFT\n * @return availableBorrowsInReserve the borrowing power in Reserve of the NFT\n * @return ltv the loan to value of the user\n * @return liquidationThreshold the liquidation threshold of the NFT\n * @return liquidationBonus the liquidation bonus of the NFT\n **/\n function getNftCollateralData(\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset\n )\n external\n view\n returns (\n uint256 totalCollateralInETH,\n uint256 totalCollateralInReserve,\n uint256 availableBorrowsInETH,\n uint256 availableBorrowsInReserve,\n uint256 ltv,\n uint256 liquidationThreshold,\n uint256 liquidationBonus\n );\n\n /**\n * @dev Returns the debt data of the NFT\n * @param nftAsset The address of the NFT\n * @param nftTokenId The token id of the NFT\n * @return loanId the loan id of the NFT\n * @return reserveAsset the address of the Reserve\n * @return totalCollateral the total power of the NFT\n * @return totalDebt the total debt of the NFT\n * @return availableBorrows the borrowing power left of the NFT\n * @return healthFactor the current health factor of the NFT\n **/\n function getNftDebtData(\n address nftAsset,\n uint256 nftTokenId\n )\n external\n view\n returns (\n uint256 loanId,\n address reserveAsset,\n uint256 totalCollateral,\n uint256 totalDebt,\n uint256 availableBorrows,\n uint256 healthFactor\n );\n\n /**\n * @dev Returns the auction data of the NFT\n * @param nftAsset The address of the NFT\n * @param nftTokenId The token id of the NFT\n * @return loanId the loan id of the NFT\n * @return bidderAddress the highest bidder address of the loan\n * @return bidPrice the highest bid price in Reserve of the loan\n * @return bidBorrowAmount the borrow amount in Reserve of the loan\n * @return bidFine the penalty fine of the loan\n **/\n function getNftAuctionData(\n address nftAsset,\n uint256 nftTokenId\n )\n external\n view\n returns (uint256 loanId, address bidderAddress, uint256 bidPrice, uint256 bidBorrowAmount, uint256 bidFine);\n\n /**\n * @dev Returns the state and configuration of the nft\n * @param nftAsset The address of the underlying asset of the nft\n * @param nftAsset The token ID of the asset\n **/\n function getNftLiquidatePrice(\n address nftAsset,\n uint256 nftTokenId\n ) external view returns (uint256 liquidatePrice, uint256 paybackAmount);\n\n /**\n * @dev Returns the list of nft addresses in the protocol\n **/\n function getNftsList() external view returns (address[] memory);\n\n /**\n * @dev Set the _pause state of a reserve\n * - Only callable by the LendPool contract\n * @param val `true` to pause the reserve, `false` to un-pause it\n */\n function setPause(bool val) external;\n\n function setPausedTime(uint256 startTime, uint256 durationTime) external;\n\n /**\n * @dev Returns if the LendPool is paused\n */\n function paused() external view returns (bool);\n\n function getPausedTime() external view returns (uint256, uint256);\n\n /**\n * @dev Returns the cached LendPoolAddressesProvider connected to this contract\n **/\n\n function getAddressesProvider() external view returns (ILendPoolAddressesProvider);\n\n /**\n * @dev Initializes a reserve, activating it, assigning an uToken and nft loan and an\n * interest rate strategy\n * - Only callable by the LendPoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param uTokenAddress The address of the uToken that will be assigned to the reserve\n * @param debtTokenAddress The address of the debtToken that will be assigned to the reserve\n * @param interestRateAddress The address of the interest rate strategy contract\n **/\n function initReserve(\n address asset,\n address uTokenAddress,\n address debtTokenAddress,\n address interestRateAddress\n ) external;\n\n /**\n * @dev Initializes a nft, activating it, assigning nft loan and an\n * interest rate strategy\n * - Only callable by the LendPoolConfigurator contract\n * @param asset The address of the underlying asset of the nft\n **/\n function initNft(address asset, address uNftAddress) external;\n\n /**\n * @dev Updates the address of the interest rate strategy contract\n * - Only callable by the LendPoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateAddress The address of the interest rate strategy contract\n **/\n function setReserveInterestRateAddress(address asset, address rateAddress) external;\n\n /**\n * @dev Sets the configuration bitmap of the reserve as a whole\n * - Only callable by the LendPoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n **/\n function setReserveConfiguration(address asset, uint256 configuration) external;\n\n /**\n * @dev Sets the configuration bitmap of the NFT as a whole\n * - Only callable by the LendPoolConfigurator contract\n * @param asset The address of the asset of the NFT\n * @param configuration The new configuration bitmap\n **/\n function setNftConfiguration(address asset, uint256 configuration) external;\n\n /**\n * @dev Sets the configuration bitmap of the NFT as a whole\n * - Only callable by the LendPoolConfigurator contract\n * @param asset The address of the asset of the NFT\n * @param nftTokenId the NFT tokenId\n * @param configuration The new configuration bitmap\n **/\n function setNftConfigByTokenId(address asset, uint256 nftTokenId, uint256 configuration) external;\n\n /**\n * @dev Sets the max supply and token ID for a given asset\n * @param asset The address to set the data\n * @param maxSupply The max supply value\n * @param maxTokenId The max token ID value\n **/\n function setNftMaxSupplyAndTokenId(address asset, uint256 maxSupply, uint256 maxTokenId) external;\n\n /**\n * @dev Sets the max number of reserves in the protocol\n * @param val the value to set the max number of reserves\n **/\n function setMaxNumberOfReserves(uint256 val) external;\n\n /**\n * @dev Sets the max number of NFTs in the protocol\n * @param val the value to set the max number of NFTs\n **/\n function setMaxNumberOfNfts(uint256 val) external;\n\n /**\n * @notice Assigns the rescuer role to a given address.\n * @param newRescuer New rescuer's address\n */\n function updateRescuer(address newRescuer) external;\n\n /**\n * @notice Update the safe health factor value for redeems\n * @param newSafeHealthFactor New safe health factor value\n */\n function updateSafeHealthFactor(uint256 newSafeHealthFactor) external;\n\n /**\n * @dev Sets new treasury to the specified UToken\n * @param uToken the utoken to update the treasury address to\n * @param treasury the new treasury address\n **/\n function setTreasuryAddress(address uToken, address treasury) external;\n\n /**\n * @notice Rescue tokens or ETH locked up in this contract.\n * @param tokenContract ERC20 token contract address\n * @param to Recipient address\n * @param amount Amount to withdraw\n * @param rescueETH bool to know if we want to rescue ETH or other token\n */\n function rescue(IERC20 tokenContract, address to, uint256 amount, bool rescueETH) external;\n\n /**\n * @notice Rescue NFTs locked up in this contract.\n * @param nftAsset ERC721 asset contract address\n * @param tokenId ERC721 token id\n * @param to Recipient address\n */\n function rescueNFT(IERC721Upgradeable nftAsset, uint256 tokenId, address to) external;\n\n /**\n * @dev Sets the fee percentage for liquidations\n * @param percentage the fee percentage to be set\n **/\n function setLiquidateFeePercentage(uint256 percentage) external;\n\n /**\n * @dev Sets the max timeframe between NFT config triggers and borrows\n * @param timeframe the number of seconds for the timeframe\n **/\n function setTimeframe(uint256 timeframe) external;\n\n /**\n * @dev Adds and address to be allowed to sell on NFTX\n * @param nftAsset the nft address of the NFT to sell\n * @param val if true is allowed to sell if false is not\n **/\n function setIsMarketSupported(address nftAsset, uint8 market, bool val) external;\n\n /**\n * @dev sets the fee for configuringNFTAsCollateral\n * @param configFee the amount to charge to the user\n **/\n function setConfigFee(uint256 configFee) external;\n\n /**\n * @dev sets the fee to be charged on first bid on nft\n * @param auctionDurationConfigFee the amount to charge to the user\n **/\n function setAuctionDurationConfigFee(uint256 auctionDurationConfigFee) external;\n\n /**\n * @dev Returns the maximum number of reserves supported to be listed in this LendPool\n */\n function getMaxNumberOfReserves() external view returns (uint256);\n\n /**\n * @dev Returns the maximum number of nfts supported to be listed in this LendPool\n */\n function getMaxNumberOfNfts() external view returns (uint256);\n\n /**\n * @dev Returns the fee percentage for liquidations\n **/\n function getLiquidateFeePercentage() external view returns (uint256);\n\n /**\n * @notice Returns current rescuer\n * @return Rescuer's address\n */\n function rescuer() external view returns (address);\n\n /**\n * @notice Returns current safe health factor\n * @return The safe health factor value\n */\n function getSafeHealthFactor() external view returns (uint256);\n\n /**\n * @dev Returns the max timeframe between NFT config triggers and borrows\n **/\n function getTimeframe() external view returns (uint256);\n\n /**\n * @dev Returns the configFee amount\n **/\n function getConfigFee() external view returns (uint256);\n\n /**\n * @dev Returns the auctionDurationConfigFee amount\n **/\n function getAuctionDurationConfigFee() external view returns (uint256);\n\n /**\n * @dev Returns if the address is allowed to sell or not on NFTX\n */\n function getIsMarketSupported(address nftAsset, uint8 market) external view returns (bool);\n}\n"
},
"contracts/interfaces/ILendPoolAddressesProvider.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\n/**\n * @title LendPoolAddressesProvider contract\n * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles\n * - Acting also as factory of proxies and admin of those, so with right to change its implementations\n * - Owned by the Unlockd Governance\n * @author Unlockd\n **/\ninterface ILendPoolAddressesProvider {\n event MarketIdSet(string newMarketId);\n event LendPoolUpdated(address indexed newAddress, bytes encodedCallData);\n event ConfigurationAdminUpdated(address indexed newAddress);\n event EmergencyAdminUpdated(address indexed newAddress);\n event LendPoolConfiguratorUpdated(address indexed newAddress, bytes encodedCallData);\n event ReserveOracleUpdated(address indexed newAddress);\n event NftOracleUpdated(address indexed newAddress);\n event LendPoolLoanUpdated(address indexed newAddress, bytes encodedCallData);\n event ProxyCreated(bytes32 id, address indexed newAddress);\n event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy, bytes encodedCallData);\n event UNFTRegistryUpdated(address indexed newAddress);\n event IncentivesControllerUpdated(address indexed newAddress);\n event UIDataProviderUpdated(address indexed newAddress);\n event UnlockdDataProviderUpdated(address indexed newAddress);\n event WalletBalanceProviderUpdated(address indexed newAddress);\n event NFTXVaultFactoryUpdated(address indexed newAddress);\n event SushiSwapRouterUpdated(address indexed newAddress);\n event LSSVMRouterUpdated(address indexed newAddress);\n event LendPoolLiquidatorUpdated(address indexed newAddress);\n event LtvManagerUpdated(address indexed newAddress);\n\n /**\n * @dev Returns the id of the Unlockd market to which this contracts points to\n * @return The market id\n **/\n function getMarketId() external view returns (string memory);\n\n /**\n * @dev Allows to set the market which this LendPoolAddressesProvider represents\n * @param marketId The market id\n */\n function setMarketId(string calldata marketId) external;\n\n /**\n * @dev Sets an address for an id replacing the address saved in the addresses map\n * IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @dev General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `implementationAddress`\n * IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param impl The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address impl, bytes memory encodedCallData) external;\n\n /**\n * @dev Returns an address by id\n * @return The address\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @dev Returns the address of the LendPool proxy\n * @return The LendPool proxy address\n **/\n function getLendPool() external view returns (address);\n\n /**\n * @dev Updates the implementation of the LendPool, or creates the proxy\n * setting the new `pool` implementation on the first time calling it\n * @param pool The new LendPool implementation\n * @param encodedCallData calldata to execute\n **/\n function setLendPoolImpl(address pool, bytes memory encodedCallData) external;\n\n /**\n * @dev Returns the address of the LendPoolConfigurator proxy\n * @return The LendPoolConfigurator proxy address\n **/\n function getLendPoolConfigurator() external view returns (address);\n\n /**\n * @dev Updates the implementation of the LendPoolConfigurator, or creates the proxy\n * setting the new `configurator` implementation on the first time calling it\n * @param configurator The new LendPoolConfigurator implementation\n * @param encodedCallData calldata to execute\n **/\n function setLendPoolConfiguratorImpl(address configurator, bytes memory encodedCallData) external;\n\n /**\n * @dev returns the address of the LendPool admin\n * @return the LendPoolAdmin address\n **/\n function getPoolAdmin() external view returns (address);\n\n /**\n * @dev sets the address of the LendPool admin\n * @param admin the LendPoolAdmin address\n **/\n function setPoolAdmin(address admin) external;\n\n /**\n * @dev returns the address of the emergency admin\n * @return the EmergencyAdmin address\n **/\n function getEmergencyAdmin() external view returns (address);\n\n /**\n * @dev sets the address of the emergency admin\n * @param admin the EmergencyAdmin address\n **/\n function setEmergencyAdmin(address admin) external;\n\n /**\n * @dev returns the address of the reserve oracle\n * @return the ReserveOracle address\n **/\n function getReserveOracle() external view returns (address);\n\n /**\n * @dev sets the address of the reserve oracle\n * @param reserveOracle the ReserveOracle address\n **/\n function setReserveOracle(address reserveOracle) external;\n\n /**\n * @dev returns the address of the NFT oracle\n * @return the NFTOracle address\n **/\n function getNFTOracle() external view returns (address);\n\n /**\n * @dev sets the address of the NFT oracle\n * @param nftOracle the NFTOracle address\n **/\n function setNFTOracle(address nftOracle) external;\n\n /**\n * @dev returns the address of the lendpool loan\n * @return the LendPoolLoan address\n **/\n function getLendPoolLoan() external view returns (address);\n\n /**\n * @dev sets the address of the lendpool loan\n * @param loan the LendPoolLoan address\n * @param encodedCallData calldata to execute\n **/\n function setLendPoolLoanImpl(address loan, bytes memory encodedCallData) external;\n\n /**\n * @dev returns the address of the UNFT Registry\n * @return the UNFTRegistry address\n **/\n function getUNFTRegistry() external view returns (address);\n\n /**\n * @dev sets the address of the UNFT registry\n * @param factory the UNFTRegistry address\n **/\n function setUNFTRegistry(address factory) external;\n\n /**\n * @dev returns the address of the incentives controller\n * @return the IncentivesController address\n **/\n function getIncentivesController() external view returns (address);\n\n /**\n * @dev sets the address of the incentives controller\n * @param controller the IncentivesController address\n **/\n function setIncentivesController(address controller) external;\n\n /**\n * @dev returns the address of the UI data provider\n * @return the UIDataProvider address\n **/\n function getUIDataProvider() external view returns (address);\n\n /**\n * @dev sets the address of the UI data provider\n * @param provider the UIDataProvider address\n **/\n function setUIDataProvider(address provider) external;\n\n /**\n * @dev returns the address of the Unlockd data provider\n * @return the UnlockdDataProvider address\n **/\n function getUnlockdDataProvider() external view returns (address);\n\n /**\n * @dev sets the address of the Unlockd data provider\n * @param provider the UnlockdDataProvider address\n **/\n function setUnlockdDataProvider(address provider) external;\n\n /**\n * @dev returns the address of the wallet balance provider\n * @return the WalletBalanceProvider address\n **/\n function getWalletBalanceProvider() external view returns (address);\n\n /**\n * @dev sets the address of the wallet balance provider\n * @param provider the WalletBalanceProvider address\n **/\n function setWalletBalanceProvider(address provider) external;\n\n function getNFTXVaultFactory() external view returns (address);\n\n /**\n * @dev sets the address of the NFTXVault Factory contract\n * @param factory the NFTXVault Factory address\n **/\n function setNFTXVaultFactory(address factory) external;\n\n /**\n * @dev returns the address of the SushiSwap router contract\n **/\n function getSushiSwapRouter() external view returns (address);\n\n /**\n * @dev sets the address of the LSSVM router contract\n * @param router the LSSVM router address\n **/\n function setSushiSwapRouter(address router) external;\n\n /**\n * @dev returns the address of the LSSVM router contract\n **/\n function getLSSVMRouter() external view returns (address);\n\n /**\n * @dev sets the address of the LSSVM router contract\n * @param router the SushiSwap router address\n **/\n function setLSSVMRouter(address router) external;\n\n /**\n * @dev returns the address of the LendPool liquidator contract\n **/\n function getLendPoolLiquidator() external view returns (address);\n\n /**\n * @dev sets the address of the LendPool liquidator contract\n * @param liquidator the LendPool liquidator address\n **/\n function setLendPoolLiquidator(address liquidator) external;\n}\n"
},
"contracts/interfaces/ILendPoolLoan.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {DataTypes} from \"../libraries/types/DataTypes.sol\";\nimport {CountersUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol\";\n\ninterface ILendPoolLoan {\n /**\n * @dev Emitted on initialization to share location of dependent notes\n * @param pool The address of the associated lend pool\n */\n event Initialized(address indexed pool);\n\n /**\n * @dev Emitted when a loan is created\n * @param user The address initiating the action\n */\n event LoanCreated(\n address indexed user,\n address indexed onBehalfOf,\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset,\n uint256 amount,\n uint256 borrowIndex\n );\n\n /**\n * @dev Emitted when a loan is updated\n * @param user The address initiating the action\n */\n event LoanUpdated(\n address indexed user,\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset,\n uint256 amountAdded,\n uint256 amountTaken,\n uint256 borrowIndex\n );\n\n /**\n * @dev Emitted when a loan is repaid by the borrower\n * @param user The address initiating the action\n */\n event LoanRepaid(\n address indexed user,\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset,\n uint256 amount,\n uint256 borrowIndex\n );\n\n /**\n * @dev Emitted when a loan is auction by the liquidator\n * @param user The address initiating the action\n */\n event LoanAuctioned(\n address indexed user,\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n uint256 amount,\n uint256 borrowIndex,\n address bidder,\n uint256 price,\n address previousBidder,\n uint256 previousPrice\n );\n\n /**\n * @dev Emitted when a loan is redeemed\n * @param user The address initiating the action\n */\n event LoanRedeemed(\n address indexed user,\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset,\n uint256 amountTaken,\n uint256 borrowIndex\n );\n\n /**\n * @dev Emitted when a loan is liquidate by the liquidator\n * @param user The address initiating the action\n */\n event LoanLiquidated(\n address indexed user,\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset,\n uint256 amount,\n uint256 borrowIndex\n );\n\n /**\n * @dev Emitted when a loan is liquidate on NFTX\n */\n event LoanLiquidatedNFTX(\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset,\n uint256 amount,\n uint256 borrowIndex,\n uint256 sellPrice\n );\n\n /**\n * @dev Emitted when a loan is liquidate on SudoSwap\n */\n event LoanLiquidatedSudoSwap(\n uint256 indexed loanId,\n address nftAsset,\n uint256 nftTokenId,\n address reserveAsset,\n uint256 amount,\n uint256 borrowIndex,\n uint256 sellPrice,\n address LSSVMPair\n );\n\n function initNft(address nftAsset, address uNftAddress) external;\n\n /**\n * @dev Create store a loan object with some params\n * @param initiator The address of the user initiating the borrow\n * @param onBehalfOf The address receiving the loan\n * @param nftAsset The address of the underlying NFT asset\n * @param nftTokenId The token Id of the underlying NFT asset\n * @param uNftAddress The address of the uNFT token\n * @param reserveAsset The address of the underlying reserve asset\n * @param amount The loan amount\n * @param borrowIndex The index to get the scaled loan amount\n */\n function createLoan(\n address initiator,\n address onBehalfOf,\n address nftAsset,\n uint256 nftTokenId,\n address uNftAddress,\n address reserveAsset,\n uint256 amount,\n uint256 borrowIndex\n ) external returns (uint256);\n\n /**\n * @dev Update the given loan with some params\n *\n * Requirements:\n * - The caller must be a holder of the loan\n * - The loan must be in state Active\n * @param initiator The address of the user updating the loan\n * @param loanId The loan ID\n * @param amountAdded The amount added to the loan\n * @param amountTaken The amount taken from the loan\n * @param borrowIndex The index to get the scaled loan amount\n */\n function updateLoan(\n address initiator,\n uint256 loanId,\n uint256 amountAdded,\n uint256 amountTaken,\n uint256 borrowIndex\n ) external;\n\n /**\n * @dev Repay the given loan\n *\n * Requirements:\n * - The caller must be a holder of the loan\n * - The caller must send in principal + interest\n * - The loan must be in state Active\n *\n * @param initiator The address of the user initiating the repay\n * @param loanId The loan getting burned\n * @param uNftAddress The address of uNFT\n * @param amount The amount repaid\n * @param borrowIndex The index to get the scaled loan amount\n */\n function repayLoan(\n address initiator,\n uint256 loanId,\n address uNftAddress,\n uint256 amount,\n uint256 borrowIndex\n ) external;\n\n /**\n * @dev Auction the given loan\n *\n * Requirements:\n * - The price must be greater than current highest price\n * - The loan must be in state Active or Auction\n *\n * @param initiator The address of the user initiating the auction\n * @param loanId The loan getting auctioned\n * @param bidPrice The bid price of this auction\n */\n function auctionLoan(\n address initiator,\n uint256 loanId,\n address onBehalfOf,\n uint256 bidPrice,\n uint256 borrowAmount,\n uint256 borrowIndex\n ) external;\n\n /**\n * @dev Redeem the given loan with some params\n *\n * Requirements:\n * - The caller must be a holder of the loan\n * - The loan must be in state Auction\n * @param initiator The address of the user initiating the borrow\n * @param loanId The loan getting redeemed\n * @param amountTaken The taken amount\n * @param borrowIndex The index to get the scaled loan amount\n */\n function redeemLoan(address initiator, uint256 loanId, uint256 amountTaken, uint256 borrowIndex) external;\n\n /**\n * @dev Liquidate the given loan\n *\n * Requirements:\n * - The caller must send in principal + interest\n * - The loan must be in state Active\n *\n * @param initiator The address of the user initiating the auction\n * @param loanId The loan getting burned\n * @param uNftAddress The address of uNFT\n * @param borrowAmount The borrow amount\n * @param borrowIndex The index to get the scaled loan amount\n */\n function liquidateLoan(\n address initiator,\n uint256 loanId,\n address uNftAddress,\n uint256 borrowAmount,\n uint256 borrowIndex\n ) external;\n\n /**\n * @dev Liquidate the given loan on NFTX\n *\n * Requirements:\n * - The caller must send in principal + interest\n * - The loan must be in state Auction\n *\n * @param loanId The loan getting burned\n */\n function liquidateLoanNFTX(\n uint256 loanId,\n address uNftAddress,\n uint256 borrowAmount,\n uint256 borrowIndex,\n uint256 amountOutMin\n ) external returns (uint256 sellPrice);\n\n /**\n * @dev Liquidate the given loan on SudoSwap\n *\n * Requirements:\n * - The caller must send in principal + interest\n * - The loan must be in state Auction\n *\n * @param loanId The loan getting burned\n */\n function liquidateLoanSudoSwap(\n uint256 loanId,\n address uNftAddress,\n uint256 borrowAmount,\n uint256 borrowIndex,\n DataTypes.SudoSwapParams memory sudoswapParams\n ) external returns (uint256 sellPrice);\n\n /**\n * @dev returns the borrower of a specific loan\n * param loanId the loan to get the borrower from\n */\n function borrowerOf(uint256 loanId) external view returns (address);\n\n /**\n * @dev returns the loan corresponding to a specific NFT\n * param nftAsset the underlying NFT asset\n * param tokenId the underlying token ID for the NFT\n */\n function getCollateralLoanId(address nftAsset, uint256 nftTokenId) external view returns (uint256);\n\n /**\n * @dev returns the loan corresponding to a specific loan Id\n * param loanId the loan Id\n */\n function getLoan(uint256 loanId) external view returns (DataTypes.LoanData memory loanData);\n\n /**\n * @dev returns the collateral and reserve corresponding to a specific loan\n * param loanId the loan Id\n */\n function getLoanCollateralAndReserve(\n uint256 loanId\n ) external view returns (address nftAsset, uint256 nftTokenId, address reserveAsset, uint256 scaledAmount);\n\n /**\n * @dev returns the reserve and borrow __scaled__ amount corresponding to a specific loan\n * param loanId the loan Id\n */\n function getLoanReserveBorrowScaledAmount(uint256 loanId) external view returns (address, uint256);\n\n /**\n * @dev returns the reserve and borrow amount corresponding to a specific loan\n * param loanId the loan Id\n */\n function getLoanReserveBorrowAmount(uint256 loanId) external view returns (address, uint256);\n\n function getLoanHighestBid(uint256 loanId) external view returns (address, uint256);\n\n /**\n * @dev returns the collateral amount for a given NFT\n * param nftAsset the underlying NFT asset\n */\n function getNftCollateralAmount(address nftAsset) external view returns (uint256);\n\n /**\n * @dev returns the collateral amount for a given NFT and a specific user\n * param user the user\n * param nftAsset the underlying NFT asset\n */\n function getUserNftCollateralAmount(address user, address nftAsset) external view returns (uint256);\n\n /**\n * @dev returns the counter tracker for all the loan ID's in the protocol\n */\n function getLoanIdTracker() external view returns (CountersUpgradeable.Counter memory);\n}\n"
},
"contracts/interfaces/INFTOracleGetter.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\n/************\n@title INFTOracleGetter interface\n@notice Interface for getting NFT price oracle.*/\ninterface INFTOracleGetter {\n /* CAUTION: Price uint is ETH based (WEI, 18 decimals) */\n /***********\n @dev returns the asset price in ETH\n @param assetContract the underlying NFT asset\n @param tokenId the underlying NFT token Id\n */\n function getNFTPrice(address assetContract, uint256 tokenId) external view returns (uint256);\n}\n"
},
"contracts/interfaces/IReserveOracleGetter.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\n/************\n@title IReserveOracleGetter interface\n@notice Interface for getting Reserve price oracle.*/\ninterface IReserveOracleGetter {\n /* CAUTION: Price uint is ETH based (WEI, 18 decimals) */\n /***********\n @dev returns the asset price in ETH\n */\n function getAssetPrice(address asset) external view returns (uint256);\n\n // get twap price depending on _period\n function getTwapPrice(address _priceFeedKey, uint256 _interval) external view returns (uint256);\n}\n"
},
"contracts/interfaces/IScaledBalanceToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\ninterface IScaledBalanceToken {\n /**\n * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the\n * updated stored balance divided by the reserve's liquidity index at the moment of the update\n * @param user The user whose balance is calculated\n * @return The scaled balance of the user\n **/\n function scaledBalanceOf(address user) external view returns (uint256);\n\n /**\n * @dev Returns the scaled balance of the user and the scaled total supply.\n * @param user The address of the user\n * @return The scaled balance of the user\n * @return The scaled balance and the scaled total supply\n **/\n function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);\n\n /**\n * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)\n * @return The scaled total supply\n **/\n function scaledTotalSupply() external view returns (uint256);\n}\n"
},
"contracts/interfaces/IUToken.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {ILendPoolAddressesProvider} from \"./ILendPoolAddressesProvider.sol\";\nimport {IIncentivesController} from \"./IIncentivesController.sol\";\nimport {IScaledBalanceToken} from \"./IScaledBalanceToken.sol\";\n\nimport {IERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport {IERC20MetadataUpgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\ninterface IUToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable {\n /**\n * @dev Emitted when an uToken is initialized\n * @param underlyingAsset The address of the underlying asset\n * @param pool The address of the associated lending pool\n * @param treasury The address of the treasury\n * @param incentivesController The address of the incentives controller for this uToken\n **/\n event Initialized(\n address indexed underlyingAsset,\n address indexed pool,\n address treasury,\n address incentivesController\n );\n\n /**\n * @dev Initializes the bToken\n * @param addressProvider The address of the address provider where this bToken will be used\n * @param treasury The address of the Unlockd treasury, receiving the fees on this bToken\n * @param underlyingAsset The address of the underlying asset of this bToken\n * @param uTokenDecimals The amount of token decimals\n * @param uTokenName The name of the token\n * @param uTokenSymbol The token symbol\n */\n function initialize(\n ILendPoolAddressesProvider addressProvider,\n address treasury,\n address underlyingAsset,\n uint8 uTokenDecimals,\n string calldata uTokenName,\n string calldata uTokenSymbol\n ) external;\n\n /**\n * @dev Emitted after the mint action\n * @param from The address performing the mint\n * @param value The amount being\n * @param index The new liquidity index of the reserve\n **/\n event Mint(address indexed from, uint256 value, uint256 index);\n\n /**\n * @dev Mints `amount` uTokens to `user`\n * @param user The address receiving the minted tokens\n * @param amount The amount of tokens getting minted\n * @param index The new liquidity index of the reserve\n * @return `true` if the the previous balance of the user was 0\n */\n function mint(address user, uint256 amount, uint256 index) external returns (bool);\n\n /**\n * @dev Emitted after uTokens are burned\n * @param from The owner of the uTokens, getting them burned\n * @param target The address that will receive the underlying\n * @param value The amount being burned\n * @param index The new liquidity index of the reserve\n **/\n event Burn(address indexed from, address indexed target, uint256 value, uint256 index);\n\n /**\n * @dev Emitted during the transfer action\n * @param from The user whose tokens are being transferred\n * @param to The recipient\n * @param value The amount being transferred\n * @param index The new liquidity index of the reserve\n **/\n event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);\n\n /**\n * @dev Emitted when treasury address is updated in utoken\n * @param _newTreasuryAddress The new treasury address\n **/\n event TreasuryAddressUpdated(address indexed _newTreasuryAddress);\n\n /**\n * @dev Burns uTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n * @param user The owner of the uTokens, getting them burned\n * @param receiverOfUnderlying The address that will receive the underlying\n * @param amount The amount being burned\n * @param index The new liquidity index of the reserve\n **/\n function burn(address user, address receiverOfUnderlying, uint256 amount, uint256 index) external;\n\n /**\n * @dev Mints uTokens to the reserve treasury\n * @param amount The amount of tokens getting minted\n * @param index The new liquidity index of the reserve\n */\n function mintToTreasury(uint256 amount, uint256 index) external;\n\n /**\n * @dev Transfers the underlying asset to `target`. Used by the LendPool to transfer\n * assets in borrow() and withdraw()\n * @param user The recipient of the underlying\n * @param amount The amount getting transferred\n * @return The amount transferred\n **/\n function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);\n\n /**\n * @dev Returns the address of the incentives controller contract\n **/\n function getIncentivesController() external view returns (IIncentivesController);\n\n /**\n * @dev Returns the address of the underlying asset of this uToken\n **/\n function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n\n /**\n * @dev Returns the address of the treasury set to this uToken\n **/\n function RESERVE_TREASURY_ADDRESS() external view returns (address);\n\n /**\n * @dev Sets the address of the treasury to this uToken\n **/\n function setTreasuryAddress(address treasury) external;\n}\n"
},
"contracts/libraries/configuration/NftConfiguration.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\n\n/**\n * @title NftConfiguration library\n * @author Unlockd\n * @notice Implements the bitmap logic to handle the NFT configuration\n */\nlibrary NftConfiguration {\n uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant REDEEM_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant AUCTION_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant REDEEM_FINE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant REDEEM_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant MIN_BIDFINE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant CONFIG_TIMESTAMP_MASK = 0xFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n\n /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;\n uint256 constant IS_FROZEN_START_BIT_POSITION = 57;\n uint256 constant REDEEM_DURATION_START_BIT_POSITION = 64;\n uint256 constant AUCTION_DURATION_START_BIT_POSITION = 80;\n uint256 constant REDEEM_FINE_START_BIT_POSITION = 96;\n uint256 constant REDEEM_THRESHOLD_START_BIT_POSITION = 112;\n uint256 constant MIN_BIDFINE_START_BIT_POSITION = 128;\n uint256 constant CONFIG_TIMESTAMP_START_BIT_POSITION = 144;\n\n uint256 constant MAX_VALID_LTV = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n uint256 constant MAX_VALID_REDEEM_DURATION = 65535;\n uint256 constant MAX_VALID_AUCTION_DURATION = 65535;\n uint256 constant MAX_VALID_REDEEM_FINE = 65535;\n uint256 constant MAX_VALID_REDEEM_THRESHOLD = 65535;\n uint256 constant MAX_VALID_MIN_BIDFINE = 65535;\n uint256 constant MAX_VALID_CONFIG_TIMESTAMP = 4294967295;\n\n /**\n * @dev Sets the Loan to Value of the NFT\n * @param self The NFT configuration\n * @param ltv the new ltv\n **/\n function setLtv(DataTypes.NftConfigurationMap memory self, uint256 ltv) internal pure {\n require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);\n\n self.data = (self.data & LTV_MASK) | ltv;\n }\n\n /**\n * @dev Gets the Loan to Value of the NFT\n * @param self The NFT configuration\n * @return The loan to value\n **/\n function getLtv(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return self.data & ~LTV_MASK;\n }\n\n /**\n * @dev Sets the liquidation threshold of the NFT\n * @param self The NFT configuration\n * @param threshold The new liquidation threshold\n **/\n function setLiquidationThreshold(DataTypes.NftConfigurationMap memory self, uint256 threshold) internal pure {\n require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);\n\n self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation threshold of the NFT\n * @param self The NFT configuration\n * @return The liquidation threshold\n **/\n function getLiquidationThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the liquidation bonus of the NFT\n * @param self The NFT configuration\n * @param bonus The new liquidation bonus\n **/\n function setLiquidationBonus(DataTypes.NftConfigurationMap memory self, uint256 bonus) internal pure {\n require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);\n\n self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation bonus of the NFT\n * @param self The NFT configuration\n * @return The liquidation bonus\n **/\n function getLiquidationBonus(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the active state of the NFT\n * @param self The NFT configuration\n * @param active The active state\n **/\n function setActive(DataTypes.NftConfigurationMap memory self, bool active) internal pure {\n self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the active state of the NFT\n * @param self The NFT configuration\n * @return The active state\n **/\n function getActive(DataTypes.NftConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~ACTIVE_MASK) != 0;\n }\n\n /**\n * @dev Sets the frozen state of the NFT\n * @param self The NFT configuration\n * @param frozen The frozen state\n **/\n function setFrozen(DataTypes.NftConfigurationMap memory self, bool frozen) internal pure {\n self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the frozen state of the NFT\n * @param self The NFT configuration\n * @return The frozen state\n **/\n function getFrozen(DataTypes.NftConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~FROZEN_MASK) != 0;\n }\n\n /**\n * @dev Sets the redeem duration of the NFT\n * @param self The NFT configuration\n * @param redeemDuration The redeem duration\n **/\n function setRedeemDuration(DataTypes.NftConfigurationMap memory self, uint256 redeemDuration) internal pure {\n require(redeemDuration <= MAX_VALID_REDEEM_DURATION, Errors.RC_INVALID_REDEEM_DURATION);\n\n self.data = (self.data & REDEEM_DURATION_MASK) | (redeemDuration << REDEEM_DURATION_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the redeem duration of the NFT\n * @param self The NFT configuration\n * @return The redeem duration\n **/\n function getRedeemDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the auction duration of the NFT\n * @param self The NFT configuration\n * @param auctionDuration The auction duration\n **/\n function setAuctionDuration(DataTypes.NftConfigurationMap memory self, uint256 auctionDuration) internal pure {\n require(auctionDuration <= MAX_VALID_AUCTION_DURATION, Errors.RC_INVALID_AUCTION_DURATION);\n\n self.data = (self.data & AUCTION_DURATION_MASK) | (auctionDuration << AUCTION_DURATION_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the auction duration of the NFT\n * @param self The NFT configuration\n * @return The auction duration\n **/\n function getAuctionDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the redeem fine of the NFT\n * @param self The NFT configuration\n * @param redeemFine The redeem duration\n **/\n function setRedeemFine(DataTypes.NftConfigurationMap memory self, uint256 redeemFine) internal pure {\n require(redeemFine <= MAX_VALID_REDEEM_FINE, Errors.RC_INVALID_REDEEM_FINE);\n\n self.data = (self.data & REDEEM_FINE_MASK) | (redeemFine << REDEEM_FINE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the redeem fine of the NFT\n * @param self The NFT configuration\n * @return The redeem fine\n **/\n function getRedeemFine(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the redeem threshold of the NFT\n * @param self The NFT configuration\n * @param redeemThreshold The redeem duration\n **/\n function setRedeemThreshold(DataTypes.NftConfigurationMap memory self, uint256 redeemThreshold) internal pure {\n require(redeemThreshold <= MAX_VALID_REDEEM_THRESHOLD, Errors.RC_INVALID_REDEEM_THRESHOLD);\n\n self.data = (self.data & REDEEM_THRESHOLD_MASK) | (redeemThreshold << REDEEM_THRESHOLD_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the redeem threshold of the NFT\n * @param self The NFT configuration\n * @return The redeem threshold\n **/\n function getRedeemThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the min & max threshold of the NFT\n * @param self The NFT configuration\n * @param minBidFine The min bid fine\n **/\n function setMinBidFine(DataTypes.NftConfigurationMap memory self, uint256 minBidFine) internal pure {\n require(minBidFine <= MAX_VALID_MIN_BIDFINE, Errors.RC_INVALID_MIN_BID_FINE);\n\n self.data = (self.data & MIN_BIDFINE_MASK) | (minBidFine << MIN_BIDFINE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the min bid fine of the NFT\n * @param self The NFT configuration\n * @return The min bid fine\n **/\n function getMinBidFine(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return ((self.data & ~MIN_BIDFINE_MASK) >> MIN_BIDFINE_START_BIT_POSITION);\n }\n\n /**\n * @dev Sets the timestamp when the NFTconfig was triggered\n * @param self The NFT configuration\n * @param configTimestamp The config timestamp\n **/\n function setConfigTimestamp(DataTypes.NftConfigurationMap memory self, uint256 configTimestamp) internal pure {\n require(configTimestamp <= MAX_VALID_CONFIG_TIMESTAMP, Errors.RC_INVALID_MAX_CONFIG_TIMESTAMP);\n\n self.data = (self.data & CONFIG_TIMESTAMP_MASK) | (configTimestamp << CONFIG_TIMESTAMP_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the timestamp when the NFTconfig was triggered\n * @param self The NFT configuration\n * @return The config timestamp\n **/\n function getConfigTimestamp(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {\n return ((self.data & ~CONFIG_TIMESTAMP_MASK) >> CONFIG_TIMESTAMP_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the configuration flags of the NFT\n * @param self The NFT configuration\n * @return The state flags representing active, frozen\n **/\n function getFlags(DataTypes.NftConfigurationMap storage self) internal view returns (bool, bool) {\n uint256 dataLocal = self.data;\n\n return ((dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0);\n }\n\n /**\n * @dev Gets the configuration flags of the NFT from a memory object\n * @param self The NFT configuration\n * @return The state flags representing active, frozen\n **/\n function getFlagsMemory(DataTypes.NftConfigurationMap memory self) internal pure returns (bool, bool) {\n return ((self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0);\n }\n\n /**\n * @dev Gets the collateral configuration paramters of the NFT\n * @param self The NFT configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus\n **/\n function getCollateralParams(\n DataTypes.NftConfigurationMap storage self\n ) internal view returns (uint256, uint256, uint256) {\n uint256 dataLocal = self.data;\n\n return (\n dataLocal & ~LTV_MASK,\n (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the auction configuration paramters of the NFT\n * @param self The NFT configuration\n * @return The state params representing redeem duration, auction duration, redeem fine\n **/\n function getAuctionParams(\n DataTypes.NftConfigurationMap storage self\n ) internal view returns (uint256, uint256, uint256, uint256) {\n uint256 dataLocal = self.data;\n\n return (\n (dataLocal & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION,\n (dataLocal & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION,\n (dataLocal & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION,\n (dataLocal & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the collateral configuration paramters of the NFT from a memory object\n * @param self The NFT configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus\n **/\n function getCollateralParamsMemory(\n DataTypes.NftConfigurationMap memory self\n ) internal pure returns (uint256, uint256, uint256) {\n return (\n self.data & ~LTV_MASK,\n (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the auction configuration paramters of the NFT from a memory object\n * @param self The NFT configuration\n * @return The state params representing redeem duration, auction duration, redeem fine\n **/\n function getAuctionParamsMemory(\n DataTypes.NftConfigurationMap memory self\n ) internal pure returns (uint256, uint256, uint256, uint256) {\n return (\n (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION,\n (self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION,\n (self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION,\n (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the min & max bid fine of the NFT\n * @param self The NFT configuration\n * @return The min & max bid fine\n **/\n function getMinBidFineMemory(DataTypes.NftConfigurationMap memory self) internal pure returns (uint256) {\n return ((self.data & ~MIN_BIDFINE_MASK) >> MIN_BIDFINE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the timestamp the NFT was configured\n * @param self The NFT configuration\n * @return The timestamp value\n **/\n function getConfigTimestampMemory(DataTypes.NftConfigurationMap memory self) internal pure returns (uint256) {\n return ((self.data & ~CONFIG_TIMESTAMP_MASK) >> CONFIG_TIMESTAMP_START_BIT_POSITION);\n }\n}\n"
},
"contracts/libraries/configuration/ReserveConfiguration.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\n\n/**\n * @title ReserveConfiguration library\n * @author Unlockd\n * @notice Implements the bitmap logic to handle the reserve configuration\n */\nlibrary ReserveConfiguration {\n uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore\n uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore\n uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n\n /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;\n uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;\n uint256 constant IS_FROZEN_START_BIT_POSITION = 57;\n uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;\n uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;\n uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n\n uint256 constant MAX_VALID_LTV = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n uint256 constant MAX_VALID_DECIMALS = 255;\n uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;\n\n /**\n * @dev Sets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @param ltv the new ltv\n **/\n function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {\n require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);\n\n self.data = (self.data & LTV_MASK) | ltv;\n }\n\n /**\n * @dev Gets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @return The loan to value\n **/\n function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n return self.data & ~LTV_MASK;\n }\n\n /**\n * @dev Sets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @param threshold The new liquidation threshold\n **/\n function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure {\n require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);\n\n self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @return The liquidation threshold\n **/\n function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @param bonus The new liquidation bonus\n **/\n function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure {\n require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);\n\n self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @return The liquidation bonus\n **/\n function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the decimals of the underlying asset of the reserve\n * @param self The reserve configuration\n * @param decimals The decimals\n **/\n function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure {\n require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);\n\n self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the decimals of the underlying asset of the reserve\n * @param self The reserve configuration\n * @return The decimals of the asset\n **/\n function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;\n }\n\n /**\n * @dev Sets the active state of the reserve\n * @param self The reserve configuration\n * @param active The active state\n **/\n function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {\n self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the active state of the reserve\n * @param self The reserve configuration\n * @return The active state\n **/\n function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~ACTIVE_MASK) != 0;\n }\n\n /**\n * @dev Sets the frozen state of the reserve\n * @param self The reserve configuration\n * @param frozen The frozen state\n **/\n function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {\n self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the frozen state of the reserve\n * @param self The reserve configuration\n * @return The frozen state\n **/\n function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~FROZEN_MASK) != 0;\n }\n\n /**\n * @dev Enables or disables borrowing on the reserve\n * @param self The reserve configuration\n * @param enabled True if the borrowing needs to be enabled, false otherwise\n **/\n function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {\n self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the borrowing state of the reserve\n * @param self The reserve configuration\n * @return The borrowing state\n **/\n function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~BORROWING_MASK) != 0;\n }\n\n /**\n * @dev Enables or disables stable rate borrowing on the reserve\n * @param self The reserve configuration\n * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise\n **/\n function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {\n self.data =\n (self.data & STABLE_BORROWING_MASK) |\n (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the stable rate borrowing state of the reserve\n * @param self The reserve configuration\n * @return The stable rate borrowing state\n **/\n function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {\n return (self.data & ~STABLE_BORROWING_MASK) != 0;\n }\n\n /**\n * @dev Sets the reserve factor of the reserve\n * @param self The reserve configuration\n * @param reserveFactor The reserve factor\n **/\n function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure {\n require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);\n\n self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the reserve factor of the reserve\n * @param self The reserve configuration\n * @return The reserve factor\n **/\n function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {\n return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;\n }\n\n /**\n * @dev Gets the configuration flags of the reserve\n * @param self The reserve configuration\n * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n **/\n function getFlags(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (\n bool,\n bool,\n bool,\n bool\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n (dataLocal & ~ACTIVE_MASK) != 0,\n (dataLocal & ~FROZEN_MASK) != 0,\n (dataLocal & ~BORROWING_MASK) != 0,\n (dataLocal & ~STABLE_BORROWING_MASK) != 0\n );\n }\n\n /**\n * @dev Gets the configuration paramters of the reserve\n * @param self The reserve configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n **/\n function getParams(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n dataLocal & ~LTV_MASK,\n (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the configuration paramters of the reserve from a memory object\n * @param self The reserve configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n **/\n function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n return (\n self.data & ~LTV_MASK,\n (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION\n );\n }\n\n /**\n * @dev Gets the configuration flags of the reserve from a memory object\n * @param self The reserve configuration\n * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n **/\n function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (\n bool,\n bool,\n bool,\n bool\n )\n {\n return (\n (self.data & ~ACTIVE_MASK) != 0,\n (self.data & ~FROZEN_MASK) != 0,\n (self.data & ~BORROWING_MASK) != 0,\n (self.data & ~STABLE_BORROWING_MASK) != 0\n );\n }\n}\n"
},
"contracts/libraries/helpers/Errors.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\n/**\n * @title Errors library\n * @author Unlockd\n * @notice Defines the error messages emitted by the different contracts of the Unlockd protocol\n */\nlibrary Errors {\n enum ReturnCode {\n SUCCESS,\n FAILED\n }\n\n string public constant SUCCESS = \"0\";\n\n //common errors\n string public constant CALLER_NOT_POOL_ADMIN = \"100\"; // 'The caller must be the pool admin'\n string public constant CALLER_NOT_ADDRESS_PROVIDER = \"101\";\n string public constant INVALID_FROM_BALANCE_AFTER_TRANSFER = \"102\";\n string public constant INVALID_TO_BALANCE_AFTER_TRANSFER = \"103\";\n string public constant CALLER_NOT_ONBEHALFOF_OR_IN_WHITELIST = \"104\";\n string public constant CALLER_NOT_POOL_LIQUIDATOR = \"105\";\n string public constant INVALID_ZERO_ADDRESS = \"106\";\n string public constant CALLER_NOT_LTV_MANAGER = \"107\";\n string public constant CALLER_NOT_PRICE_MANAGER = \"108\";\n\n //math library errors\n string public constant MATH_MULTIPLICATION_OVERFLOW = \"200\";\n string public constant MATH_ADDITION_OVERFLOW = \"201\";\n string public constant MATH_DIVISION_BY_ZERO = \"202\";\n\n //validation & check errors\n string public constant VL_INVALID_AMOUNT = \"301\"; // 'Amount must be greater than 0'\n string public constant VL_NO_ACTIVE_RESERVE = \"302\"; // 'Action requires an active reserve'\n string public constant VL_RESERVE_FROZEN = \"303\"; // 'Action cannot be performed because the reserve is frozen'\n string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = \"304\"; // 'User cannot withdraw more than the available balance'\n string public constant VL_BORROWING_NOT_ENABLED = \"305\"; // 'Borrowing is not enabled'\n string public constant VL_COLLATERAL_BALANCE_IS_0 = \"306\"; // 'The collateral balance is 0'\n string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = \"307\"; // 'Health factor is lesser than the liquidation threshold'\n string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = \"308\"; // 'There is not enough collateral to cover a new borrow'\n string public constant VL_NO_DEBT_OF_SELECTED_TYPE = \"309\"; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'\n string public constant VL_NO_ACTIVE_NFT = \"310\";\n string public constant VL_NFT_FROZEN = \"311\";\n string public constant VL_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = \"312\"; // 'User did not borrow the specified currency'\n string public constant VL_INVALID_HEALTH_FACTOR = \"313\";\n string public constant VL_INVALID_ONBEHALFOF_ADDRESS = \"314\";\n string public constant VL_INVALID_TARGET_ADDRESS = \"315\";\n string public constant VL_INVALID_RESERVE_ADDRESS = \"316\";\n string public constant VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER = \"317\";\n string public constant VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER = \"318\";\n string public constant VL_HEALTH_FACTOR_HIGHER_THAN_LIQUIDATION_THRESHOLD = \"319\";\n string public constant VL_TIMEFRAME_EXCEEDED = \"320\";\n string public constant VL_VALUE_EXCEED_TREASURY_BALANCE = \"321\";\n\n //lend pool errors\n string public constant LP_CALLER_NOT_LEND_POOL_CONFIGURATOR = \"400\"; // 'The caller of the function is not the lending pool configurator'\n string public constant LP_IS_PAUSED = \"401\"; // 'Pool is paused'\n string public constant LP_NO_MORE_RESERVES_ALLOWED = \"402\";\n string public constant LP_NOT_CONTRACT = \"403\";\n string public constant LP_BORROW_NOT_EXCEED_LIQUIDATION_THRESHOLD = \"404\";\n string public constant LP_BORROW_IS_EXCEED_LIQUIDATION_PRICE = \"405\";\n string public constant LP_NO_MORE_NFTS_ALLOWED = \"406\";\n string public constant LP_INVALID_USER_NFT_AMOUNT = \"407\";\n string public constant LP_INCONSISTENT_PARAMS = \"408\";\n string public constant LP_NFT_IS_NOT_USED_AS_COLLATERAL = \"409\";\n string public constant LP_CALLER_MUST_BE_AN_UTOKEN = \"410\";\n string public constant LP_INVALID_NFT_AMOUNT = \"411\";\n string public constant LP_NFT_HAS_USED_AS_COLLATERAL = \"412\";\n string public constant LP_DELEGATE_CALL_FAILED = \"413\";\n string public constant LP_AMOUNT_LESS_THAN_EXTRA_DEBT = \"414\";\n string public constant LP_AMOUNT_LESS_THAN_REDEEM_THRESHOLD = \"415\";\n string public constant LP_AMOUNT_GREATER_THAN_MAX_REPAY = \"416\";\n string public constant LP_NFT_TOKEN_ID_EXCEED_MAX_LIMIT = \"417\";\n string public constant LP_NFT_SUPPLY_NUM_EXCEED_MAX_LIMIT = \"418\";\n string public constant LP_CALLER_NOT_LEND_POOL_LIQUIDATOR_NOR_GATEWAY = \"419\";\n string public constant LP_CONSECUTIVE_BIDS_NOT_ALLOWED = \"420\";\n string public constant LP_INVALID_OVERFLOW_VALUE = \"421\";\n string public constant LP_CALLER_NOT_NFT_HOLDER = \"422\";\n string public constant LP_NFT_NOT_ALLOWED_TO_SELL = \"423\";\n string public constant LP_RESERVES_WITHOUT_ENOUGH_LIQUIDITY = \"424\";\n string public constant LP_COLLECTION_NOT_SUPPORTED = \"425\";\n string public constant LP_MSG_VALUE_DIFFERENT_FROM_CONFIG_FEE = \"426\";\n string public constant LP_INVALID_SAFE_HEALTH_FACTOR = \"427\";\n\n //lend pool loan errors\n string public constant LPL_INVALID_LOAN_STATE = \"480\";\n string public constant LPL_INVALID_LOAN_AMOUNT = \"481\";\n string public constant LPL_INVALID_TAKEN_AMOUNT = \"482\";\n string public constant LPL_AMOUNT_OVERFLOW = \"483\";\n string public constant LPL_BID_PRICE_LESS_THAN_LIQUIDATION_PRICE = \"484\";\n string public constant LPL_BID_PRICE_LESS_THAN_HIGHEST_PRICE = \"485\";\n string public constant LPL_BID_REDEEM_DURATION_HAS_END = \"486\";\n string public constant LPL_BID_USER_NOT_SAME = \"487\";\n string public constant LPL_BID_REPAY_AMOUNT_NOT_ENOUGH = \"488\";\n string public constant LPL_BID_AUCTION_DURATION_HAS_END = \"489\";\n string public constant LPL_BID_AUCTION_DURATION_NOT_END = \"490\";\n string public constant LPL_BID_PRICE_LESS_THAN_BORROW = \"491\";\n string public constant LPL_INVALID_BIDDER_ADDRESS = \"492\";\n string public constant LPL_AMOUNT_LESS_THAN_BID_FINE = \"493\";\n string public constant LPL_INVALID_BID_FINE = \"494\";\n string public constant LPL_BID_PRICE_LESS_THAN_MIN_BID_REQUIRED = \"495\";\n\n //common token errors\n string public constant CT_CALLER_MUST_BE_LEND_POOL = \"500\"; // 'The caller of this function must be a lending pool'\n string public constant CT_INVALID_MINT_AMOUNT = \"501\"; //invalid amount to mint\n string public constant CT_INVALID_BURN_AMOUNT = \"502\"; //invalid amount to burn\n string public constant CT_BORROW_ALLOWANCE_NOT_ENOUGH = \"503\";\n\n //reserve logic errors\n string public constant RL_RESERVE_ALREADY_INITIALIZED = \"601\"; // 'Reserve has already been initialized'\n string public constant RL_LIQUIDITY_INDEX_OVERFLOW = \"602\"; // Liquidity index overflows uint128\n string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = \"603\"; // Variable borrow index overflows uint128\n string public constant RL_LIQUIDITY_RATE_OVERFLOW = \"604\"; // Liquidity rate overflows uint128\n string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = \"605\"; // Variable borrow rate overflows uint128\n\n //configure errors\n string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = \"700\"; // 'The liquidity of the reserve needs to be 0'\n string public constant LPC_INVALID_CONFIGURATION = \"701\"; // 'Invalid risk parameters for the reserve'\n string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = \"702\"; // 'The caller must be the emergency admin'\n string public constant LPC_INVALID_UNFT_ADDRESS = \"703\";\n string public constant LPC_INVALIED_LOAN_ADDRESS = \"704\";\n string public constant LPC_NFT_LIQUIDITY_NOT_0 = \"705\";\n string public constant LPC_PARAMS_MISMATCH = \"706\"; // NFT assets & token ids mismatch\n string public constant LPC_FEE_PERCENTAGE_TOO_HIGH = \"707\";\n string public constant LPC_INVALID_LTVMANAGER_ADDRESS = \"708\";\n string public constant LPC_INCONSISTENT_PARAMS = \"709\";\n string public constant LPC_INVALID_SAFE_HEALTH_FACTOR = \"710\";\n //reserve config errors\n string public constant RC_INVALID_LTV = \"730\";\n string public constant RC_INVALID_LIQ_THRESHOLD = \"731\";\n string public constant RC_INVALID_LIQ_BONUS = \"732\";\n string public constant RC_INVALID_DECIMALS = \"733\";\n string public constant RC_INVALID_RESERVE_FACTOR = \"734\";\n string public constant RC_INVALID_REDEEM_DURATION = \"735\";\n string public constant RC_INVALID_AUCTION_DURATION = \"736\";\n string public constant RC_INVALID_REDEEM_FINE = \"737\";\n string public constant RC_INVALID_REDEEM_THRESHOLD = \"738\";\n string public constant RC_INVALID_MIN_BID_FINE = \"739\";\n string public constant RC_INVALID_MAX_BID_FINE = \"740\";\n string public constant RC_INVALID_MAX_CONFIG_TIMESTAMP = \"741\";\n\n //address provider erros\n string public constant LPAPR_PROVIDER_NOT_REGISTERED = \"760\"; // 'Provider is not registered'\n string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = \"761\";\n\n //NFTXHelper\n string public constant NFTX_INVALID_VAULTS_LENGTH = \"800\";\n\n //NFTOracleErrors\n string public constant NFTO_INVALID_PRICEM_ADDRESS = \"900\";\n}\n"
},
"contracts/libraries/logic/GenericLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {ILendPoolLoan} from \"../../interfaces/ILendPoolLoan.sol\";\nimport {IReserveOracleGetter} from \"../../interfaces/IReserveOracleGetter.sol\";\nimport {INFTOracleGetter} from \"../../interfaces/INFTOracleGetter.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {PercentageMath} from \"../math/PercentageMath.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {NftConfiguration} from \"../configuration/NftConfiguration.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\n\n/**\n * @title GenericLogic library\n * @author Unlockd\n * @notice Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n using ReserveLogic for DataTypes.ReserveData;\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using NftConfiguration for DataTypes.NftConfigurationMap;\n\n uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;\n\n struct CalculateLoanDataVars {\n uint256 reserveUnitPrice;\n uint256 reserveUnit;\n uint256 reserveDecimals;\n uint256 healthFactor;\n uint256 totalCollateralInETH;\n uint256 totalCollateralInReserve;\n uint256 totalDebtInETH;\n uint256 totalDebtInReserve;\n uint256 nftLtv;\n uint256 nftLiquidationThreshold;\n address nftAsset;\n uint256 nftTokenId;\n uint256 nftUnitPrice;\n uint256 minRedeemValue;\n }\n\n /**\n * @dev Calculates the nft loan data.\n * this includes the total collateral/borrow balances in Reserve,\n * the Loan To Value, the Liquidation Ratio, and the Health factor.\n * @param reserveAddress the underlying asset of the reserve\n * @param reserveData Data of the reserve\n * @param nftAddress the underlying NFT asset\n * @param nftTokenId the token Id for the NFT\n * @param nftConfig Config of the nft by tokenId\n * @param loanAddress The loan address\n * @param loanId The loan identifier\n * @param reserveOracle The price oracle address of reserve\n * @param nftOracle The price oracle address of nft\n * @return The total collateral and total debt of the loan in Reserve, the ltv, liquidation threshold and the HF\n **/\n function calculateLoanData(\n address reserveAddress,\n DataTypes.ReserveData storage reserveData,\n address nftAddress,\n uint256 nftTokenId,\n DataTypes.NftConfigurationMap storage nftConfig,\n address loanAddress,\n uint256 loanId,\n address reserveOracle,\n address nftOracle\n ) internal view returns (uint256, uint256, uint256) {\n CalculateLoanDataVars memory vars;\n (vars.nftLtv, vars.nftLiquidationThreshold, ) = nftConfig.getCollateralParams();\n\n // calculate total borrow balance for the loan\n if (loanId != 0) {\n (vars.totalDebtInETH, vars.totalDebtInReserve) = calculateNftDebtData(\n reserveAddress,\n reserveData,\n loanAddress,\n loanId,\n reserveOracle\n );\n }\n\n // calculate total collateral balance for the nft\n (vars.totalCollateralInETH, vars.totalCollateralInReserve) = calculateNftCollateralData(\n reserveAddress,\n reserveData,\n nftAddress,\n nftTokenId,\n reserveOracle,\n nftOracle\n );\n\n // calculate health by borrow and collateral\n vars.healthFactor = calculateHealthFactorFromBalances(\n vars.totalCollateralInReserve,\n vars.totalDebtInReserve,\n vars.nftLiquidationThreshold\n );\n return (vars.totalCollateralInReserve, vars.totalDebtInReserve, vars.healthFactor);\n }\n\n /**\n * @dev Calculates the nft debt data.\n * this includes the total collateral/borrow balances in Reserve,\n * the Loan To Value, the Liquidation Ratio, and the Health factor.\n * @param reserveAddress the underlying asset of the reserve\n * @param reserveData Data of the reserve\n * @param loanAddress The loan address\n * @param loanId The loan identifier\n * @param reserveOracle The price oracle address of reserve\n * @return The total debt in ETH and the total debt in the Reserve\n **/\n function calculateNftDebtData(\n address reserveAddress,\n DataTypes.ReserveData storage reserveData,\n address loanAddress,\n uint256 loanId,\n address reserveOracle\n ) internal view returns (uint256, uint256) {\n CalculateLoanDataVars memory vars;\n\n // all asset price has converted to ETH based, unit is in WEI (18 decimals)\n\n vars.reserveDecimals = reserveData.configuration.getDecimals();\n vars.reserveUnit = 10 ** vars.reserveDecimals;\n\n vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress);\n\n (, vars.totalDebtInReserve) = ILendPoolLoan(loanAddress).getLoanReserveBorrowAmount(loanId);\n vars.totalDebtInETH = (vars.totalDebtInReserve * vars.reserveUnitPrice) / vars.reserveUnit;\n\n return (vars.totalDebtInETH, vars.totalDebtInReserve);\n }\n\n /**\n * @dev Calculates the nft collateral data.\n * this includes the total collateral/borrow balances in Reserve,\n * the Loan To Value, the Liquidation Ratio, and the Health factor.\n * @param reserveAddress the underlying asset of the reserve\n * @param reserveData Data of the reserve\n * @param nftAddress The underlying NFT asset\n * @param nftTokenId The underlying NFT token Id\n * @param reserveOracle The price oracle address of reserve\n * @param nftOracle The nft price oracle address\n * @return The total debt in ETH and the total debt in the Reserve\n **/\n function calculateNftCollateralData(\n address reserveAddress,\n DataTypes.ReserveData storage reserveData,\n address nftAddress,\n uint256 nftTokenId,\n address reserveOracle,\n address nftOracle\n ) internal view returns (uint256, uint256) {\n reserveData;\n\n CalculateLoanDataVars memory vars;\n\n // calculate total collateral balance for the nft\n // all asset price has converted to ETH based, unit is in WEI (18 decimals)\n vars.nftUnitPrice = INFTOracleGetter(nftOracle).getNFTPrice(nftAddress, nftTokenId);\n vars.totalCollateralInETH = vars.nftUnitPrice;\n\n if (reserveAddress != address(0)) {\n vars.reserveDecimals = reserveData.configuration.getDecimals();\n vars.reserveUnit = 10 ** vars.reserveDecimals;\n\n vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress);\n vars.totalCollateralInReserve = (vars.totalCollateralInETH * vars.reserveUnit) / vars.reserveUnitPrice;\n }\n\n return (vars.totalCollateralInETH, vars.totalCollateralInReserve);\n }\n\n /**\n * @dev Calculates the optimal min redeem value\n * @param borrowAmount The debt\n * @param nftAddress The nft address\n * @param nftTokenId The token id\n * @param nftOracle The nft oracle address\n * @param liquidationThreshold The liquidation threshold\n * @param safeHealthFactor The safe health factor value\n * @return The health factor calculated from the balances provided\n **/\n function calculateOptimalMinRedeemValue(\n uint256 borrowAmount,\n address nftAddress,\n uint256 nftTokenId,\n address nftOracle,\n uint256 liquidationThreshold,\n uint256 safeHealthFactor\n ) internal view returns (uint256) {\n CalculateLoanDataVars memory vars;\n\n vars.nftUnitPrice = INFTOracleGetter(nftOracle).getNFTPrice(nftAddress, nftTokenId);\n vars.minRedeemValue =\n borrowAmount -\n ((vars.nftUnitPrice.percentMul(liquidationThreshold)).wadDiv(safeHealthFactor));\n if (vars.nftUnitPrice < vars.minRedeemValue) {\n return vars.nftUnitPrice;\n }\n\n return vars.minRedeemValue;\n }\n\n function calculateOptimalMaxRedeemValue(uint256 debt, uint256 minRedeem) internal pure returns (uint256) {\n return debt - ((debt - minRedeem).wadDiv(2 ether));\n }\n\n /**\n * @dev Calculates the health factor from the corresponding balances\n * @param totalCollateral The total collateral\n * @param totalDebt The total debt\n * @param liquidationThreshold The avg liquidation threshold\n * @return The health factor calculated from the balances provided\n **/\n function calculateHealthFactorFromBalances(\n uint256 totalCollateral,\n uint256 totalDebt,\n uint256 liquidationThreshold\n ) internal pure returns (uint256) {\n if (totalDebt == 0) return type(uint256).max;\n\n return (totalCollateral.percentMul(liquidationThreshold)).wadDiv(totalDebt);\n }\n\n /**\n * @dev Calculates the equivalent amount that an user can borrow, depending on the available collateral and the\n * average Loan To Value\n * @param totalCollateral The total collateral\n * @param totalDebt The total borrow balance\n * @param ltv The average loan to value\n * @return the amount available to borrow for the user\n **/\n\n function calculateAvailableBorrows(\n uint256 totalCollateral,\n uint256 totalDebt,\n uint256 ltv\n ) internal pure returns (uint256) {\n uint256 availableBorrows = totalCollateral.percentMul(ltv);\n\n if (availableBorrows < totalDebt) {\n return 0;\n }\n\n availableBorrows = availableBorrows - totalDebt;\n return availableBorrows;\n }\n\n struct CalcLiquidatePriceLocalVars {\n uint256 ltv;\n uint256 liquidationThreshold;\n uint256 liquidationBonus;\n uint256 nftPriceInETH;\n uint256 nftPriceInReserve;\n uint256 reserveDecimals;\n uint256 reservePriceInETH;\n uint256 thresholdPrice;\n uint256 liquidatePrice;\n uint256 borrowAmount;\n }\n\n /**\n * @dev Calculates the loan liquidation price\n * @param loanId the loan Id\n * @param reserveAsset The underlying asset of the reserve\n * @param reserveData the reserve data\n * @param nftAsset the underlying NFT asset\n * @param nftTokenId the NFT token Id\n * @param nftConfig The NFT data\n * @param poolLoan The pool loan address\n * @param reserveOracle The price oracle address of reserve\n * @param nftOracle The price oracle address of nft\n * @return The borrow amount, threshold price and liquidation price\n **/\n function calculateLoanLiquidatePrice(\n uint256 loanId,\n address reserveAsset,\n DataTypes.ReserveData storage reserveData,\n address nftAsset,\n uint256 nftTokenId,\n DataTypes.NftConfigurationMap storage nftConfig,\n address poolLoan,\n address reserveOracle,\n address nftOracle\n ) internal view returns (uint256, uint256, uint256) {\n CalcLiquidatePriceLocalVars memory vars;\n\n /*\n * 0 CR LH 100\n * |___________________|___________________|___________________|\n * < Borrowing with Interest <\n * CR: Callteral Ratio;\n * LH: Liquidate Threshold;\n * Liquidate Trigger: Borrowing with Interest > thresholdPrice;\n * Liquidate Price: (100% - BonusRatio) * NFT Price;\n */\n\n vars.reserveDecimals = reserveData.configuration.getDecimals();\n\n (, vars.borrowAmount) = ILendPoolLoan(poolLoan).getLoanReserveBorrowAmount(loanId);\n\n (vars.ltv, vars.liquidationThreshold, vars.liquidationBonus) = nftConfig.getCollateralParams();\n\n vars.nftPriceInETH = INFTOracleGetter(nftOracle).getNFTPrice(nftAsset, nftTokenId);\n vars.reservePriceInETH = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAsset);\n\n vars.nftPriceInReserve = ((10 ** vars.reserveDecimals) * vars.nftPriceInETH) / vars.reservePriceInETH;\n\n vars.thresholdPrice = vars.nftPriceInReserve.percentMul(vars.liquidationThreshold);\n\n vars.liquidatePrice = vars.nftPriceInReserve.percentMul(PercentageMath.PERCENTAGE_FACTOR - vars.liquidationBonus);\n\n return (vars.borrowAmount, vars.thresholdPrice, vars.liquidatePrice);\n }\n\n struct CalcLoanBidFineLocalVars {\n uint256 reserveDecimals;\n uint256 reservePriceInETH;\n uint256 baseBidFineInReserve;\n uint256 minBidFinePct;\n uint256 minBidFineInReserve;\n uint256 bidFineInReserve;\n uint256 debtAmount;\n }\n\n function calculateLoanBidFine(\n address reserveAsset,\n DataTypes.ReserveData storage reserveData,\n address nftAsset,\n DataTypes.NftConfigurationMap storage nftConfig,\n DataTypes.LoanData memory loanData,\n address poolLoan,\n address reserveOracle\n ) internal view returns (uint256, uint256) {\n nftAsset;\n\n if (loanData.bidPrice == 0) {\n return (0, 0);\n }\n\n CalcLoanBidFineLocalVars memory vars;\n\n vars.reserveDecimals = reserveData.configuration.getDecimals();\n vars.reservePriceInETH = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAsset);\n vars.baseBidFineInReserve = (1 ether * 10 ** vars.reserveDecimals) / vars.reservePriceInETH;\n\n vars.minBidFinePct = nftConfig.getMinBidFine();\n vars.minBidFineInReserve = vars.baseBidFineInReserve.percentMul(vars.minBidFinePct);\n\n (, vars.debtAmount) = ILendPoolLoan(poolLoan).getLoanReserveBorrowAmount(loanData.loanId);\n\n vars.bidFineInReserve = vars.debtAmount.percentMul(nftConfig.getRedeemFine());\n if (vars.bidFineInReserve < vars.minBidFineInReserve) {\n vars.bidFineInReserve = vars.minBidFineInReserve;\n }\n\n return (vars.minBidFineInReserve, vars.bidFineInReserve);\n }\n}\n"
},
"contracts/libraries/logic/ReserveLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {IUToken} from \"../../interfaces/IUToken.sol\";\nimport {IDebtToken} from \"../../interfaces/IDebtToken.sol\";\nimport {IInterestRate} from \"../../interfaces/IInterestRate.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {MathUtils} from \"../math/MathUtils.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {PercentageMath} from \"../math/PercentageMath.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\n\nimport {IERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport {SafeERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\n/**\n * @title ReserveLogic library\n * @author Unlockd\n * @notice Implements the logic to update the reserves state\n */\nlibrary ReserveLogic {\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /**\n * @dev Emitted when the state of a reserve is updated\n * @param asset The address of the underlying asset of the reserve\n * @param liquidityRate The new liquidity rate\n * @param variableBorrowRate The new variable borrow rate\n * @param liquidityIndex The new liquidity index\n * @param variableBorrowIndex The new variable borrow index\n **/\n event ReserveDataUpdated(\n address indexed asset,\n uint256 liquidityRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n using ReserveLogic for DataTypes.ReserveData;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n /**\n * @dev Returns the ongoing normalized income for the reserve\n * A value of 1e27 means there is no income. As time passes, the income is accrued\n * A value of 2*1e27 means for each unit of asset one unit of income has been accrued\n * @param reserve The reserve object\n * @return the normalized income. expressed in ray\n **/\n function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) {\n uint40 timestamp = reserve.lastUpdateTimestamp;\n\n //solium-disable-next-line\n if (timestamp == uint40(block.timestamp)) {\n //if the index was updated in the same block, no need to perform any calculation\n return reserve.liquidityIndex;\n }\n\n uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(\n reserve.liquidityIndex\n );\n\n return cumulated;\n }\n\n /**\n * @dev Returns the ongoing normalized variable debt for the reserve\n * A value of 1e27 means there is no debt. As time passes, the income is accrued\n * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated\n * @param reserve The reserve object\n * @return The normalized variable debt. expressed in ray\n **/\n function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) {\n uint40 timestamp = reserve.lastUpdateTimestamp;\n\n //solium-disable-next-line\n if (timestamp == uint40(block.timestamp)) {\n //if the index was updated in the same block, no need to perform any calculation\n return reserve.variableBorrowIndex;\n }\n\n uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(\n reserve.variableBorrowIndex\n );\n\n return cumulated;\n }\n\n /**\n * @dev Updates the liquidity cumulative index and the variable borrow index.\n * @param reserve the reserve object\n **/\n function updateState(DataTypes.ReserveData storage reserve) internal {\n uint256 scaledVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply();\n uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;\n uint256 previousLiquidityIndex = reserve.liquidityIndex;\n uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;\n\n (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes(\n reserve,\n scaledVariableDebt,\n previousLiquidityIndex,\n previousVariableBorrowIndex,\n lastUpdatedTimestamp\n );\n\n _mintToTreasury(\n reserve,\n scaledVariableDebt,\n previousVariableBorrowIndex,\n newLiquidityIndex,\n newVariableBorrowIndex,\n lastUpdatedTimestamp\n );\n }\n\n /**\n * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income.\n * @param reserve The reserve object\n * @param totalLiquidity The total liquidity available in the reserve\n * @param amount The amount to accomulate\n **/\n function cumulateToLiquidityIndex(\n DataTypes.ReserveData storage reserve,\n uint256 totalLiquidity,\n uint256 amount\n ) internal {\n uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay());\n\n uint256 result = amountToLiquidityRatio + (WadRayMath.ray());\n\n result = result.rayMul(reserve.liquidityIndex);\n require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);\n\n reserve.liquidityIndex = uint128(result);\n }\n\n /**\n * @dev Initializes a reserve\n * @param reserve The reserve object\n * @param uTokenAddress The address of the overlying uToken contract\n * @param debtTokenAddress The address of the overlying debtToken contract\n * @param interestRateAddress The address of the interest rate strategy contract\n **/\n function init(\n DataTypes.ReserveData storage reserve,\n address uTokenAddress,\n address debtTokenAddress,\n address interestRateAddress\n ) external {\n require(reserve.uTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);\n\n reserve.liquidityIndex = uint128(WadRayMath.ray());\n reserve.variableBorrowIndex = uint128(WadRayMath.ray());\n reserve.uTokenAddress = uTokenAddress;\n reserve.debtTokenAddress = debtTokenAddress;\n reserve.interestRateAddress = interestRateAddress;\n }\n\n struct UpdateInterestRatesLocalVars {\n uint256 availableLiquidity;\n uint256 newLiquidityRate;\n uint256 newVariableRate;\n uint256 totalVariableDebt;\n }\n\n /**\n * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate\n * @param reserve The address of the reserve to be updated\n * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action\n * @param liquidityTaken The amount of liquidity taken from the protocol (withdraw or borrow)\n **/\n function updateInterestRates(\n DataTypes.ReserveData storage reserve,\n address reserveAddress,\n address uTokenAddress,\n uint256 liquidityAdded,\n uint256 liquidityTaken\n ) internal {\n UpdateInterestRatesLocalVars memory vars;\n\n //calculates the total variable debt locally using the scaled borrow amount instead\n //of borrow amount(), as it's noticeably cheaper. Also, the index has been\n //updated by the previous updateState() call\n vars.totalVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply().rayMul(\n reserve.variableBorrowIndex\n );\n\n (vars.newLiquidityRate, vars.newVariableRate) = IInterestRate(reserve.interestRateAddress).calculateInterestRates(\n reserveAddress,\n uTokenAddress,\n liquidityAdded,\n liquidityTaken,\n vars.totalVariableDebt,\n reserve.configuration.getReserveFactor()\n );\n require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);\n require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);\n\n reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);\n reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);\n\n emit ReserveDataUpdated(\n reserveAddress,\n vars.newLiquidityRate,\n vars.newVariableRate,\n reserve.liquidityIndex,\n reserve.variableBorrowIndex\n );\n }\n\n struct MintToTreasuryLocalVars {\n uint256 currentVariableDebt;\n uint256 previousVariableDebt;\n uint256 totalDebtAccrued;\n uint256 amountToMint;\n uint256 reserveFactor;\n }\n\n /**\n * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the\n * specific asset.\n * @param reserve The reserve reserve to be updated\n * @param scaledVariableDebt The current scaled total variable debt\n * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest\n * @param newLiquidityIndex The new liquidity index\n * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest\n **/\n function _mintToTreasury(\n DataTypes.ReserveData storage reserve,\n uint256 scaledVariableDebt,\n uint256 previousVariableBorrowIndex,\n uint256 newLiquidityIndex,\n uint256 newVariableBorrowIndex,\n uint40 timestamp\n ) internal {\n timestamp;\n MintToTreasuryLocalVars memory vars;\n\n vars.reserveFactor = reserve.configuration.getReserveFactor();\n\n if (vars.reserveFactor == 0) {\n return;\n }\n\n //calculate the last principal variable debt\n vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);\n\n //calculate the new total supply after accumulation of the index\n vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);\n\n //debt accrued is the sum of the current debt minus the sum of the debt at the last update\n vars.totalDebtAccrued = vars.currentVariableDebt - (vars.previousVariableDebt);\n\n vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);\n\n if (vars.amountToMint != 0) {\n IUToken(reserve.uTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);\n }\n }\n\n /**\n * @dev Updates the reserve indexes and the timestamp of the update\n * @param reserve The reserve reserve to be updated\n * @param scaledVariableDebt The scaled variable debt\n * @param liquidityIndex The last stored liquidity index\n * @param variableBorrowIndex The last stored variable borrow index\n **/\n function _updateIndexes(\n DataTypes.ReserveData storage reserve,\n uint256 scaledVariableDebt,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex,\n uint40 timestamp\n ) internal returns (uint256, uint256) {\n uint256 currentLiquidityRate = reserve.currentLiquidityRate;\n\n uint256 newLiquidityIndex = liquidityIndex;\n uint256 newVariableBorrowIndex = variableBorrowIndex;\n\n //only cumulating if there is any income being produced\n if (currentLiquidityRate > 0) {\n uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);\n newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);\n require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);\n\n reserve.liquidityIndex = uint128(newLiquidityIndex);\n\n //as the liquidity rate might come only from stable rate loans, we need to ensure\n //that there is actual variable debt before accumulating\n if (scaledVariableDebt != 0) {\n uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(\n reserve.currentVariableBorrowRate,\n timestamp\n );\n newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);\n require(newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW);\n reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);\n }\n }\n\n //solium-disable-next-line\n reserve.lastUpdateTimestamp = uint40(block.timestamp);\n return (newLiquidityIndex, newVariableBorrowIndex);\n }\n}\n"
},
"contracts/libraries/logic/SupplyLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {IUToken} from \"../../interfaces/IUToken.sol\";\n\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\n\nimport {IERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport {SafeERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\n\n/**\n * @title SupplyLogic library\n * @author Unlockd\n * @notice Implements the logic to supply feature\n */\nlibrary SupplyLogic {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using ReserveLogic for DataTypes.ReserveData;\n\n /**\n * @dev Emitted on deposit()\n * @param user The address initiating the deposit\n * @param amount The amount deposited\n * @param reserve The address of the underlying asset of the reserve\n * @param onBehalfOf The beneficiary of the deposit, receiving the uTokens\n * @param referral The referral code used\n **/\n event Deposit(\n address user,\n address indexed reserve,\n uint256 amount,\n address indexed onBehalfOf,\n uint16 indexed referral\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param user The address initiating the withdrawal, owner of uTokens\n * @param reserve The address of the underlyng asset being withdrawn\n * @param amount The amount to be withdrawn\n * @param to Address that will receive the underlying\n **/\n event Withdraw(address indexed user, address indexed reserve, uint256 amount, address indexed to);\n\n /**\n * @notice Implements the supply feature. Through `deposit()`, users deposit assets to the protocol.\n * @dev Emits the `Deposit()` event.\n * @param reservesData The state of all the reserves\n * @param params The additional parameters needed to execute the deposit function\n */\n function executeDeposit(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.ExecuteDepositParams memory params\n ) external {\n require(params.onBehalfOf != address(0), Errors.VL_INVALID_ONBEHALFOF_ADDRESS);\n\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n address uToken = reserve.uTokenAddress;\n require(uToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n\n ValidationLogic.validateDeposit(reserve, params.amount);\n\n reserve.updateState();\n reserve.updateInterestRates(params.asset, uToken, params.amount, 0);\n\n IERC20Upgradeable(params.asset).safeTransferFrom(params.initiator, uToken, params.amount);\n\n IUToken(uToken).mint(params.onBehalfOf, params.amount, reserve.liquidityIndex);\n\n emit Deposit(params.initiator, params.asset, params.amount, params.onBehalfOf, params.referralCode);\n }\n\n /**\n * @notice Implements the withdraw feature. Through `withdraw()`, users withdraw assets from the protocol.\n * @dev Emits the `Withdraw()` event.\n * @param reservesData The state of all the reserves\n * @param params The additional parameters needed to execute the withdraw function\n */\n function executeWithdraw(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.ExecuteWithdrawParams memory params\n ) external returns (uint256) {\n require(params.to != address(0), Errors.VL_INVALID_TARGET_ADDRESS);\n\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n address uToken = reserve.uTokenAddress;\n require(uToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n\n uint256 userBalance = IUToken(uToken).balanceOf(params.initiator);\n\n uint256 amountToWithdraw = params.amount;\n\n if (params.amount == type(uint256).max) {\n amountToWithdraw = userBalance;\n }\n\n ValidationLogic.validateWithdraw(reserve, amountToWithdraw, userBalance);\n\n reserve.updateState();\n\n reserve.updateInterestRates(params.asset, uToken, 0, amountToWithdraw);\n\n IUToken(uToken).burn(params.initiator, params.to, amountToWithdraw, reserve.liquidityIndex);\n\n emit Withdraw(params.initiator, params.asset, amountToWithdraw, params.to);\n\n return amountToWithdraw;\n }\n}\n"
},
"contracts/libraries/logic/ValidationLogic.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\nimport {GenericLogic} from \"./GenericLogic.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {PercentageMath} from \"../math/PercentageMath.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {NftConfiguration} from \"../configuration/NftConfiguration.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {IInterestRate} from \"../../interfaces/IInterestRate.sol\";\nimport {ILendPoolLoan} from \"../../interfaces/ILendPoolLoan.sol\";\nimport {ILendPool} from \"../../interfaces/ILendPool.sol\";\n\nimport {IERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport {SafeERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\n/**\n * @title ValidationLogic library\n * @author Unlockd\n * @notice Implements functions to validate the different actions of the protocol\n */\nlibrary ValidationLogic {\n using ReserveLogic for DataTypes.ReserveData;\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using NftConfiguration for DataTypes.NftConfigurationMap;\n\n /**\n * @dev Validates a deposit action\n * @param reserve The reserve object on which the user is depositing\n * @param amount The amount to be deposited\n */\n function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {\n (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();\n\n require(amount != 0, Errors.VL_INVALID_AMOUNT);\n require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n require(!isFrozen, Errors.VL_RESERVE_FROZEN);\n }\n\n /**\n * @dev Validates a withdraw action\n * @param reserveData The reserve state\n * @param amount The amount to be withdrawn\n * @param userBalance The balance of the user\n */\n function validateWithdraw(\n DataTypes.ReserveData storage reserveData,\n uint256 amount,\n uint256 userBalance\n ) external view {\n require(amount != 0, Errors.VL_INVALID_AMOUNT);\n require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n\n (bool isActive, , , ) = reserveData.configuration.getFlags();\n require(isActive, Errors.VL_NO_ACTIVE_RESERVE);\n }\n\n struct ValidateBorrowLocalVars {\n uint256 currentLtv;\n uint256 currentLiquidationThreshold;\n uint256 amountOfCollateralNeeded;\n uint256 userCollateralBalance;\n uint256 userBorrowBalance;\n uint256 availableLiquidity;\n uint256 healthFactor;\n bool isActive;\n bool isFrozen;\n bool borrowingEnabled;\n bool stableRateBorrowingEnabled;\n bool nftIsActive;\n bool nftIsFrozen;\n address loanReserveAsset;\n address loanBorrower;\n }\n\n /**\n * @dev Validates a borrow action\n * @param reserveData The reserve state from which the user is borrowing\n * @param nftData The state of the user for the specific nft\n */\n function validateBorrow(\n DataTypes.ExecuteBorrowParams memory params,\n DataTypes.ReserveData storage reserveData,\n DataTypes.NftData storage nftData,\n DataTypes.NftConfigurationMap storage nftConfig,\n address loanAddress,\n uint256 loanId,\n address reserveOracle,\n address nftOracle\n ) external view {\n ValidateBorrowLocalVars memory vars;\n require(reserveData.uTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n require(nftData.uNftAddress != address(0), Errors.LPC_INVALID_UNFT_ADDRESS);\n require(params.amount > 0, Errors.VL_INVALID_AMOUNT);\n\n if (loanId != 0) {\n DataTypes.LoanData memory loanData = ILendPoolLoan(loanAddress).getLoan(loanId);\n\n require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE);\n require(params.asset == loanData.reserveAsset, Errors.VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER);\n require(params.onBehalfOf == loanData.borrower, Errors.VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER);\n }\n\n (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserveData\n .configuration\n .getFlags();\n require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);\n require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);\n require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);\n (vars.nftIsActive, vars.nftIsFrozen) = nftData.configuration.getFlags();\n require(vars.nftIsActive, Errors.VL_NO_ACTIVE_NFT);\n require(!vars.nftIsFrozen, Errors.VL_NFT_FROZEN);\n\n /**\n * @dev additional check for individual asset\n */\n (vars.nftIsActive, vars.nftIsFrozen) = nftConfig.getFlags();\n require(vars.nftIsActive, Errors.VL_NO_ACTIVE_NFT);\n require(!vars.nftIsFrozen, Errors.VL_NFT_FROZEN);\n\n require(\n (nftConfig.getConfigTimestamp() + ILendPool(address(this)).getTimeframe()) >= block.timestamp,\n Errors.VL_TIMEFRAME_EXCEEDED\n );\n\n (vars.currentLtv, vars.currentLiquidationThreshold, ) = nftConfig.getCollateralParams();\n\n (vars.userCollateralBalance, vars.userBorrowBalance, vars.healthFactor) = GenericLogic.calculateLoanData(\n params.asset,\n reserveData,\n params.nftAsset,\n params.nftTokenId,\n nftConfig,\n loanAddress,\n loanId,\n reserveOracle,\n nftOracle\n );\n\n require(vars.userCollateralBalance > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);\n require(\n vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n );\n\n //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\n //LTV is calculated in percentage\n vars.amountOfCollateralNeeded = (vars.userBorrowBalance + params.amount).percentDiv(vars.currentLtv);\n\n require(vars.amountOfCollateralNeeded <= vars.userCollateralBalance, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW);\n }\n\n /**\n * @dev Validates a repay action\n * @param reserveData The reserve state from which the user is repaying\n * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)\n * @param borrowAmount The borrow balance of the user\n */\n function validateRepay(\n DataTypes.ReserveData storage reserveData,\n DataTypes.NftData storage nftData,\n DataTypes.NftConfigurationMap storage nftConfig,\n DataTypes.LoanData memory loanData,\n uint256 amountSent,\n uint256 borrowAmount\n ) external view {\n require(nftData.uNftAddress != address(0), Errors.LPC_INVALID_UNFT_ADDRESS);\n require(reserveData.uTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n\n require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);\n\n require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n /**\n * @dev additional check for individual asset\n */\n require(nftConfig.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n require(amountSent > 0, Errors.VL_INVALID_AMOUNT);\n\n require(borrowAmount > 0, Errors.VL_NO_DEBT_OF_SELECTED_TYPE);\n\n require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE);\n }\n\n /**\n * @dev Validates the auction action\n * @param reserveData The reserve data of the principal\n * @param nftData The nft data of the underlying nft\n * @param bidPrice Total variable debt balance of the user\n **/\n function validateAuction(\n DataTypes.ReserveData storage reserveData,\n DataTypes.NftData storage nftData,\n DataTypes.NftConfigurationMap storage nftConfig,\n DataTypes.LoanData memory loanData,\n uint256 bidPrice\n ) internal view {\n require(nftData.uNftAddress != address(0), Errors.LPC_INVALID_UNFT_ADDRESS);\n require(reserveData.uTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n\n require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);\n\n require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n /**\n * @dev additional check for individual asset\n */\n require(nftConfig.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n require(\n loanData.state == DataTypes.LoanState.Active || loanData.state == DataTypes.LoanState.Auction,\n Errors.LPL_INVALID_LOAN_STATE\n );\n\n require(bidPrice > 0, Errors.VL_INVALID_AMOUNT);\n }\n\n /**\n * @dev Validates a redeem action\n * @param reserveData The reserve state\n * @param nftData The nft state\n */\n function validateRedeem(\n DataTypes.ReserveData storage reserveData,\n DataTypes.NftData storage nftData,\n DataTypes.NftConfigurationMap storage nftConfig,\n DataTypes.LoanData memory loanData,\n uint256 amount\n ) external view {\n require(nftData.uNftAddress != address(0), Errors.LPC_INVALID_UNFT_ADDRESS);\n require(reserveData.uTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n\n require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);\n\n require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n /**\n * @dev additional check for individual asset\n */\n require(nftConfig.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE);\n\n require(amount > 0, Errors.VL_INVALID_AMOUNT);\n }\n\n /**\n * @dev Validates the liquidation action\n * @param reserveData The reserve data of the principal\n * @param nftData The data of the underlying NFT\n * @param loanData The loan data of the underlying NFT\n **/\n function validateLiquidate(\n DataTypes.ReserveData storage reserveData,\n DataTypes.NftData storage nftData,\n DataTypes.NftConfigurationMap storage nftConfig,\n DataTypes.LoanData memory loanData\n ) internal view {\n require(nftData.uNftAddress != address(0), Errors.LPC_INVALID_UNFT_ADDRESS);\n require(reserveData.uTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n\n require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);\n\n require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n /**\n * @dev additional check for individual asset\n */\n require(nftConfig.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE);\n }\n\n /**\n * @dev Validates the liquidation NFTX action\n * @param reserveData The reserve data of the principal\n * @param nftData The data of the underlying NFT\n * @param loanData The loan data of the underlying NFT\n **/\n function validateLiquidateMarkets(\n DataTypes.ReserveData storage reserveData,\n DataTypes.NftData storage nftData,\n DataTypes.NftConfigurationMap storage nftConfig,\n DataTypes.LoanData memory loanData\n ) internal view {\n require(nftData.uNftAddress != address(0), Errors.LPC_INVALID_UNFT_ADDRESS);\n require(reserveData.uTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);\n\n require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);\n\n require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n /**\n * @dev additional check for individual asset\n */\n require(nftConfig.getActive(), Errors.VL_NO_ACTIVE_NFT);\n\n /**\n * @dev Loan requires to be in `Active` state. The Markets liquidate process is triggered if there has not been any auction\n * and the auction time has passed. In that case, loan is not in `Auction` nor `Defaulted`, and needs to be liquidated in a third-party market.\n */\n require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE);\n }\n\n /**\n * @dev Validates an uToken transfer\n * @param from The user from which the uTokens are being transferred\n * @param reserveData The state of the reserve\n */\n function validateTransfer(address from, DataTypes.ReserveData storage reserveData) internal pure {\n from;\n reserveData;\n }\n}\n"
},
"contracts/libraries/math/MathUtils.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {WadRayMath} from \"./WadRayMath.sol\";\n\nlibrary MathUtils {\n using WadRayMath for uint256;\n\n /// @dev Ignoring leap years\n uint256 internal constant SECONDS_PER_YEAR = 365 days;\n\n /**\n * @dev Function to calculate the interest accumulated using a linear interest rate formula\n * @param rate The interest rate, in ray\n * @param lastUpdateTimestamp The timestamp of the last update of the interest\n * @return The interest rate linearly accumulated during the timeDelta, in ray\n **/\n\n function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {\n //solium-disable-next-line\n uint256 timeDifference = block.timestamp - (uint256(lastUpdateTimestamp));\n\n return ((rate * (timeDifference)) / SECONDS_PER_YEAR) + (WadRayMath.ray());\n }\n\n /**\n * @dev Function to calculate the interest using a compounded interest rate formula\n * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n *\n * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n *\n * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions\n * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods\n *\n * @param rate The interest rate, in ray\n * @param lastUpdateTimestamp The timestamp of the last update of the interest\n * @return The interest rate compounded during the timeDelta, in ray\n **/\n function calculateCompoundedInterest(\n uint256 rate,\n uint40 lastUpdateTimestamp,\n uint256 currentTimestamp\n ) internal pure returns (uint256) {\n //solium-disable-next-line\n uint256 exp = currentTimestamp - (uint256(lastUpdateTimestamp));\n\n if (exp == 0) {\n return WadRayMath.ray();\n }\n\n uint256 expMinusOne = exp - 1;\n\n uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n uint256 ratePerSecond = rate / SECONDS_PER_YEAR;\n\n uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);\n uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);\n\n uint256 secondTerm = (exp * (expMinusOne) * (basePowerTwo)) / 2;\n uint256 thirdTerm = (exp * (expMinusOne) * (expMinusTwo) * (basePowerThree)) / 6;\n\n return WadRayMath.ray() + (ratePerSecond * (exp)) + (secondTerm) + (thirdTerm);\n }\n\n /**\n * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp\n * @param rate The interest rate (in ray)\n * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated\n **/\n function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) {\n return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);\n }\n}\n"
},
"contracts/libraries/math/PercentageMath.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {Errors} from \"../helpers/Errors.sol\";\n\n/**\n * @title PercentageMath library\n * @author Unlockd\n * @notice Provides functions to perform percentage calculations\n * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR\n * @dev Operations are rounded half up\n **/\n\nlibrary PercentageMath {\n uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals\n uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;\n uint256 constant ONE_PERCENT = 1e2; //100, 1%\n uint256 constant TEN_PERCENT = 1e3; //1000, 10%\n uint256 constant ONE_THOUSANDTH_PERCENT = 1e1; //10, 0.1%\n uint256 constant ONE_TEN_THOUSANDTH_PERCENT = 1; //1, 0.01%\n\n /**\n * @dev Executes a percentage multiplication\n * @param value The value of which the percentage needs to be calculated\n * @param percentage The percentage of the value to be calculated\n * @return The percentage of value\n **/\n function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {\n if (value == 0 || percentage == 0) {\n return 0;\n }\n\n require(value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;\n }\n\n /**\n * @dev Executes a percentage division\n * @param value The value of which the percentage needs to be calculated\n * @param percentage The percentage of the value to be calculated\n * @return The value divided the percentage\n **/\n function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {\n require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO);\n uint256 halfPercentage = percentage / 2;\n\n require(value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;\n }\n}\n"
},
"contracts/libraries/math/WadRayMath.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nimport {Errors} from \"../helpers/Errors.sol\";\n\n/**\n * @title WadRayMath library\n * @author Unlockd\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)\n **/\n\nlibrary WadRayMath {\n uint256 internal constant WAD = 1e18;\n uint256 internal constant HALF_WAD = WAD / 2;\n\n uint256 internal constant RAY = 1e27;\n uint256 internal constant HALF_RAY = RAY / 2;\n\n uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n /**\n * @return One ray, 1e27\n **/\n function ray() internal pure returns (uint256) {\n return RAY;\n }\n\n /**\n * @return One wad, 1e18\n **/\n\n function wad() internal pure returns (uint256) {\n return WAD;\n }\n\n /**\n * @return Half ray, 1e27/2\n **/\n function halfRay() internal pure returns (uint256) {\n return HALF_RAY;\n }\n\n /**\n * @return Half ray, 1e18/2\n **/\n function halfWad() internal pure returns (uint256) {\n return HALF_WAD;\n }\n\n /**\n * @dev Multiplies two wad, rounding half up to the nearest wad\n * @param a Wad\n * @param b Wad\n * @return The result of a*b, in wad\n **/\n function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0 || b == 0) {\n return 0;\n }\n\n require(a <= (type(uint256).max - HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * b + HALF_WAD) / WAD;\n }\n\n /**\n * @dev Divides two wad, rounding half up to the nearest wad\n * @param a Wad\n * @param b Wad\n * @return The result of a/b, in wad\n **/\n function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b != 0, Errors.MATH_DIVISION_BY_ZERO);\n uint256 halfB = b / 2;\n\n require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * WAD + halfB) / b;\n }\n\n /**\n * @dev Multiplies two ray, rounding half up to the nearest ray\n * @param a Ray\n * @param b Ray\n * @return The result of a*b, in ray\n **/\n function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0 || b == 0) {\n return 0;\n }\n\n require(a <= (type(uint256).max - HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * b + HALF_RAY) / RAY;\n }\n\n /**\n * @dev Divides two ray, rounding half up to the nearest ray\n * @param a Ray\n * @param b Ray\n * @return The result of a/b, in ray\n **/\n function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b != 0, Errors.MATH_DIVISION_BY_ZERO);\n uint256 halfB = b / 2;\n\n require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * RAY + halfB) / b;\n }\n\n /**\n * @dev Casts ray down to wad\n * @param a Ray\n * @return a casted to wad, rounded half up to the nearest wad\n **/\n function rayToWad(uint256 a) internal pure returns (uint256) {\n uint256 halfRatio = WAD_RAY_RATIO / 2;\n uint256 result = halfRatio + a;\n require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW);\n\n return result / WAD_RAY_RATIO;\n }\n\n /**\n * @dev Converts wad up to ray\n * @param a Wad\n * @return a converted in ray\n **/\n function wadToRay(uint256 a) internal pure returns (uint256) {\n uint256 result = a * WAD_RAY_RATIO;\n require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW);\n return result;\n }\n}\n"
},
"contracts/libraries/types/DataTypes.sol": {
"content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.4;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n uint40 lastUpdateTimestamp;\n //tokens addresses\n address uTokenAddress;\n address debtTokenAddress;\n //address of the interest rate strategy\n address interestRateAddress;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint8 id;\n }\n\n struct NftData {\n //stores the nft configuration\n NftConfigurationMap configuration;\n //address of the uNFT contract\n address uNftAddress;\n //the id of the nft. Represents the position in the list of the active nfts\n uint8 id;\n uint256 maxSupply;\n uint256 maxTokenId;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: Reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60-63: reserved\n //bit 64-79: reserve factor\n uint256 data;\n }\n\n struct NftConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 56: NFT is active\n //bit 57: NFT is frozen\n //bit 64-71: Redeem duration\n //bit 72-79: Auction duration\n //bit 80-95: Redeem fine\n //bit 96-111: Redeem threshold\n //bit 112-127: Min bid fine\n //bit 128-159: Timestamp Config\n uint256 data;\n }\n\n /**\n * @dev Enum describing the current state of a loan\n * State change flow:\n * Created -> Active -> Repaid\n * -> Auction -> Defaulted\n */\n enum LoanState {\n // We need a default that is not 'Created' - this is the zero value\n None,\n // The loan data is stored, but not initiated yet.\n Created,\n // The loan has been initialized, funds have been delivered to the borrower and the collateral is held.\n Active,\n // The loan is in auction, higest price liquidator will got chance to claim it.\n Auction,\n // The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state.\n Repaid,\n // The loan was delinquent and collateral claimed by the liquidator. This is a terminal state.\n Defaulted\n }\n\n struct LoanData {\n //the id of the nft loan\n uint256 loanId;\n //the current state of the loan\n LoanState state;\n //address of borrower\n address borrower;\n //address of nft asset token\n address nftAsset;\n //the id of nft token\n uint256 nftTokenId;\n //address of reserve asset token\n address reserveAsset;\n //scaled borrow amount. Expressed in ray\n uint256 scaledAmount;\n //start time of first bid time\n uint256 bidStartTimestamp;\n //bidder address of higest bid\n address bidderAddress;\n //price of higest bid\n uint256 bidPrice;\n //borrow amount of loan\n uint256 bidBorrowAmount;\n //bidder address of first bid\n address firstBidderAddress;\n }\n\n struct ExecuteDepositParams {\n address initiator;\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteWithdrawParams {\n address initiator;\n address asset;\n uint256 amount;\n address to;\n }\n\n struct ExecuteBorrowParams {\n address initiator;\n address asset;\n uint256 amount;\n address nftAsset;\n uint256 nftTokenId;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteRepayParams {\n address initiator;\n address nftAsset;\n uint256 nftTokenId;\n uint256 amount;\n }\n\n struct ExecuteAuctionParams {\n address initiator;\n address nftAsset;\n uint256 nftTokenId;\n uint256 bidPrice;\n address onBehalfOf;\n uint256 auctionDurationConfigFee;\n }\n\n struct ExecuteRedeemParams {\n address initiator;\n address nftAsset;\n uint256 nftTokenId;\n uint256 amount;\n uint256 bidFine;\n uint256 safeHealthFactor;\n }\n\n struct ExecuteLiquidateParams {\n address initiator;\n address nftAsset;\n uint256 nftTokenId;\n uint256 amount;\n }\n\n struct ExecuteLiquidateMarketsParams {\n address nftAsset;\n uint256 nftTokenId;\n uint256 liquidateFeePercentage;\n uint256 amountOutMin;\n }\n\n struct SudoSwapParams {\n address LSSVMPair;\n uint256 amountOutMinSudoswap;\n }\n struct ExecuteLendPoolStates {\n uint256 pauseStartTime;\n uint256 pauseDurationTime;\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"evmVersion": "istanbul",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {
"contracts/libraries/logic/ValidationLogic.sol": {
"ValidationLogic": "0x8749e3e58a437eca1b7dfa7046c99a51cd784def"
}
}
}
}