{ "language": "Solidity", "sources": { "contracts/dependencies/openzeppelin/contracts/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.10;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return 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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(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 /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/Context.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return payable(msg.sender);\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/ERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/ERC721.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)\n\npragma solidity 0.8.10;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./IERC721Metadata.sol\";\nimport \"./Address.sol\";\nimport \"./Context.sol\";\nimport \"./Strings.sol\";\nimport \"./ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(ERC165)\n returns (bool)\n {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner)\n public\n view\n virtual\n override\n returns (uint256)\n {\n require(\n owner != address(0),\n \"ERC721: address zero is not a valid owner\"\n );\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n address owner = _owners[tokenId];\n require(\n owner != address(0),\n \"ERC721: owner query for nonexistent token\"\n );\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n \"ERC721Metadata: URI query for nonexistent token\"\n );\n\n string memory baseURI = _baseURI();\n return\n bytes(baseURI).length > 0\n ? string(abi.encodePacked(baseURI, tokenId.toString()))\n : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n require(\n _exists(tokenId),\n \"ERC721: approved query for nonexistent token\"\n );\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved)\n public\n virtual\n override\n {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(\n _isApprovedOrOwner(_msgSender(), tokenId),\n \"ERC721: transfer caller is not owner nor approved\"\n );\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) public virtual override {\n require(\n _isApprovedOrOwner(_msgSender(), tokenId),\n \"ERC721: transfer caller is not owner nor approved\"\n );\n _safeTransfer(from, to, tokenId, _data);\n }\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 * `_data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\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 `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 _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(\n _checkOnERC721Received(from, to, tokenId, _data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId)\n internal\n view\n virtual\n returns (bool)\n {\n require(\n _exists(tokenId),\n \"ERC721: operator query for nonexistent token\"\n );\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner ||\n isApprovedForAll(owner, spender) ||\n getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\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 _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory _data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, _data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(\n ERC721.ownerOf(tokenId) == from,\n \"ERC721: transfer from incorrect owner\"\n );\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits a {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits a {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param _data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) private returns (bool) {\n if (to.isContract()) {\n try\n IERC721Receiver(to).onERC721Received(\n _msgSender(),\n from,\n tokenId,\n _data\n )\n returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n } else {\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n" }, "contracts/dependencies/openzeppelin/contracts/ERC721Enumerable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./ERC721.sol\";\nimport \"./IERC721Enumerable.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the EIP that adds\n * enumerability of all the token ids in the contract as well as all token ids owned by each\n * account.\n */\nabstract contract ERC721Enumerable is ERC721, IERC721Enumerable {\n // Mapping from owner to list of owned token IDs\n mapping(address => mapping(uint256 => uint256)) private _ownedTokens;\n\n // Mapping from token ID to index of the owner tokens list\n mapping(uint256 => uint256) private _ownedTokensIndex;\n\n // Array with all token ids, used for enumeration\n uint256[] private _allTokens;\n\n // Mapping from token id to position in the allTokens array\n mapping(uint256 => uint256) private _allTokensIndex;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(ERC721)\n returns (bool)\n {\n return\n interfaceId == type(IERC721Enumerable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index)\n public\n view\n virtual\n override\n returns (uint256)\n {\n require(\n index < ERC721.balanceOf(owner),\n \"ERC721Enumerable: owner index out of bounds\"\n );\n return _ownedTokens[owner][index];\n }\n\n /**\n * @dev See {IERC721Enumerable-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _allTokens.length;\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenByIndex}.\n */\n function tokenByIndex(uint256 index)\n public\n view\n virtual\n override\n returns (uint256)\n {\n require(\n index < ERC721Enumerable.totalSupply(),\n \"ERC721Enumerable: global index out of bounds\"\n );\n return _allTokens[index];\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, tokenId);\n\n if (from == address(0)) {\n _addTokenToAllTokensEnumeration(tokenId);\n } else if (from != to) {\n _removeTokenFromOwnerEnumeration(from, tokenId);\n }\n if (to == address(0)) {\n _removeTokenFromAllTokensEnumeration(tokenId);\n } else if (to != from) {\n _addTokenToOwnerEnumeration(to, tokenId);\n }\n }\n\n /**\n * @dev Private function to add a token to this extension's ownership-tracking data structures.\n * @param to address representing the new owner of the given token ID\n * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n */\n function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n uint256 length = ERC721.balanceOf(to);\n _ownedTokens[to][length] = tokenId;\n _ownedTokensIndex[tokenId] = length;\n }\n\n /**\n * @dev Private function to add a token to this extension's token tracking data structures.\n * @param tokenId uint256 ID of the token to be added to the tokens list\n */\n function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n _allTokensIndex[tokenId] = _allTokens.length;\n _allTokens.push(tokenId);\n }\n\n /**\n * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n * @param from address representing the previous owner of the given token ID\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */\n function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)\n private\n {\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;\n uint256 tokenIndex = _ownedTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary\n if (tokenIndex != lastTokenIndex) {\n uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];\n\n _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n }\n\n // This also deletes the contents at the last position of the array\n delete _ownedTokensIndex[tokenId];\n delete _ownedTokens[from][lastTokenIndex];\n }\n\n /**\n * @dev Private function to remove a token from this extension's token tracking data structures.\n * This has O(1) time complexity, but alters the order of the _allTokens array.\n * @param tokenId uint256 ID of the token to be removed from the tokens list\n */\n function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = _allTokens.length - 1;\n uint256 tokenIndex = _allTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n uint256 lastTokenId = _allTokens[lastTokenIndex];\n\n _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n // This also deletes the contents at the last position of the array\n delete _allTokensIndex[tokenId];\n _allTokens.pop();\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\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)\n external\n 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)\n external\n view\n 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(\n address indexed owner,\n address indexed spender,\n uint256 value\n );\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\nimport {IERC20} from \"./IERC20.sol\";\n\ninterface IERC20Detailed is IERC20 {\n function name() external view returns (string memory);\n\n function symbol() external view returns (string memory);\n\n function decimals() external view returns (uint8);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(\n address indexed from,\n address indexed to,\n uint256 indexed tokenId\n );\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(\n address indexed owner,\n address indexed approved,\n uint256 indexed tokenId\n );\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(\n address indexed owner,\n address indexed operator,\n bool approved\n );\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`.\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 /**\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 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 the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId)\n external\n view\n returns (address operator);\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)\n external\n view\n returns (bool);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721Enumerable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index)\n external\n view\n returns (uint256);\n\n /**\n * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n * Use along with {totalSupply} to enumerate all tokens.\n */\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721Metadata.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721Receiver.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)\n\npragma solidity 0.8.10;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/Ownable.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"./Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\ncontract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(\n address indexed previousOwner,\n address indexed newOwner\n );\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(_owner == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(\n newOwner != address(0),\n \"Ownable: new owner is the zero address\"\n );\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/SafeCast.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\npragma solidity 0.8.10;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(\n value <= type(uint224).max,\n \"SafeCast: value doesn't fit in 224 bits\"\n );\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(\n value <= type(uint128).max,\n \"SafeCast: value doesn't fit in 128 bits\"\n );\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(\n value <= type(uint96).max,\n \"SafeCast: value doesn't fit in 96 bits\"\n );\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(\n value <= type(uint64).max,\n \"SafeCast: value doesn't fit in 64 bits\"\n );\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(\n value <= type(uint32).max,\n \"SafeCast: value doesn't fit in 32 bits\"\n );\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(\n value <= type(uint16).max,\n \"SafeCast: value doesn't fit in 16 bits\"\n );\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(\n value <= type(uint8).max,\n \"SafeCast: value doesn't fit in 8 bits\"\n );\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(\n value >= type(int128).min && value <= type(int128).max,\n \"SafeCast: value doesn't fit in 128 bits\"\n );\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(\n value >= type(int64).min && value <= type(int64).max,\n \"SafeCast: value doesn't fit in 64 bits\"\n );\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(\n value >= type(int32).min && value <= type(int32).max,\n \"SafeCast: value doesn't fit in 32 bits\"\n );\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(\n value >= type(int16).min && value <= type(int16).max,\n \"SafeCast: value doesn't fit in 16 bits\"\n );\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(\n value >= type(int8).min && value <= type(int8).max,\n \"SafeCast: value doesn't fit in 8 bits\"\n );\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(\n value <= uint256(type(int256).max),\n \"SafeCast: value doesn't fit in an int256\"\n );\n return int256(value);\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity 0.8.10;\n\nimport \"./IERC20.sol\";\nimport \"./draft-IERC20Permit.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}" }, "contracts/dependencies/openzeppelin/contracts/Strings.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/draft-IERC20Permit.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity 0.8.10;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}" }, "contracts/dependencies/seaport/contracts/lib/ConsiderationEnums.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\n// prettier-ignore\nenum OrderType {\n // 0: no partial fills, anyone can execute\n FULL_OPEN,\n\n // 1: partial fills supported, anyone can execute\n PARTIAL_OPEN,\n\n // 2: no partial fills, only offerer or zone can execute\n FULL_RESTRICTED,\n\n // 3: partial fills supported, only offerer or zone can execute\n PARTIAL_RESTRICTED\n}\n\n// prettier-ignore\nenum BasicOrderType {\n // 0: no partial fills, anyone can execute\n ETH_TO_ERC721_FULL_OPEN,\n\n // 1: partial fills supported, anyone can execute\n ETH_TO_ERC721_PARTIAL_OPEN,\n\n // 2: no partial fills, only offerer or zone can execute\n ETH_TO_ERC721_FULL_RESTRICTED,\n\n // 3: partial fills supported, only offerer or zone can execute\n ETH_TO_ERC721_PARTIAL_RESTRICTED,\n\n // 4: no partial fills, anyone can execute\n ETH_TO_ERC1155_FULL_OPEN,\n\n // 5: partial fills supported, anyone can execute\n ETH_TO_ERC1155_PARTIAL_OPEN,\n\n // 6: no partial fills, only offerer or zone can execute\n ETH_TO_ERC1155_FULL_RESTRICTED,\n\n // 7: partial fills supported, only offerer or zone can execute\n ETH_TO_ERC1155_PARTIAL_RESTRICTED,\n\n // 8: no partial fills, anyone can execute\n ERC20_TO_ERC721_FULL_OPEN,\n\n // 9: partial fills supported, anyone can execute\n ERC20_TO_ERC721_PARTIAL_OPEN,\n\n // 10: no partial fills, only offerer or zone can execute\n ERC20_TO_ERC721_FULL_RESTRICTED,\n\n // 11: partial fills supported, only offerer or zone can execute\n ERC20_TO_ERC721_PARTIAL_RESTRICTED,\n\n // 12: no partial fills, anyone can execute\n ERC20_TO_ERC1155_FULL_OPEN,\n\n // 13: partial fills supported, anyone can execute\n ERC20_TO_ERC1155_PARTIAL_OPEN,\n\n // 14: no partial fills, only offerer or zone can execute\n ERC20_TO_ERC1155_FULL_RESTRICTED,\n\n // 15: partial fills supported, only offerer or zone can execute\n ERC20_TO_ERC1155_PARTIAL_RESTRICTED,\n\n // 16: no partial fills, anyone can execute\n ERC721_TO_ERC20_FULL_OPEN,\n\n // 17: partial fills supported, anyone can execute\n ERC721_TO_ERC20_PARTIAL_OPEN,\n\n // 18: no partial fills, only offerer or zone can execute\n ERC721_TO_ERC20_FULL_RESTRICTED,\n\n // 19: partial fills supported, only offerer or zone can execute\n ERC721_TO_ERC20_PARTIAL_RESTRICTED,\n\n // 20: no partial fills, anyone can execute\n ERC1155_TO_ERC20_FULL_OPEN,\n\n // 21: partial fills supported, anyone can execute\n ERC1155_TO_ERC20_PARTIAL_OPEN,\n\n // 22: no partial fills, only offerer or zone can execute\n ERC1155_TO_ERC20_FULL_RESTRICTED,\n\n // 23: partial fills supported, only offerer or zone can execute\n ERC1155_TO_ERC20_PARTIAL_RESTRICTED\n}\n\n// prettier-ignore\nenum BasicOrderRouteType {\n // 0: provide Ether (or other native token) to receive offered ERC721 item.\n ETH_TO_ERC721,\n\n // 1: provide Ether (or other native token) to receive offered ERC1155 item.\n ETH_TO_ERC1155,\n\n // 2: provide ERC20 item to receive offered ERC721 item.\n ERC20_TO_ERC721,\n\n // 3: provide ERC20 item to receive offered ERC1155 item.\n ERC20_TO_ERC1155,\n\n // 4: provide ERC721 item to receive offered ERC20 item.\n ERC721_TO_ERC20,\n\n // 5: provide ERC1155 item to receive offered ERC20 item.\n ERC1155_TO_ERC20\n}\n\n// prettier-ignore\nenum ItemType {\n // 0: ETH on mainnet, MATIC on polygon, etc.\n NATIVE,\n\n // 1: ERC20 items (ERC777 and ERC20 analogues could also technically work)\n ERC20,\n\n // 2: ERC721 items\n ERC721,\n\n // 3: ERC1155 items\n ERC1155,\n\n // 4: ERC721 items where a number of tokenIds are supported\n ERC721_WITH_CRITERIA,\n\n // 5: ERC1155 items where a number of ids are supported\n ERC1155_WITH_CRITERIA\n}\n\n// prettier-ignore\nenum Side {\n // 0: Items that can be spent\n OFFER,\n\n // 1: Items that must be received\n CONSIDERATION\n}\n" }, "contracts/dependencies/seaport/contracts/lib/ConsiderationStructs.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\nimport {\n OrderType,\n BasicOrderType,\n ItemType,\n Side\n} from \"./ConsiderationEnums.sol\";\n\n/**\n * @dev An order contains eleven components: an offerer, a zone (or account that\n * can cancel the order or restrict who can fulfill the order depending on\n * the type), the order type (specifying partial fill support as well as\n * restricted order status), the start and end time, a hash that will be\n * provided to the zone when validating restricted orders, a salt, a key\n * corresponding to a given conduit, a counter, and an arbitrary number of\n * offer items that can be spent along with consideration items that must\n * be received by their respective recipient.\n */\nstruct OrderComponents {\n address offerer;\n address zone;\n OfferItem[] offer;\n ConsiderationItem[] consideration;\n OrderType orderType;\n uint256 startTime;\n uint256 endTime;\n bytes32 zoneHash;\n uint256 salt;\n bytes32 conduitKey;\n uint256 counter;\n}\n\n/**\n * @dev An offer item has five components: an item type (ETH or other native\n * tokens, ERC20, ERC721, and ERC1155, as well as criteria-based ERC721 and\n * ERC1155), a token address, a dual-purpose \"identifierOrCriteria\"\n * component that will either represent a tokenId or a merkle root\n * depending on the item type, and a start and end amount that support\n * increasing or decreasing amounts over the duration of the respective\n * order.\n */\nstruct OfferItem {\n ItemType itemType;\n address token;\n uint256 identifierOrCriteria;\n uint256 startAmount;\n uint256 endAmount;\n}\n\n/**\n * @dev A consideration item has the same five components as an offer item and\n * an additional sixth component designating the required recipient of the\n * item.\n */\nstruct ConsiderationItem {\n ItemType itemType;\n address token;\n uint256 identifierOrCriteria;\n uint256 startAmount;\n uint256 endAmount;\n address payable recipient;\n}\n\n/**\n * @dev A spent item is translated from a utilized offer item and has four\n * components: an item type (ETH or other native tokens, ERC20, ERC721, and\n * ERC1155), a token address, a tokenId, and an amount.\n */\nstruct SpentItem {\n ItemType itemType;\n address token;\n uint256 identifier;\n uint256 amount;\n}\n\n/**\n * @dev A received item is translated from a utilized consideration item and has\n * the same four components as a spent item, as well as an additional fifth\n * component designating the required recipient of the item.\n */\nstruct ReceivedItem {\n ItemType itemType;\n address token;\n uint256 identifier;\n uint256 amount;\n address payable recipient;\n}\n\n/**\n * @dev For basic orders involving ETH / native / ERC20 <=> ERC721 / ERC1155\n * matching, a group of six functions may be called that only requires a\n * subset of the usual order arguments. Note the use of a \"basicOrderType\"\n * enum; this represents both the usual order type as well as the \"route\"\n * of the basic order (a simple derivation function for the basic order\n * type is `basicOrderType = orderType + (4 * basicOrderRoute)`.)\n */\nstruct BasicOrderParameters {\n // calldata offset\n address considerationToken; // 0x24\n uint256 considerationIdentifier; // 0x44\n uint256 considerationAmount; // 0x64\n address payable offerer; // 0x84\n address zone; // 0xa4\n address offerToken; // 0xc4\n uint256 offerIdentifier; // 0xe4\n uint256 offerAmount; // 0x104\n BasicOrderType basicOrderType; // 0x124\n uint256 startTime; // 0x144\n uint256 endTime; // 0x164\n bytes32 zoneHash; // 0x184\n uint256 salt; // 0x1a4\n bytes32 offererConduitKey; // 0x1c4\n bytes32 fulfillerConduitKey; // 0x1e4\n uint256 totalOriginalAdditionalRecipients; // 0x204\n AdditionalRecipient[] additionalRecipients; // 0x224\n bytes signature; // 0x244\n // Total length, excluding dynamic array data: 0x264 (580)\n}\n\n/**\n * @dev Basic orders can supply any number of additional recipients, with the\n * implied assumption that they are supplied from the offered ETH (or other\n * native token) or ERC20 token for the order.\n */\nstruct AdditionalRecipient {\n uint256 amount;\n address payable recipient;\n}\n\n/**\n * @dev The full set of order components, with the exception of the counter,\n * must be supplied when fulfilling more sophisticated orders or groups of\n * orders. The total number of original consideration items must also be\n * supplied, as the caller may specify additional consideration items.\n */\nstruct OrderParameters {\n address offerer; // 0x00\n address zone; // 0x20\n OfferItem[] offer; // 0x40\n ConsiderationItem[] consideration; // 0x60\n OrderType orderType; // 0x80\n uint256 startTime; // 0xa0\n uint256 endTime; // 0xc0\n bytes32 zoneHash; // 0xe0\n uint256 salt; // 0x100\n bytes32 conduitKey; // 0x120\n uint256 totalOriginalConsiderationItems; // 0x140\n // offer.length // 0x160\n}\n\n/**\n * @dev Orders require a signature in addition to the other order parameters.\n */\nstruct Order {\n OrderParameters parameters;\n bytes signature;\n}\n\n/**\n * @dev Advanced orders include a numerator (i.e. a fraction to attempt to fill)\n * and a denominator (the total size of the order) in addition to the\n * signature and other order parameters. It also supports an optional field\n * for supplying extra data; this data will be included in a staticcall to\n * `isValidOrderIncludingExtraData` on the zone for the order if the order\n * type is restricted and the offerer or zone are not the caller.\n */\nstruct AdvancedOrder {\n OrderParameters parameters;\n uint120 numerator;\n uint120 denominator;\n bytes signature;\n bytes extraData;\n}\n\n/**\n * @dev Orders can be validated (either explicitly via `validate`, or as a\n * consequence of a full or partial fill), specifically cancelled (they can\n * also be cancelled in bulk via incrementing a per-zone counter), and\n * partially or fully filled (with the fraction filled represented by a\n * numerator and denominator).\n */\nstruct OrderStatus {\n bool isValidated;\n bool isCancelled;\n uint120 numerator;\n uint120 denominator;\n}\n\n/**\n * @dev A criteria resolver specifies an order, side (offer vs. consideration),\n * and item index. It then provides a chosen identifier (i.e. tokenId)\n * alongside a merkle proof demonstrating the identifier meets the required\n * criteria.\n */\nstruct CriteriaResolver {\n uint256 orderIndex;\n Side side;\n uint256 index;\n uint256 identifier;\n bytes32[] criteriaProof;\n}\n\n/**\n * @dev A fulfillment is applied to a group of orders. It decrements a series of\n * offer and consideration items, then generates a single execution\n * element. A given fulfillment can be applied to as many offer and\n * consideration items as desired, but must contain at least one offer and\n * at least one consideration that match. The fulfillment must also remain\n * consistent on all key parameters across all offer items (same offerer,\n * token, type, tokenId, and conduit preference) as well as across all\n * consideration items (token, type, tokenId, and recipient).\n */\nstruct Fulfillment {\n FulfillmentComponent[] offerComponents;\n FulfillmentComponent[] considerationComponents;\n}\n\n/**\n * @dev Each fulfillment component contains one index referencing a specific\n * order and another referencing a specific offer or consideration item.\n */\nstruct FulfillmentComponent {\n uint256 orderIndex;\n uint256 itemIndex;\n}\n\n/**\n * @dev An execution is triggered once all consideration items have been zeroed\n * out. It sends the item in question from the offerer to the item's\n * recipient, optionally sourcing approvals from either this contract\n * directly or from the offerer's chosen conduit if one is specified. An\n * execution is not provided as an argument, but rather is derived via\n * orders, criteria resolvers, and fulfillments (where the total number of\n * executions will be less than or equal to the total number of indicated\n * fulfillments) and returned as part of `matchOrders`.\n */\nstruct Execution {\n ReceivedItem item;\n address offerer;\n bytes32 conduitKey;\n}\n" }, "contracts/dependencies/yoga-labs/ApeCoinStaking.sol": { "content": "//SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"../openzeppelin/contracts/IERC20.sol\";\nimport \"../openzeppelin/contracts/SafeERC20.sol\";\nimport \"../openzeppelin/contracts/SafeCast.sol\";\nimport \"../openzeppelin/contracts/Ownable.sol\";\nimport \"../openzeppelin/contracts/ERC721Enumerable.sol\";\n\n/**\n * @title ApeCoin Staking Contract\n * @notice Stake ApeCoin across four different pools that release hourly rewards\n * @author HorizenLabs\n */\ncontract ApeCoinStaking is Ownable {\n using SafeCast for uint256;\n using SafeCast for int256;\n\n /// @notice State for ApeCoin, BAYC, MAYC, and Pair Pools\n struct Pool {\n uint48 lastRewardedTimestampHour;\n uint16 lastRewardsRangeIndex;\n uint96 stakedAmount;\n uint96 accumulatedRewardsPerShare;\n TimeRange[] timeRanges;\n }\n\n /// @notice Pool rules valid for a given duration of time.\n /// @dev All TimeRange timestamp values must represent whole hours\n struct TimeRange {\n uint48 startTimestampHour;\n uint48 endTimestampHour;\n uint96 rewardsPerHour;\n uint96 capPerPosition;\n }\n\n /// @dev Convenience struct for front-end applications\n struct PoolUI {\n uint256 poolId;\n uint256 stakedAmount;\n TimeRange currentTimeRange;\n }\n\n /// @dev Per address amount and reward tracking\n struct Position {\n uint256 stakedAmount;\n int256 rewardsDebt;\n }\n mapping (address => Position) public addressPosition;\n\n /// @dev Struct for depositing and withdrawing from the BAYC and MAYC NFT pools\n struct SingleNft {\n uint32 tokenId;\n uint224 amount;\n }\n /// @dev Struct for depositing from the BAKC (Pair) pool\n struct PairNftDepositWithAmount {\n uint32 mainTokenId;\n uint32 bakcTokenId;\n uint184 amount;\n }\n /// @dev Struct for withdrawing from the BAKC (Pair) pool\n struct PairNftWithdrawWithAmount {\n uint32 mainTokenId;\n uint32 bakcTokenId;\n uint184 amount;\n bool isUncommit;\n }\n /// @dev Struct for claiming from an NFT pool\n struct PairNft {\n uint128 mainTokenId;\n uint128 bakcTokenId;\n }\n /// @dev NFT paired status. Can be used bi-directionally (BAYC/MAYC -> BAKC) or (BAKC -> BAYC/MAYC)\n struct PairingStatus {\n uint248 tokenId;\n bool isPaired;\n }\n\n // @dev UI focused payload\n struct DashboardStake {\n uint256 poolId;\n uint256 tokenId;\n uint256 deposited;\n uint256 unclaimed;\n uint256 rewards24hr;\n DashboardPair pair;\n }\n /// @dev Sub struct for DashboardStake\n struct DashboardPair {\n uint256 mainTokenId;\n uint256 mainTypePoolId;\n }\n /// @dev Placeholder for pair status, used by ApeCoin Pool\n DashboardPair private NULL_PAIR = DashboardPair(0, 0);\n\n /// @notice Internal ApeCoin amount for distributing staking reward claims\n IERC20 public immutable apeCoin;\n uint256 private constant APE_COIN_PRECISION = 1e18;\n uint256 private constant MIN_DEPOSIT = 1 * APE_COIN_PRECISION;\n uint256 private constant SECONDS_PER_HOUR = 3600;\n uint256 private constant SECONDS_PER_MINUTE = 60;\n\n uint256 constant APECOIN_POOL_ID = 0;\n uint256 constant BAYC_POOL_ID = 1;\n uint256 constant MAYC_POOL_ID = 2;\n uint256 constant BAKC_POOL_ID = 3;\n Pool[4] public pools;\n\n /// @dev NFT contract mapping per pool\n mapping(uint256 => ERC721Enumerable) public nftContracts;\n /// @dev poolId => tokenId => nft position\n mapping(uint256 => mapping(uint256 => Position)) public nftPosition;\n /// @dev main type pool ID: 1: BAYC 2: MAYC => main token ID => bakc token ID\n mapping(uint256 => mapping(uint256 => PairingStatus)) public mainToBakc;\n /// @dev bakc Token ID => main type pool ID: 1: BAYC 2: MAYC => main token ID\n mapping(uint256 => mapping(uint256 => PairingStatus)) public bakcToMain;\n\n /** Custom Events */\n event UpdatePool(\n uint256 indexed poolId,\n uint256 lastRewardedBlock,\n uint256 stakedAmount,\n uint256 accumulatedRewardsPerShare\n );\n event Deposit(\n address indexed user,\n uint256 amount,\n address recipient\n );\n event DepositNft(\n address indexed user,\n uint256 indexed poolId,\n uint256 amount,\n uint256 tokenId\n );\n event DepositPairNft(\n address indexed user,\n uint256 amount,\n uint256 mainTypePoolId,\n uint256 mainTokenId,\n uint256 bakcTokenId\n );\n event Withdraw(\n address indexed user,\n uint256 amount,\n address recipient\n );\n event WithdrawNft(\n address indexed user,\n uint256 indexed poolId,\n uint256 amount,\n address recipient,\n uint256 tokenId\n );\n event WithdrawPairNft(\n address indexed user,\n uint256 amount,\n uint256 mainTypePoolId,\n uint256 mainTokenId,\n uint256 bakcTokenId\n );\n event ClaimRewards(\n address indexed user,\n uint256 amount,\n address recipient\n );\n event ClaimRewardsNft(\n address indexed user,\n uint256 indexed poolId,\n uint256 amount,\n uint256 tokenId\n );\n event ClaimRewardsPairNft(\n address indexed user,\n uint256 amount,\n uint256 mainTypePoolId,\n uint256 mainTokenId,\n uint256 bakcTokenId\n );\n\n error DepositMoreThanOneAPE();\n error InvalidPoolId();\n error StartMustBeGreaterThanEnd();\n error StartNotWholeHour();\n error EndNotWholeHour();\n error StartMustEqualLastEnd();\n error CallerNotOwner();\n error MainTokenNotOwnedOrPaired();\n error BAKCNotOwnedOrPaired();\n error BAKCAlreadyPaired();\n error ExceededCapAmount();\n error NotOwnerOfMain();\n error NotOwnerOfBAKC();\n error ProvidedTokensNotPaired();\n error ExceededStakedAmount();\n error NeitherTokenInPairOwnedByCaller();\n error SplitPairCantPartiallyWithdraw();\n error UncommitWrongParameters();\n\n /**\n * @notice Construct a new ApeCoinStaking instance\n * @param _apeCoinContractAddress The ApeCoin ERC20 contract address\n * @param _baycContractAddress The BAYC NFT contract address\n * @param _maycContractAddress The MAYC NFT contract address\n * @param _bakcContractAddress The BAKC NFT contract address\n */\n constructor(\n address _apeCoinContractAddress,\n address _baycContractAddress,\n address _maycContractAddress,\n address _bakcContractAddress\n ) {\n apeCoin = IERC20(_apeCoinContractAddress);\n nftContracts[BAYC_POOL_ID] = ERC721Enumerable(_baycContractAddress);\n nftContracts[MAYC_POOL_ID] = ERC721Enumerable(_maycContractAddress);\n nftContracts[BAKC_POOL_ID] = ERC721Enumerable(_bakcContractAddress);\n }\n\n // Deposit/Commit Methods\n\n /**\n * @notice Deposit ApeCoin to the ApeCoin Pool\n * @param _amount Amount in ApeCoin\n * @param _recipient Address the deposit it stored to\n * @dev ApeCoin deposit must be >= 1 ApeCoin\n */\n function depositApeCoin(uint256 _amount, address _recipient) public {\n if (_amount < MIN_DEPOSIT) revert DepositMoreThanOneAPE();\n updatePool(APECOIN_POOL_ID);\n\n Position storage position = addressPosition[_recipient];\n _deposit(APECOIN_POOL_ID, position, _amount);\n\n apeCoin.transferFrom(msg.sender, address(this), _amount);\n\n emit Deposit(msg.sender, _amount, _recipient);\n }\n\n /**\n * @notice Deposit ApeCoin to the ApeCoin Pool\n * @param _amount Amount in ApeCoin\n * @dev Deposit on behalf of msg.sender. ApeCoin deposit must be >= 1 ApeCoin\n */\n function depositSelfApeCoin(uint256 _amount) external {\n depositApeCoin(_amount, msg.sender);\n }\n\n /**\n * @notice Deposit ApeCoin to the BAYC Pool\n * @param _nfts Array of SingleNft structs\n * @dev Commits 1 or more BAYC NFTs, each with an ApeCoin amount to the BAYC pool.\\\n * Each BAYC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the BAYC pool cap amount.\n */\n function depositBAYC(SingleNft[] calldata _nfts) external {\n _depositNft(BAYC_POOL_ID, _nfts);\n }\n\n /**\n * @notice Deposit ApeCoin to the MAYC Pool\n * @param _nfts Array of SingleNft structs\n * @dev Commits 1 or more MAYC NFTs, each with an ApeCoin amount to the MAYC pool.\\\n * Each MAYC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the MAYC pool cap amount.\n */\n function depositMAYC(SingleNft[] calldata _nfts) external {\n _depositNft(MAYC_POOL_ID, _nfts);\n }\n\n /**\n * @notice Deposit ApeCoin to the Pair Pool, where Pair = (BAYC + BAKC) or (MAYC + BAKC)\n * @param _baycPairs Array of PairNftDepositWithAmount structs\n * @param _maycPairs Array of PairNftDepositWithAmount structs\n * @dev Commits 1 or more Pairs, each with an ApeCoin amount to the Pair pool.\\\n * Each BAKC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the Pair pool cap amount.\\\n * Example 1: BAYC + BAKC + 1 ApeCoin: [[0, 0, \"1000000000000000000\"],[]]\\\n * Example 2: MAYC + BAKC + 1 ApeCoin: [[], [0, 0, \"1000000000000000000\"]]\\\n * Example 3: (BAYC + BAKC + 1 ApeCoin) and (MAYC + BAKC + 1 ApeCoin): [[0, 0, \"1000000000000000000\"], [0, 1, \"1000000000000000000\"]]\n */\n function depositBAKC(PairNftDepositWithAmount[] calldata _baycPairs, PairNftDepositWithAmount[] calldata _maycPairs) external {\n updatePool(BAKC_POOL_ID);\n _depositPairNft(BAYC_POOL_ID, _baycPairs);\n _depositPairNft(MAYC_POOL_ID, _maycPairs);\n }\n\n // Claim Rewards Methods\n\n /**\n * @notice Claim rewards for msg.sender and send to recipient\n * @param _recipient Address to send claim reward to\n */\n function claimApeCoin(address _recipient) public {\n updatePool(APECOIN_POOL_ID);\n\n Position storage position = addressPosition[msg.sender];\n uint256 rewardsToBeClaimed = _claim(APECOIN_POOL_ID, position, _recipient);\n\n emit ClaimRewards(msg.sender, rewardsToBeClaimed, _recipient);\n }\n\n /// @notice Claim and send rewards\n function claimSelfApeCoin() external {\n claimApeCoin(msg.sender);\n }\n\n /**\n * @notice Claim rewards for array of BAYC NFTs and send to recipient\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n * @param _recipient Address to send claim reward to\n */\n function claimBAYC(uint256[] calldata _nfts, address _recipient) external {\n _claimNft(BAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Claim rewards for array of BAYC NFTs\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n */\n function claimSelfBAYC(uint256[] calldata _nfts) external {\n _claimNft(BAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Claim rewards for array of MAYC NFTs and send to recipient\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n * @param _recipient Address to send claim reward to\n */\n function claimMAYC(uint256[] calldata _nfts, address _recipient) external {\n _claimNft(MAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Claim rewards for array of MAYC NFTs\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n */\n function claimSelfMAYC(uint256[] calldata _nfts) external {\n _claimNft(MAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Claim rewards for array of Paired NFTs and send to recipient\n * @param _baycPairs Array of Paired BAYC NFTs owned and committed by the msg.sender\n * @param _maycPairs Array of Paired MAYC NFTs owned and committed by the msg.sender\n * @param _recipient Address to send claim reward to\n */\n function claimBAKC(PairNft[] calldata _baycPairs, PairNft[] calldata _maycPairs, address _recipient) public {\n updatePool(BAKC_POOL_ID);\n _claimPairNft(BAYC_POOL_ID, _baycPairs, _recipient);\n _claimPairNft(MAYC_POOL_ID, _maycPairs, _recipient);\n }\n\n /**\n * @notice Claim rewards for array of Paired NFTs\n * @param _baycPairs Array of Paired BAYC NFTs owned and committed by the msg.sender\n * @param _maycPairs Array of Paired MAYC NFTs owned and committed by the msg.sender\n */\n function claimSelfBAKC(PairNft[] calldata _baycPairs, PairNft[] calldata _maycPairs) external {\n claimBAKC(_baycPairs, _maycPairs, msg.sender);\n }\n\n // Uncommit/Withdraw Methods\n\n /**\n * @notice Withdraw staked ApeCoin from the ApeCoin pool. Performs an automatic claim as part of the withdraw process.\n * @param _amount Amount of ApeCoin\n * @param _recipient Address to send withdraw amount and claim to\n */\n function withdrawApeCoin(uint256 _amount, address _recipient) public {\n updatePool(APECOIN_POOL_ID);\n\n Position storage position = addressPosition[msg.sender];\n if (_amount == position.stakedAmount) {\n uint256 rewardsToBeClaimed = _claim(APECOIN_POOL_ID, position, _recipient);\n emit ClaimRewards(msg.sender, rewardsToBeClaimed, _recipient);\n }\n _withdraw(APECOIN_POOL_ID, position, _amount);\n\n apeCoin.transfer(_recipient, _amount);\n\n emit Withdraw(msg.sender, _amount, _recipient);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the ApeCoin pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _amount Amount of ApeCoin\n */\n function withdrawSelfApeCoin(uint256 _amount) external {\n withdrawApeCoin(_amount, msg.sender);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the BAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of BAYC NFT's with staked amounts\n * @param _recipient Address to send withdraw amount and claim to\n */\n function withdrawBAYC(SingleNft[] calldata _nfts, address _recipient) external {\n _withdrawNft(BAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the BAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of BAYC NFT's with staked amounts\n */\n function withdrawSelfBAYC(SingleNft[] calldata _nfts) external {\n _withdrawNft(BAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the MAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of MAYC NFT's with staked amounts\n * @param _recipient Address to send withdraw amount and claim to\n */\n function withdrawMAYC(SingleNft[] calldata _nfts, address _recipient) external {\n _withdrawNft(MAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the MAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of MAYC NFT's with staked amounts\n */\n function withdrawSelfMAYC(SingleNft[] calldata _nfts) external {\n _withdrawNft(MAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the Pair pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _baycPairs Array of Paired BAYC NFT's with staked amounts and isUncommit boolean\n * @param _maycPairs Array of Paired MAYC NFT's with staked amounts and isUncommit boolean\n * @dev if pairs have split ownership and BAKC is attempting a withdraw, the withdraw must be for the total staked amount\n */\n function withdrawBAKC(PairNftWithdrawWithAmount[] calldata _baycPairs, PairNftWithdrawWithAmount[] calldata _maycPairs) external {\n updatePool(BAKC_POOL_ID);\n _withdrawPairNft(BAYC_POOL_ID, _baycPairs);\n _withdrawPairNft(MAYC_POOL_ID, _maycPairs);\n }\n\n // Time Range Methods\n\n /**\n * @notice Add single time range with a given rewards per hour for a given pool\n * @dev In practice one Time Range will represent one quarter (defined by `_startTimestamp`and `_endTimeStamp` as whole hours)\n * where the rewards per hour is constant for a given pool.\n * @param _poolId Available pool values 0-3\n * @param _amount Total amount of ApeCoin to be distributed over the range\n * @param _startTimestamp Whole hour timestamp representation\n * @param _endTimeStamp Whole hour timestamp representation\n * @param _capPerPosition Per position cap amount determined by poolId\n */\n function addTimeRange(\n uint256 _poolId,\n uint256 _amount,\n uint256 _startTimestamp,\n uint256 _endTimeStamp,\n uint256 _capPerPosition) external onlyOwner\n {\n if (_poolId > BAKC_POOL_ID) revert InvalidPoolId();\n if (_startTimestamp >= _endTimeStamp) revert StartMustBeGreaterThanEnd();\n if (getMinute(_startTimestamp) > 0 || getSecond(_startTimestamp) > 0) revert StartNotWholeHour();\n if (getMinute(_endTimeStamp) > 0 || getSecond(_endTimeStamp) > 0) revert EndNotWholeHour();\n\n Pool storage pool = pools[_poolId];\n uint256 length = pool.timeRanges.length;\n if (length > 0) {\n if (_startTimestamp != pool.timeRanges[length - 1].endTimestampHour) revert StartMustEqualLastEnd();\n }\n\n uint256 hoursInSeconds = _endTimeStamp - _startTimestamp;\n uint256 rewardsPerHour = _amount * SECONDS_PER_HOUR / hoursInSeconds;\n\n TimeRange memory next = TimeRange(_startTimestamp.toUint48(), _endTimeStamp.toUint48(),\n rewardsPerHour.toUint96(), _capPerPosition.toUint96());\n pool.timeRanges.push(next);\n }\n\n /**\n * @notice Removes the last Time Range for a given pool.\n * @param _poolId Available pool values 0-3\n */\n function removeLastTimeRange(uint256 _poolId) external onlyOwner {\n pools[_poolId].timeRanges.pop();\n }\n\n /**\n * @notice Lookup method for a TimeRange struct\n * @return TimeRange A Pool's timeRanges struct by index.\n * @param _poolId Available pool values 0-3\n * @param _index Target index in a Pool's timeRanges array\n */\n function getTimeRangeBy(uint256 _poolId, uint256 _index) public view returns (TimeRange memory) {\n return pools[_poolId].timeRanges[_index];\n }\n\n // Pool Methods\n\n /**\n * @notice Lookup available rewards for a pool over a given time range\n * @return uint256 The amount of ApeCoin rewards to be distributed by pool for a given time range\n * @return uint256 The amount of time ranges\n * @param _poolId Available pool values 0-3\n * @param _from Whole hour timestamp representation\n * @param _to Whole hour timestamp representation\n */\n function rewardsBy(uint256 _poolId, uint256 _from, uint256 _to) public view returns (uint256, uint256) {\n Pool memory pool = pools[_poolId];\n\n uint256 currentIndex = pool.lastRewardsRangeIndex;\n if(_to < pool.timeRanges[0].startTimestampHour) return (0, currentIndex);\n\n while(_from > pool.timeRanges[currentIndex].endTimestampHour && _to > pool.timeRanges[currentIndex].endTimestampHour) {\n unchecked {\n ++currentIndex;\n }\n }\n\n uint256 rewards;\n TimeRange memory current;\n uint256 startTimestampHour;\n uint256 endTimestampHour;\n uint256 length = pool.timeRanges.length;\n for(uint256 i = currentIndex; i < length;) {\n current = pool.timeRanges[i];\n startTimestampHour = _from <= current.startTimestampHour ? current.startTimestampHour : _from;\n endTimestampHour = _to <= current.endTimestampHour ? _to : current.endTimestampHour;\n\n rewards = rewards + (endTimestampHour - startTimestampHour) * current.rewardsPerHour / SECONDS_PER_HOUR;\n\n if(_to <= endTimestampHour) {\n return (rewards, i);\n }\n unchecked {\n ++i;\n }\n }\n\n return (rewards, length - 1);\n }\n\n /**\n * @notice Updates reward variables `lastRewardedTimestampHour`, `accumulatedRewardsPerShare` and `lastRewardsRangeIndex`\n * for a given pool.\n * @param _poolId Available pool values 0-3\n */\n function updatePool(uint256 _poolId) public {\n Pool storage pool = pools[_poolId];\n\n if (block.timestamp < pool.timeRanges[0].startTimestampHour) return;\n if (block.timestamp <= pool.lastRewardedTimestampHour + SECONDS_PER_HOUR) return;\n\n uint48 lastTimestampHour = pool.timeRanges[pool.timeRanges.length-1].endTimestampHour;\n uint48 previousTimestampHour = getPreviousTimestampHour().toUint48();\n\n if (pool.stakedAmount == 0) {\n pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;\n return;\n }\n\n (uint256 rewards, uint256 index) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, previousTimestampHour);\n if (pool.lastRewardsRangeIndex != index) {\n pool.lastRewardsRangeIndex = index.toUint16();\n }\n pool.accumulatedRewardsPerShare = (pool.accumulatedRewardsPerShare + (rewards * APE_COIN_PRECISION) / pool.stakedAmount).toUint96();\n pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;\n\n emit UpdatePool(_poolId, pool.lastRewardedTimestampHour, pool.stakedAmount, pool.accumulatedRewardsPerShare);\n }\n\n // Read Methods\n\n function getCurrentTimeRangeIndex(Pool memory pool) private view returns (uint256) {\n uint256 current = pool.lastRewardsRangeIndex;\n\n if (block.timestamp < pool.timeRanges[current].startTimestampHour) return current;\n for(current = pool.lastRewardsRangeIndex; current < pool.timeRanges.length; ++current) {\n TimeRange memory currentTimeRange = pool.timeRanges[current];\n if (currentTimeRange.startTimestampHour <= block.timestamp && block.timestamp <= currentTimeRange.endTimestampHour) return current;\n }\n revert(\"distribution ended\");\n }\n\n /**\n * @notice Fetches a PoolUI struct (poolId, stakedAmount, currentTimeRange) for each reward pool\n * @return PoolUI for ApeCoin.\n * @return PoolUI for BAYC.\n * @return PoolUI for MAYC.\n * @return PoolUI for BAKC.\n */\n function getPoolsUI() public view returns (PoolUI memory, PoolUI memory, PoolUI memory, PoolUI memory) {\n Pool memory apeCoinPool = pools[0];\n Pool memory baycPool = pools[1];\n Pool memory maycPool = pools[2];\n Pool memory bakcPool = pools[3];\n uint256 current = getCurrentTimeRangeIndex(apeCoinPool);\n return (PoolUI(0,apeCoinPool.stakedAmount, apeCoinPool.timeRanges[current]),\n PoolUI(1,baycPool.stakedAmount, baycPool.timeRanges[current]),\n PoolUI(2,maycPool.stakedAmount, maycPool.timeRanges[current]),\n PoolUI(3,bakcPool.stakedAmount, bakcPool.timeRanges[current]));\n }\n\n /**\n * @notice Fetches an address total staked amount, used by voting contract\n * @return amount uint256 staked amount for all pools.\n * @param _address An Ethereum address\n */\n function stakedTotal(address _address) external view returns (uint256) {\n uint256 total = addressPosition[_address].stakedAmount;\n\n total += _stakedTotal(BAYC_POOL_ID, _address);\n total += _stakedTotal(MAYC_POOL_ID, _address);\n total += _stakedTotalPair(_address);\n\n return total;\n }\n\n function _stakedTotal(uint256 _poolId, address _addr) private view returns (uint256) {\n uint256 total = 0;\n uint256 nftCount = nftContracts[_poolId].balanceOf(_addr);\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 tokenId = nftContracts[_poolId].tokenOfOwnerByIndex(_addr, i);\n total += nftPosition[_poolId][tokenId].stakedAmount;\n }\n\n return total;\n }\n\n function _stakedTotalPair(address _addr) private view returns (uint256) {\n uint256 total = 0;\n\n uint256 nftCount = nftContracts[BAYC_POOL_ID].balanceOf(_addr);\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 baycTokenId = nftContracts[BAYC_POOL_ID].tokenOfOwnerByIndex(_addr, i);\n if (mainToBakc[BAYC_POOL_ID][baycTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[BAYC_POOL_ID][baycTokenId].tokenId;\n total += nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;\n }\n }\n\n nftCount = nftContracts[MAYC_POOL_ID].balanceOf(_addr);\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 maycTokenId = nftContracts[MAYC_POOL_ID].tokenOfOwnerByIndex(_addr, i);\n if (mainToBakc[MAYC_POOL_ID][maycTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[MAYC_POOL_ID][maycTokenId].tokenId;\n total += nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;\n }\n }\n\n return total;\n }\n\n /**\n * @notice Fetches a DashboardStake = [poolId, tokenId, deposited, unclaimed, rewards24Hrs, paired] \\\n * for each pool, for an Ethereum address\n * @return dashboardStakes An array of DashboardStake structs\n * @param _address An Ethereum address\n */\n function getAllStakes(address _address) public view returns (DashboardStake[] memory) {\n\n DashboardStake memory apeCoinStake = getApeCoinStake(_address);\n DashboardStake[] memory baycStakes = getBaycStakes(_address);\n DashboardStake[] memory maycStakes = getMaycStakes(_address);\n DashboardStake[] memory bakcStakes = getBakcStakes(_address);\n DashboardStake[] memory splitStakes = getSplitStakes(_address);\n\n uint256 count = (baycStakes.length + maycStakes.length + bakcStakes.length + splitStakes.length + 1);\n DashboardStake[] memory allStakes = new DashboardStake[](count);\n\n uint256 offset = 0;\n allStakes[offset] = apeCoinStake;\n ++offset;\n\n for(uint256 i = 0; i < baycStakes.length; ++i) {\n allStakes[offset] = baycStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < maycStakes.length; ++i) {\n allStakes[offset] = maycStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < bakcStakes.length; ++i) {\n allStakes[offset] = bakcStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < splitStakes.length; ++i) {\n allStakes[offset] = splitStakes[i];\n ++offset;\n }\n\n return allStakes;\n }\n\n /**\n * @notice Fetches a DashboardStake for the ApeCoin pool\n * @return dashboardStake A dashboardStake struct\n * @param _address An Ethereum address\n */\n function getApeCoinStake(address _address) public view returns (DashboardStake memory) {\n uint256 tokenId = 0;\n uint256 deposited = addressPosition[_address].stakedAmount;\n uint256 unclaimed = deposited > 0 ? this.pendingRewards(0, _address, tokenId) : 0;\n uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(0, _address, 0) : 0;\n\n return DashboardStake(APECOIN_POOL_ID, tokenId, deposited, unclaimed, rewards24Hrs, NULL_PAIR);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the BAYC pool\n * @return dashboardStakes An array of DashboardStake structs\n */\n function getBaycStakes(address _address) public view returns (DashboardStake[] memory) {\n return _getStakes(_address, BAYC_POOL_ID);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the MAYC pool\n * @return dashboardStakes An array of DashboardStake structs\n */\n function getMaycStakes(address _address) public view returns (DashboardStake[] memory) {\n return _getStakes(_address, MAYC_POOL_ID);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the BAKC pool\n * @return dashboardStakes An array of DashboardStake structs\n */\n function getBakcStakes(address _address) public view returns (DashboardStake[] memory) {\n return _getStakes(_address, BAKC_POOL_ID);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the Pair Pool when ownership is split \\\n * ie (BAYC/MAYC) and BAKC in pair pool have different owners.\n * @return dashboardStakes An array of DashboardStake structs\n * @param _address An Ethereum address\n */\n function getSplitStakes(address _address) public view returns (DashboardStake[] memory) {\n uint256 baycSplits = _getSplitStakeCount(nftContracts[BAYC_POOL_ID].balanceOf(_address), _address, BAYC_POOL_ID);\n uint256 maycSplits = _getSplitStakeCount(nftContracts[MAYC_POOL_ID].balanceOf(_address), _address, MAYC_POOL_ID);\n uint256 totalSplits = baycSplits + maycSplits;\n\n if(totalSplits == 0) {\n return new DashboardStake[](0);\n }\n\n DashboardStake[] memory baycSplitStakes = _getSplitStakes(baycSplits, _address, BAYC_POOL_ID);\n DashboardStake[] memory maycSplitStakes = _getSplitStakes(maycSplits, _address, MAYC_POOL_ID);\n\n DashboardStake[] memory splitStakes = new DashboardStake[](totalSplits);\n uint256 offset = 0;\n for(uint256 i = 0; i < baycSplitStakes.length; ++i) {\n splitStakes[offset] = baycSplitStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < maycSplitStakes.length; ++i) {\n splitStakes[offset] = maycSplitStakes[i];\n ++offset;\n }\n\n return splitStakes;\n }\n\n function _getSplitStakes(uint256 splits, address _address, uint256 _mainPoolId) private view returns (DashboardStake[] memory) {\n\n DashboardStake[] memory dashboardStakes = new DashboardStake[](splits);\n uint256 counter;\n\n for(uint256 i = 0; i < nftContracts[_mainPoolId].balanceOf(_address); ++i) {\n uint256 mainTokenId = nftContracts[_mainPoolId].tokenOfOwnerByIndex(_address, i);\n if(mainToBakc[_mainPoolId][mainTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[_mainPoolId][mainTokenId].tokenId;\n address currentOwner = nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId);\n\n /* Split Pair Check*/\n if (currentOwner != _address) {\n uint256 deposited = nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;\n uint256 unclaimed = deposited > 0 ? this.pendingRewards(BAKC_POOL_ID, currentOwner, bakcTokenId) : 0;\n uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(BAKC_POOL_ID, currentOwner, bakcTokenId): 0;\n\n DashboardPair memory pair = NULL_PAIR;\n if(bakcToMain[bakcTokenId][_mainPoolId].isPaired) {\n pair = DashboardPair(bakcToMain[bakcTokenId][_mainPoolId].tokenId, _mainPoolId);\n }\n\n DashboardStake memory dashboardStake = DashboardStake(BAKC_POOL_ID, bakcTokenId, deposited, unclaimed, rewards24Hrs, pair);\n dashboardStakes[counter] = dashboardStake;\n ++counter;\n }\n }\n }\n\n return dashboardStakes;\n }\n\n function _getSplitStakeCount(uint256 nftCount, address _address, uint256 _mainPoolId) private view returns (uint256) {\n uint256 splitCount;\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 mainTokenId = nftContracts[_mainPoolId].tokenOfOwnerByIndex(_address, i);\n if(mainToBakc[_mainPoolId][mainTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[_mainPoolId][mainTokenId].tokenId;\n address currentOwner = nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId);\n if (currentOwner != _address) {\n ++splitCount;\n }\n }\n }\n\n return splitCount;\n }\n\n function _getStakes(address _address, uint256 _poolId) private view returns (DashboardStake[] memory) {\n uint256 nftCount = nftContracts[_poolId].balanceOf(_address);\n DashboardStake[] memory dashboardStakes = nftCount > 0 ? new DashboardStake[](nftCount) : new DashboardStake[](0);\n\n if(nftCount == 0) {\n return dashboardStakes;\n }\n\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 tokenId = nftContracts[_poolId].tokenOfOwnerByIndex(_address, i);\n uint256 deposited = nftPosition[_poolId][tokenId].stakedAmount;\n uint256 unclaimed = deposited > 0 ? this.pendingRewards(_poolId, _address, tokenId) : 0;\n uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(_poolId, _address, tokenId): 0;\n\n DashboardPair memory pair = NULL_PAIR;\n if(_poolId == BAKC_POOL_ID) {\n if(bakcToMain[tokenId][BAYC_POOL_ID].isPaired) {\n pair = DashboardPair(bakcToMain[tokenId][BAYC_POOL_ID].tokenId, BAYC_POOL_ID);\n } else if(bakcToMain[tokenId][MAYC_POOL_ID].isPaired) {\n pair = DashboardPair(bakcToMain[tokenId][MAYC_POOL_ID].tokenId, MAYC_POOL_ID);\n }\n }\n\n DashboardStake memory dashboardStake = DashboardStake(_poolId, tokenId, deposited, unclaimed, rewards24Hrs, pair);\n dashboardStakes[i] = dashboardStake;\n }\n\n return dashboardStakes;\n }\n\n function _estimate24HourRewards(uint256 _poolId, address _address, uint256 _tokenId) private view returns (uint256) {\n Pool memory pool = pools[_poolId];\n Position memory position = _poolId == 0 ? addressPosition[_address]: nftPosition[_poolId][_tokenId];\n\n TimeRange memory rewards = getTimeRangeBy(_poolId, pool.lastRewardsRangeIndex);\n return (position.stakedAmount * uint256(rewards.rewardsPerHour) * 24) / uint256(pool.stakedAmount);\n }\n\n /**\n * @notice Fetches the current amount of claimable ApeCoin rewards for a given position from a given pool.\n * @return uint256 value of pending rewards\n * @param _poolId Available pool values 0-3\n * @param _address Address to lookup Position for\n * @param _tokenId An NFT id\n */\n function pendingRewards(uint256 _poolId, address _address, uint256 _tokenId) external view returns (uint256) {\n Pool memory pool = pools[_poolId];\n Position memory position = _poolId == 0 ? addressPosition[_address]: nftPosition[_poolId][_tokenId];\n\n (uint256 rewardsSinceLastCalculated,) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, getPreviousTimestampHour());\n uint256 accumulatedRewardsPerShare = pool.accumulatedRewardsPerShare;\n\n if (block.timestamp > pool.lastRewardedTimestampHour + SECONDS_PER_HOUR && pool.stakedAmount != 0) {\n accumulatedRewardsPerShare = accumulatedRewardsPerShare + rewardsSinceLastCalculated * APE_COIN_PRECISION / pool.stakedAmount;\n }\n return ((position.stakedAmount * accumulatedRewardsPerShare).toInt256() - position.rewardsDebt).toUint256() / APE_COIN_PRECISION;\n }\n\n // Convenience methods for timestamp calculation\n\n /// @notice the minutes (0 to 59) of a timestamp\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % SECONDS_PER_HOUR;\n minute = secs / SECONDS_PER_MINUTE;\n }\n\n /// @notice the seconds (0 to 59) of a timestamp\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % SECONDS_PER_MINUTE;\n }\n\n /// @notice the previous whole hour of a timestamp\n function getPreviousTimestampHour() internal view returns (uint256) {\n return block.timestamp - (getMinute(block.timestamp) * 60 + getSecond(block.timestamp));\n }\n\n // Private Methods - shared logic\n function _deposit(uint256 _poolId, Position storage _position, uint256 _amount) private {\n Pool storage pool = pools[_poolId];\n\n _position.stakedAmount += _amount;\n pool.stakedAmount += _amount.toUint96();\n _position.rewardsDebt += (_amount * pool.accumulatedRewardsPerShare).toInt256();\n }\n\n function _depositNft(uint256 _poolId, SingleNft[] calldata _nfts) private {\n updatePool(_poolId);\n uint256 tokenId;\n uint256 amount;\n Position storage position;\n uint256 length = _nfts.length;\n uint256 totalDeposit;\n for(uint256 i; i < length;) {\n tokenId = _nfts[i].tokenId;\n position = nftPosition[_poolId][tokenId];\n if (position.stakedAmount == 0) {\n if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();\n }\n amount = _nfts[i].amount;\n _depositNftGuard(_poolId, position, amount);\n totalDeposit += amount;\n emit DepositNft(msg.sender, _poolId, amount, tokenId);\n unchecked {\n ++i;\n }\n }\n if (totalDeposit > 0) apeCoin.transferFrom(msg.sender, address(this), totalDeposit);\n }\n\n function _depositPairNft(uint256 mainTypePoolId, PairNftDepositWithAmount[] calldata _nfts) private {\n uint256 length = _nfts.length;\n uint256 totalDeposit;\n PairNftDepositWithAmount memory pair;\n Position storage position;\n for(uint256 i; i < length;) {\n pair = _nfts[i];\n position = nftPosition[BAKC_POOL_ID][pair.bakcTokenId];\n\n if(position.stakedAmount == 0) {\n if (nftContracts[mainTypePoolId].ownerOf(pair.mainTokenId) != msg.sender\n || mainToBakc[mainTypePoolId][pair.mainTokenId].isPaired) revert MainTokenNotOwnedOrPaired();\n if (nftContracts[BAKC_POOL_ID].ownerOf(pair.bakcTokenId) != msg.sender\n || bakcToMain[pair.bakcTokenId][mainTypePoolId].isPaired) revert BAKCNotOwnedOrPaired();\n\n mainToBakc[mainTypePoolId][pair.mainTokenId] = PairingStatus(pair.bakcTokenId, true);\n bakcToMain[pair.bakcTokenId][mainTypePoolId] = PairingStatus(pair.mainTokenId, true);\n } else if (pair.mainTokenId != bakcToMain[pair.bakcTokenId][mainTypePoolId].tokenId\n || pair.bakcTokenId != mainToBakc[mainTypePoolId][pair.mainTokenId].tokenId)\n revert BAKCAlreadyPaired();\n\n _depositNftGuard(BAKC_POOL_ID, position, pair.amount);\n totalDeposit += pair.amount;\n emit DepositPairNft(msg.sender, pair.amount, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);\n unchecked {\n ++i;\n }\n }\n if (totalDeposit > 0) apeCoin.transferFrom(msg.sender, address(this), totalDeposit);\n }\n\n function _depositNftGuard(uint256 _poolId, Position storage _position, uint256 _amount) private {\n if (_amount < MIN_DEPOSIT) revert DepositMoreThanOneAPE();\n if (_amount + _position.stakedAmount > pools[_poolId].timeRanges[pools[_poolId].lastRewardsRangeIndex].capPerPosition)\n revert ExceededCapAmount();\n\n _deposit(_poolId, _position, _amount);\n }\n\n function _claim(uint256 _poolId, Position storage _position, address _recipient) private returns (uint256 rewardsToBeClaimed) {\n Pool storage pool = pools[_poolId];\n\n int256 accumulatedApeCoins = (_position.stakedAmount * uint256(pool.accumulatedRewardsPerShare)).toInt256();\n rewardsToBeClaimed = (accumulatedApeCoins - _position.rewardsDebt).toUint256() / APE_COIN_PRECISION;\n\n _position.rewardsDebt = accumulatedApeCoins;\n\n if (rewardsToBeClaimed != 0) {\n apeCoin.transfer(_recipient, rewardsToBeClaimed);\n }\n }\n\n function _claimNft(uint256 _poolId, uint256[] calldata _nfts, address _recipient) private {\n updatePool(_poolId);\n uint256 tokenId;\n uint256 rewardsToBeClaimed;\n uint256 length = _nfts.length;\n for(uint256 i; i < length;) {\n tokenId = _nfts[i];\n if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();\n Position storage position = nftPosition[_poolId][tokenId];\n rewardsToBeClaimed = _claim(_poolId, position, _recipient);\n emit ClaimRewardsNft(msg.sender, _poolId, rewardsToBeClaimed, tokenId);\n unchecked {\n ++i;\n }\n }\n }\n\n function _claimPairNft(uint256 mainTypePoolId, PairNft[] calldata _pairs, address _recipient) private {\n uint256 length = _pairs.length;\n uint256 mainTokenId;\n uint256 bakcTokenId;\n Position storage position;\n PairingStatus storage mainToSecond;\n PairingStatus storage secondToMain;\n for(uint256 i; i < length;) {\n mainTokenId = _pairs[i].mainTokenId;\n if (nftContracts[mainTypePoolId].ownerOf(mainTokenId) != msg.sender) revert NotOwnerOfMain();\n\n bakcTokenId = _pairs[i].bakcTokenId;\n if (nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId) != msg.sender) revert NotOwnerOfBAKC();\n\n mainToSecond = mainToBakc[mainTypePoolId][mainTokenId];\n secondToMain = bakcToMain[bakcTokenId][mainTypePoolId];\n\n if (mainToSecond.tokenId != bakcTokenId || !mainToSecond.isPaired\n || secondToMain.tokenId != mainTokenId || !secondToMain.isPaired) revert ProvidedTokensNotPaired();\n\n position = nftPosition[BAKC_POOL_ID][bakcTokenId];\n uint256 rewardsToBeClaimed = _claim(BAKC_POOL_ID, position, _recipient);\n emit ClaimRewardsPairNft(msg.sender, rewardsToBeClaimed, mainTypePoolId, mainTokenId, bakcTokenId);\n unchecked {\n ++i;\n }\n }\n }\n\n function _withdraw(uint256 _poolId, Position storage _position, uint256 _amount) private {\n if (_amount > _position.stakedAmount) revert ExceededStakedAmount();\n\n Pool storage pool = pools[_poolId];\n\n _position.stakedAmount -= _amount;\n pool.stakedAmount -= _amount.toUint96();\n _position.rewardsDebt -= (_amount * pool.accumulatedRewardsPerShare).toInt256();\n }\n\n function _withdrawNft(uint256 _poolId, SingleNft[] calldata _nfts, address _recipient) private {\n updatePool(_poolId);\n uint256 tokenId;\n uint256 amount;\n uint256 length = _nfts.length;\n uint256 totalWithdraw;\n Position storage position;\n for(uint256 i; i < length;) {\n tokenId = _nfts[i].tokenId;\n if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();\n\n amount = _nfts[i].amount;\n position = nftPosition[_poolId][tokenId];\n if (amount == position.stakedAmount) {\n uint256 rewardsToBeClaimed = _claim(_poolId, position, _recipient);\n emit ClaimRewardsNft(msg.sender, _poolId, rewardsToBeClaimed, tokenId);\n }\n _withdraw(_poolId, position, amount);\n totalWithdraw += amount;\n emit WithdrawNft(msg.sender, _poolId, amount, _recipient, tokenId);\n unchecked {\n ++i;\n }\n }\n if (totalWithdraw > 0) apeCoin.transfer(_recipient, totalWithdraw);\n }\n\n function _withdrawPairNft(uint256 mainTypePoolId, PairNftWithdrawWithAmount[] calldata _nfts) private {\n address mainTokenOwner;\n address bakcOwner;\n PairNftWithdrawWithAmount memory pair;\n PairingStatus storage mainToSecond;\n PairingStatus storage secondToMain;\n Position storage position;\n uint256 length = _nfts.length;\n for(uint256 i; i < length;) {\n pair = _nfts[i];\n mainTokenOwner = nftContracts[mainTypePoolId].ownerOf(pair.mainTokenId);\n bakcOwner = nftContracts[BAKC_POOL_ID].ownerOf(pair.bakcTokenId);\n\n if (mainTokenOwner != msg.sender) {\n if (bakcOwner != msg.sender) revert NeitherTokenInPairOwnedByCaller();\n }\n\n mainToSecond = mainToBakc[mainTypePoolId][pair.mainTokenId];\n secondToMain = bakcToMain[pair.bakcTokenId][mainTypePoolId];\n\n if (mainToSecond.tokenId != pair.bakcTokenId || !mainToSecond.isPaired\n || secondToMain.tokenId != pair.mainTokenId || !secondToMain.isPaired) revert ProvidedTokensNotPaired();\n\n position = nftPosition[BAKC_POOL_ID][pair.bakcTokenId];\n if(!pair.isUncommit) {\n if(pair.amount == position.stakedAmount) revert UncommitWrongParameters();\n }\n if (mainTokenOwner != bakcOwner) {\n if (!pair.isUncommit) revert SplitPairCantPartiallyWithdraw();\n }\n\n if (pair.isUncommit) {\n uint256 rewardsToBeClaimed = _claim(BAKC_POOL_ID, position, bakcOwner);\n mainToBakc[mainTypePoolId][pair.mainTokenId] = PairingStatus(0, false);\n bakcToMain[pair.bakcTokenId][mainTypePoolId] = PairingStatus(0, false);\n emit ClaimRewardsPairNft(msg.sender, rewardsToBeClaimed, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);\n }\n uint256 finalAmountToWithdraw = pair.isUncommit ? position.stakedAmount: pair.amount;\n _withdraw(BAKC_POOL_ID, position, finalAmountToWithdraw);\n apeCoin.transfer(mainTokenOwner, finalAmountToWithdraw);\n emit WithdrawPairNft(msg.sender, finalAmountToWithdraw, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);\n unchecked {\n ++i;\n }\n }\n }\n\n}\n" }, "contracts/interfaces/IACLManager.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\n\n/**\n * @title IACLManager\n *\n * @notice Defines the basic interface for the ACL Manager\n **/\ninterface IACLManager {\n /**\n * @notice Returns the contract address of the PoolAddressesProvider\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Returns the identifier of the PoolAdmin role\n * @return The id of the PoolAdmin role\n */\n function POOL_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the EmergencyAdmin role\n * @return The id of the EmergencyAdmin role\n */\n function EMERGENCY_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the RiskAdmin role\n * @return The id of the RiskAdmin role\n */\n function RISK_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the FlashBorrower role\n * @return The id of the FlashBorrower role\n */\n function FLASH_BORROWER_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the Bridge role\n * @return The id of the Bridge role\n */\n function BRIDGE_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the AssetListingAdmin role\n * @return The id of the AssetListingAdmin role\n */\n function ASSET_LISTING_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Set the role as admin of a specific role.\n * @dev By default the admin role for all roles is `DEFAULT_ADMIN_ROLE`.\n * @param role The role to be managed by the admin role\n * @param adminRole The admin role\n */\n function setRoleAdmin(bytes32 role, bytes32 adminRole) external;\n\n /**\n * @notice Adds a new admin as PoolAdmin\n * @param admin The address of the new admin\n */\n function addPoolAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as PoolAdmin\n * @param admin The address of the admin to remove\n */\n function removePoolAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is PoolAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is PoolAdmin, false otherwise\n */\n function isPoolAdmin(address admin) external view returns (bool);\n\n /**\n * @notice Adds a new admin as EmergencyAdmin\n * @param admin The address of the new admin\n */\n function addEmergencyAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as EmergencyAdmin\n * @param admin The address of the admin to remove\n */\n function removeEmergencyAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is EmergencyAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is EmergencyAdmin, false otherwise\n */\n function isEmergencyAdmin(address admin) external view returns (bool);\n\n /**\n * @notice Adds a new admin as RiskAdmin\n * @param admin The address of the new admin\n */\n function addRiskAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as RiskAdmin\n * @param admin The address of the admin to remove\n */\n function removeRiskAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is RiskAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is RiskAdmin, false otherwise\n */\n function isRiskAdmin(address admin) external view returns (bool);\n\n /**\n * @notice Adds a new address as FlashBorrower\n * @param borrower The address of the new FlashBorrower\n */\n function addFlashBorrower(address borrower) external;\n\n /**\n * @notice Removes an admin as FlashBorrower\n * @param borrower The address of the FlashBorrower to remove\n */\n function removeFlashBorrower(address borrower) external;\n\n /**\n * @notice Returns true if the address is FlashBorrower, false otherwise\n * @param borrower The address to check\n * @return True if the given address is FlashBorrower, false otherwise\n */\n function isFlashBorrower(address borrower) external view returns (bool);\n\n /**\n * @notice Adds a new address as Bridge\n * @param bridge The address of the new Bridge\n */\n function addBridge(address bridge) external;\n\n /**\n * @notice Removes an address as Bridge\n * @param bridge The address of the bridge to remove\n */\n function removeBridge(address bridge) external;\n\n /**\n * @notice Returns true if the address is Bridge, false otherwise\n * @param bridge The address to check\n * @return True if the given address is Bridge, false otherwise\n */\n function isBridge(address bridge) external view returns (bool);\n\n /**\n * @notice Adds a new admin as AssetListingAdmin\n * @param admin The address of the new admin\n */\n function addAssetListingAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as AssetListingAdmin\n * @param admin The address of the admin to remove\n */\n function removeAssetListingAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is AssetListingAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is AssetListingAdmin, false otherwise\n */\n function isAssetListingAdmin(address admin) external view returns (bool);\n}\n" }, "contracts/interfaces/ICreditDelegationToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title ICreditDelegationToken\n *\n * @notice Defines the basic interface for a token supporting credit delegation.\n **/\ninterface ICreditDelegationToken {\n /**\n * @dev Emitted on `approveDelegation` and `borrowAllowance\n * @param fromUser The address of the delegator\n * @param toUser The address of the delegatee\n * @param asset The address of the delegated asset\n * @param amount The amount being delegated\n */\n event BorrowAllowanceDelegated(\n address indexed fromUser,\n address indexed toUser,\n address indexed asset,\n uint256 amount\n );\n\n /**\n * @notice Delegates borrowing power to a user on the specific debt token.\n * Delegation will still respect the liquidation constraints (even if delegated, a\n * delegatee cannot force a delegator HF to go below 1)\n * @param delegatee The address receiving the delegated borrowing power\n * @param amount The maximum amount being delegated.\n **/\n function approveDelegation(address delegatee, uint256 amount) external;\n\n /**\n * @notice 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)\n external\n view\n returns (uint256);\n\n /**\n * @notice Delegates borrowing power to a user on the specific debt token via ERC712 signature\n * @param delegator The delegator of the credit\n * @param delegatee The delegatee that can use the credit\n * @param value The amount to be delegated\n * @param deadline The deadline timestamp, type(uint256).max for max deadline\n * @param v The V signature param\n * @param s The S signature param\n * @param r The R signature param\n */\n function delegationWithSig(\n address delegator,\n address delegatee,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n}\n" }, "contracts/interfaces/IInitializableDebtToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IRewardController} from \"./IRewardController.sol\";\nimport {IPool} from \"./IPool.sol\";\n\n/**\n * @title IInitializableDebtToken\n *\n * @notice Interface for the initialize function common between debt tokens\n **/\ninterface IInitializableDebtToken {\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 pool\n * @param incentivesController The address of the incentives controller for this xToken\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 * @param params A set of encoded parameters for additional initialization\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 bytes params\n );\n\n /**\n * @notice Initializes the debt token.\n * @param pool The pool contract that is initializing this contract\n * @param underlyingAsset The address of the underlying asset of this xToken (E.g. WETH for pWETH)\n * @param incentivesController The smart contract managing potential incentives distribution\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 * @param params A set of encoded parameters for additional initialization\n */\n function initialize(\n IPool pool,\n address underlyingAsset,\n IRewardController incentivesController,\n uint8 debtTokenDecimals,\n string memory debtTokenName,\n string memory debtTokenSymbol,\n bytes calldata params\n ) external;\n}\n" }, "contracts/interfaces/IParaProxy.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.10;\n\n/******************************************************************************\\\n* EIP-2535: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\ninterface IParaProxy {\n enum ProxyImplementationAction {\n Add,\n Replace,\n Remove\n }\n // Add=0, Replace=1, Remove=2\n\n struct ProxyImplementation {\n address implAddress;\n ProxyImplementationAction action;\n bytes4[] functionSelectors;\n }\n\n /// @notice Add/replace/remove any number of functions and optionally execute\n /// a function with delegatecall\n /// @param _implementationParams Contains the implementation addresses and function selectors\n /// @param _init The address of the contract or implementation to execute _calldata\n /// @param _calldata A function call, including function selector and arguments\n /// _calldata is executed with delegatecall on _init\n function updateImplementation(\n ProxyImplementation[] calldata _implementationParams,\n address _init,\n bytes calldata _calldata\n ) external;\n\n event ImplementationUpdated(\n ProxyImplementation[] _implementationParams,\n address _init,\n bytes _calldata\n );\n}\n" }, "contracts/interfaces/IParaProxyInterfaces.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/******************************************************************************\\\n* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\n// interfaces that are compatible with Diamond proxy loupe functions\ninterface IParaProxyInterfaces {\n /// These functions are expected to be called frequently\n /// by tools.\n\n struct Implementation {\n address implAddress;\n bytes4[] functionSelectors;\n }\n\n /// @notice Gets all facet addresses and their four byte function selectors.\n /// @return facets_ Implementation\n function facets() external view returns (Implementation[] memory facets_);\n\n /// @notice Gets all the function selectors supported by a specific facet.\n /// @param _facet The facet address.\n /// @return facetFunctionSelectors_\n function facetFunctionSelectors(address _facet)\n external\n view\n returns (bytes4[] memory facetFunctionSelectors_);\n\n /// @notice Get all the facet addresses used by a diamond.\n /// @return facetAddresses_\n function facetAddresses()\n external\n view\n returns (address[] memory facetAddresses_);\n\n /// @notice Gets the facet that supports the given selector.\n /// @dev If facet is not found return address(0).\n /// @param _functionSelector The function selector.\n /// @return facetAddress_ The facet address.\n function facetAddress(bytes4 _functionSelector)\n external\n view\n returns (address facetAddress_);\n}\n" }, "contracts/interfaces/IPool.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolCore} from \"./IPoolCore.sol\";\nimport {IPoolMarketplace} from \"./IPoolMarketplace.sol\";\nimport {IPoolParameters} from \"./IPoolParameters.sol\";\nimport {IParaProxyInterfaces} from \"./IParaProxyInterfaces.sol\";\nimport \"./IPoolApeStaking.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPool is\n IPoolCore,\n IPoolMarketplace,\n IPoolParameters,\n IPoolApeStaking,\n IParaProxyInterfaces\n{\n\n}\n" }, "contracts/interfaces/IPoolAddressesProvider.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\nimport {IParaProxy} from \"../interfaces/IParaProxy.sol\";\n\n/**\n * @title IPoolAddressesProvider\n *\n * @notice Defines the basic interface for a Pool Addresses Provider.\n **/\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param implementationParams The old address of the Pool\n * @param _init The new address to call upon upgrade\n * @param _calldata The calldata input for the call\n */\n event PoolUpdated(\n IParaProxy.ProxyImplementation[] indexed implementationParams,\n address _init,\n bytes _calldata\n );\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the WETH is updated.\n * @param oldAddress The old address of the WETH\n * @param newAddress The new address of the WETH\n */\n event WETHUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event ProtocolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationParams The params of the implementation update\n */\n event ParaProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n IParaProxy.ProxyImplementation[] indexed implementationParams\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationParams The params of the implementation update\n */\n event ParaProxyUpdated(\n bytes32 indexed id,\n address indexed proxyAddress,\n IParaProxy.ProxyImplementation[] indexed implementationParams\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @dev Emitted when the marketplace registered is updated\n * @param id The identifier of the marketplace\n * @param marketplace The address of the marketplace contract\n * @param adapter The address of the marketplace adapter contract\n * @param operator The address of the marketplace transfer helper\n * @param paused Is the marketplace adapter paused\n */\n event MarketplaceUpdated(\n bytes32 indexed id,\n address indexed marketplace,\n address indexed adapter,\n address operator,\n bool paused\n );\n\n /**\n * @notice Returns the id of the ParaSpace market to which this contract points to.\n * @return The market id\n **/\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple ParaSpace markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice 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 `newImplementationAddress`.\n * @dev 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 newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev 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 * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n **/\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param implementationParams Contains the implementation addresses and function selectors\n * @param _init The address of the contract or implementation to execute _calldata\n * @param _calldata A function call, including function selector and arguments\n * _calldata is executed with delegatecall on _init\n **/\n function updatePoolImpl(\n IParaProxy.ProxyImplementation[] calldata implementationParams,\n address _init,\n bytes calldata _calldata\n ) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n **/\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n **/\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n **/\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n **/\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Returns the address of the Wrapped ETH.\n * @return The address of the Wrapped ETH\n */\n function getWETH() external view returns (address);\n\n /**\n * @notice Returns the info of the marketplace.\n * @return The info of the marketplace\n */\n function getMarketplace(bytes32 id)\n external\n view\n returns (DataTypes.Marketplace memory);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n **/\n function setProtocolDataProvider(address newDataProvider) external;\n\n /**\n * @notice Updates the address of the WETH.\n * @param newWETH The address of the new WETH\n **/\n function setWETH(address newWETH) external;\n\n /**\n * @notice Updates the info of the marketplace.\n * @param marketplace The address of the marketplace\n * @param adapter The contract which handles marketplace logic\n * @param operator The contract which operates users' tokens\n **/\n function setMarketplace(\n bytes32 id,\n address marketplace,\n address adapter,\n address operator,\n bool paused\n ) external;\n}\n" }, "contracts/interfaces/IPoolApeStaking.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport \"../dependencies/yoga-labs/ApeCoinStaking.sol\";\n\n/**\n * @title IPoolApeStaking\n *\n * @notice Defines the basic interface for an ParaSpace Ape Staking Pool.\n **/\ninterface IPoolApeStaking {\n struct StakingInfo {\n // Contract address of BAYC/MAYC\n address nftAsset;\n // address of borrowing asset, can be Ape or cApe\n address borrowAsset;\n // Borrow amount of Ape from lending pool\n uint256 borrowAmount;\n // Cash amount of Ape from user wallet\n uint256 cashAmount;\n }\n\n /**\n * @notice Deposit ape coin to BAYC/MAYC pool or BAKC pool\n * @param stakingInfo Detail info of the staking\n * @param _nfts Array of BAYC/MAYC NFT's with staked amounts\n * @param _nftPairs Array of Paired BAYC/MAYC NFT's with staked amounts\n * @dev Need check User health factor > 1.\n */\n function borrowApeAndStake(\n StakingInfo calldata stakingInfo,\n ApeCoinStaking.SingleNft[] calldata _nfts,\n ApeCoinStaking.PairNftDepositWithAmount[] calldata _nftPairs\n ) external;\n\n /**\n * @notice Withdraw staked ApeCoin from the BAYC/MAYC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nfts Array of BAYC/MAYC NFT's with staked amounts\n * @dev Need check User health factor > 1.\n */\n function withdrawApeCoin(\n address nftAsset,\n ApeCoinStaking.SingleNft[] calldata _nfts\n ) external;\n\n /**\n * @notice Claim rewards for array of tokenIds from the BAYC/MAYC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n * @dev Need check User health factor > 1.\n */\n function claimApeCoin(address nftAsset, uint256[] calldata _nfts) external;\n\n /**\n * @notice Withdraw staked ApeCoin from the BAKC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nftPairs Array of Paired BAYC/MAYC NFT's with staked amounts\n * @dev Need check User health factor > 1.\n */\n function withdrawBAKC(\n address nftAsset,\n ApeCoinStaking.PairNftWithdrawWithAmount[] memory _nftPairs\n ) external;\n\n /**\n * @notice Claim rewards for array of tokenIds from the BAYC/MAYC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nftPairs Array of Paired BAYC/MAYC NFT's\n * @dev Need check User health factor > 1.\n */\n function claimBAKC(\n address nftAsset,\n ApeCoinStaking.PairNft[] calldata _nftPairs\n ) external;\n\n /**\n * @notice Unstake user Ape coin staking position and repay user debt\n * @param nftAsset Contract address of BAYC/MAYC\n * @param tokenId Token id of the ape staking position on\n * @dev Need check User health factor > 1.\n */\n function unstakeApePositionAndRepay(address nftAsset, uint256 tokenId)\n external;\n\n /**\n * @notice repay asset and supply asset for user\n * @param underlyingAsset Contract address of BAYC/MAYC\n * @param onBehalfOf The beneficiary of the repay and supply\n * @dev Convenient callback function for unstakeApePositionAndRepay. Only NToken of BAYC/MAYC can call this.\n */\n function repayAndSupply(\n address underlyingAsset,\n address onBehalfOf,\n uint256 totalAmount\n ) external;\n\n /**\n * @notice Claim user Ape coin reward and deposit to ape compound to get cApe, then deposit cApe to Lending pool for user\n * @param nftAsset Contract address of BAYC/MAYC\n * @param users array of user address\n * @param tokenIds array of user tokenId array\n */\n function claimApeAndCompound(\n address nftAsset,\n address[] calldata users,\n uint256[][] calldata tokenIds\n ) external;\n\n /**\n * @notice Claim user BAKC paired Ape coin reward and deposit to ape compound to get cApe, then deposit cApe to Lending pool for user\n * @param nftAsset Contract address of BAYC/MAYC\n * @param users array of user address\n * @param _nftPairs Array of Paired BAYC/MAYC NFT's\n */\n function claimPairedApeAndCompound(\n address nftAsset,\n address[] calldata users,\n ApeCoinStaking.PairNft[][] calldata _nftPairs\n ) external;\n\n /**\n * @notice get current incentive fee rate for claiming ape position reward to compound\n */\n function getApeCompoundFeeRate() external returns (uint256);\n}\n" }, "contracts/interfaces/IPoolCore.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPoolCore {\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the xTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n **/\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n event SupplyERC721(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n DataTypes.ERC721SupplyParams[] tokenData,\n uint16 indexed referralCode,\n bool fromNToken\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of xTokens\n * @param to The address that will receive the underlying asset\n * @param amount The amount to be withdrawn\n **/\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on withdrawERC721()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of xTokens\n * @param to The address that will receive the underlying asset\n * @param tokenIds The tokenIds to be withdrawn\n **/\n event WithdrawERC721(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256[] tokenIds\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n **/\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param usePTokens True if the repayment is done using xTokens, `false` if done with underlying asset directly\n **/\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool usePTokens\n );\n /**\n * @dev Emitted on setUserUseERC20AsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n **/\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseERC20AsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n **/\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param liquidationAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param borrower The address of the borrower getting liquidated\n * @param liquidationAmount The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receivePToken True if the liquidators wants to receive the collateral xTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n event LiquidateERC20(\n address indexed collateralAsset,\n address indexed liquidationAsset,\n address indexed borrower,\n uint256 liquidationAmount,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receivePToken\n );\n\n /**\n * @dev Emitted when a borrower's ERC721 asset is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param liquidationAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param borrower The address of the borrower getting liquidated\n * @param liquidationAmount The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralTokenId The token id of ERC721 asset received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveNToken True if the liquidators wants to receive the collateral NTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n event LiquidateERC721(\n address indexed collateralAsset,\n address indexed liquidationAsset,\n address indexed borrower,\n uint256 liquidationAmount,\n uint256 liquidatedCollateralTokenId,\n address liquidator,\n bool receiveNToken\n );\n\n /**\n * @dev Emitted on flashClaim\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash claim\n * @param nftAsset address of the underlying asset of NFT\n * @param tokenId The token id of the asset being flash borrowed\n **/\n event FlashClaim(\n address indexed target,\n address indexed initiator,\n address indexed nftAsset,\n uint256 tokenId\n );\n\n /**\n * @dev Allows smart contracts to access the tokens within one transaction, as long as the tokens taken is returned.\n *\n * Requirements:\n * - `nftTokenIds` must exist.\n *\n * @param receiverAddress The address of the contract receiving the tokens, implementing the IFlashClaimReceiver interface\n * @param nftAssets addresses of the underlying asset of NFT\n * @param nftTokenIds token ids of the underlying asset\n * @param params Variadic packed params to pass to the receiver as extra information\n */\n function flashClaim(\n address receiverAddress,\n address[] calldata nftAssets,\n uint256[][] calldata nftTokenIds,\n bytes calldata params\n ) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying xTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 pUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the xTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of xTokens\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 supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supplies multiple `tokenIds` of underlying ERC721 asset into the reserve, receiving in return overlying nTokens.\n * - E.g. User supplies 2 BAYC and gets in return 2 nBAYC\n * @param asset The address of the underlying asset to supply\n * @param tokenData The list of tokenIds and their collateral configs to be supplied\n * @param onBehalfOf The address that will receive the xTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of xTokens\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 supplyERC721(\n address asset,\n DataTypes.ERC721SupplyParams[] calldata tokenData,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Same as `supplyERC721` but this can only be called by NToken contract and doesn't require sending the underlying asset.\n * @param asset The address of the underlying asset to supply\n * @param tokenData The list of tokenIds and their collateral configs to be supplied\n * @param onBehalfOf The address that will receive the xTokens\n **/\n function supplyERC721FromNToken(\n address asset,\n DataTypes.ERC721SupplyParams[] calldata tokenData,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the xTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of xTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\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 * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n **/\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent xTokens owned\n * E.g. User has 100 pUSDC, calls withdraw() and receives 100 USDC, burning the 100 pUSDC\n * @param asset 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 xToken balance\n * @param to The 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(\n address asset,\n uint256 amount,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Withdraws multiple `tokenIds` of underlying ERC721 asset from the reserve, burning the equivalent nTokens owned\n * E.g. User has 2 nBAYC, calls withdraw() and receives 2 BAYC, burning the 2 nBAYC\n * @param asset The address of the underlying asset to withdraw\n * @param tokenIds The underlying tokenIds to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole xToken balance\n * @param to The 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 withdrawERC721(\n address asset,\n uint256[] calldata tokenIds,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Decreases liquidity for underlying Uniswap V3 NFT LP and validates\n * that the user respects liquidation checks.\n * @param asset The asset address of uniswapV3\n * @param tokenId The id of the erc721 token\n * @param liquidityDecrease The amount of liquidity to remove of LP\n * @param amount0Min The minimum amount to remove of token0\n * @param amount1Min The minimum amount to remove of token1\n * @param receiveEthAsWeth If convert weth to ETH\n */\n function decreaseUniswapV3Liquidity(\n address asset,\n uint256 tokenId,\n uint128 liquidityDecrease,\n uint256 amount0Min,\n uint256 amount1Min,\n bool receiveEthAsWeth\n ) external;\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param referralCode The 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 * @param onBehalfOf The address of the user who will receive the debt. 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 **/\n function borrow(\n address asset,\n uint256 amount,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n **/\n function repay(\n address asset,\n uint256 amount,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve xTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 pUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual xToken dust balance, if the user xToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @return The final amount repaid\n **/\n function repayWithPTokens(address asset, uint256 amount)\n external\n returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n **/\n function repayWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n **/\n function setUserUseERC20AsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied ERC721 asset with a tokenID as collateral\n * @param asset The address of the underlying asset supplied\n * @param tokenIds the ids of the supplied ERC721 token\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n **/\n function setUserUseERC721AsCollateral(\n address asset,\n uint256[] calldata tokenIds,\n bool useAsCollateral\n ) external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `liquidationAmount` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param liquidationAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param liquidationAmount The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receivePToken True if the liquidators wants to receive the collateral xTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n function liquidateERC20(\n address collateralAsset,\n address liquidationAsset,\n address user,\n uint256 liquidationAmount,\n bool receivePToken\n ) external payable;\n\n function liquidateERC721(\n address collateralAsset,\n address user,\n uint256 collateralTokenId,\n uint256 liquidationAmount,\n bool receiveNToken\n ) external payable;\n\n /**\n * @notice Start the auction on user's specific NFT collateral\n * @param user The address of the user\n * @param collateralAsset The address of the NFT collateral\n * @param collateralTokenId The tokenId of the NFT collateral\n **/\n function startAuction(\n address user,\n address collateralAsset,\n uint256 collateralTokenId\n ) external;\n\n /**\n * @notice End specific user's auction\n * @param user The address of the user\n * @param collateralAsset The address of the NFT collateral\n * @param collateralTokenId The tokenId of the NFT collateral\n **/\n function endAuction(\n address user,\n address collateralAsset,\n uint256 collateralTokenId\n ) external;\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n **/\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice 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 getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice 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)\n external\n view\n returns (uint256);\n\n /**\n * @notice 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)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n **/\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an PToken transfer\n * @dev Only callable by the overlying xToken of the `asset`\n * @param asset The address of the underlying asset of the xToken\n * @param from The user from which the xTokens are transferred\n * @param to The user receiving the xTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The xToken balance of the `from` user before the transfer\n * @param balanceToBefore The xToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n bool usedAsCollateral,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Validates and finalizes an NToken transfer\n * @dev Only callable by the overlying xToken of the `asset`\n * @param asset The address of the underlying asset of the xToken\n * @param tokenId The tokenId of the ERC721 asset\n * @param from The user from which the xTokens are transferred\n * @param to The user receiving the xTokens\n * @param balanceFromBefore The xToken balance of the `from` user before the transfer\n */\n function finalizeTransferERC721(\n address asset,\n uint256 tokenId,\n address from,\n address to,\n bool usedAsCollateral,\n uint256 balanceFromBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n **/\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n **/\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the auction related data of specific asset collection and token id.\n * @param ntokenAsset The address of ntoken\n * @param tokenId The token id which is currently auctioned for liquidation\n * @return The auction related data of the corresponding (ntokenAsset, tokenId)\n */\n function getAuctionData(address ntokenAsset, uint256 tokenId)\n external\n view\n returns (DataTypes.AuctionData memory);\n\n // function getAuctionData(address user, address) external view returns (DataTypes.AuctionData memory);\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n **/\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Returns the auction recovery health factor\n * @return The auction recovery health factor\n */\n function AUCTION_RECOVERY_HEALTH_FACTOR() external view returns (uint64);\n}\n" }, "contracts/interfaces/IPoolMarketplace.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPoolMarketplace {\n event BuyWithCredit(\n bytes32 indexed marketplaceId,\n DataTypes.OrderInfo orderInfo,\n DataTypes.Credit credit\n );\n\n event AcceptBidWithCredit(\n bytes32 indexed marketplaceId,\n DataTypes.OrderInfo orderInfo,\n DataTypes.Credit credit\n );\n\n /**\n * @notice Implements the buyWithCredit feature. BuyWithCredit allows users to buy NFT from various NFT marketplaces\n * including OpenSea, LooksRare, X2Y2 etc. Users can use NFT's credit and will need to pay at most (1 - LTV) * $NFT\n * @dev\n * @param marketplaceId The marketplace identifier\n * @param payload The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credit The credit that user would like to use for this purchase\n * @param referralCode The referral code used\n */\n function buyWithCredit(\n bytes32 marketplaceId,\n bytes calldata payload,\n DataTypes.Credit calldata credit,\n uint16 referralCode\n ) external payable;\n\n /**\n * @notice Implements the batchBuyWithCredit feature. BuyWithCredit allows users to buy NFT from various NFT marketplaces\n * including OpenSea, LooksRare, X2Y2 etc. Users can use NFT's credit and will need to pay at most (1 - LTV) * $NFT\n * @dev marketplaceIds[i] should match payload[i] and credits[i]\n * @param marketplaceIds The marketplace identifiers\n * @param payloads The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credits The credits that user would like to use for this purchase\n * @param referralCode The referral code used\n */\n function batchBuyWithCredit(\n bytes32[] calldata marketplaceIds,\n bytes[] calldata payloads,\n DataTypes.Credit[] calldata credits,\n uint16 referralCode\n ) external payable;\n\n /**\n * @notice Implements the acceptBidWithCredit feature. AcceptBidWithCredit allows users to\n * accept a leveraged bid on ParaSpace NFT marketplace. Users can submit leveraged bid and pay\n * at most (1 - LTV) * $NFT\n * @dev The nft receiver just needs to do the downpayment\n * @param marketplaceId The marketplace identifier\n * @param payload The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credit The credit that user would like to use for this purchase\n * @param onBehalfOf Address of the user who will sell the NFT\n * @param referralCode The referral code used\n */\n function acceptBidWithCredit(\n bytes32 marketplaceId,\n bytes calldata payload,\n DataTypes.Credit calldata credit,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Implements the batchAcceptBidWithCredit feature. AcceptBidWithCredit allows users to\n * accept a leveraged bid on ParaSpace NFT marketplace. Users can submit leveraged bid and pay\n * at most (1 - LTV) * $NFT\n * @dev The nft receiver just needs to do the downpayment\n * @param marketplaceIds The marketplace identifiers\n * @param payloads The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credits The credits that the makers have approved to use for this purchase\n * @param onBehalfOf Address of the user who will sell the NFTs\n * @param referralCode The referral code used\n */\n function batchAcceptBidWithCredit(\n bytes32[] calldata marketplaceIds,\n bytes[] calldata payloads,\n DataTypes.Credit[] calldata credits,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" }, "contracts/interfaces/IPoolParameters.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPoolParameters {\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next 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 when the value of claim for yield incentive rate update\n **/\n event ClaimApeForYieldIncentiveUpdated(uint256 oldValue, uint256 newValue);\n\n /**\n * @notice Initializes a reserve, activating it, assigning an xToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param xTokenAddress The address of the xToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n **/\n function initReserve(\n address asset,\n address xTokenAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress,\n address auctionStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n **/\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n **/\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Updates the address of the auction strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param auctionStrategyAddress The address of the auction strategy contract\n **/\n function setReserveAuctionStrategyAddress(\n address asset,\n address auctionStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n **/\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of xTokens\n * @param assets The list of reserves for which the minting needs to be executed\n **/\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param assetType The asset type of the token\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amountOrTokenId The amount or id of token to transfer\n */\n function rescueTokens(\n DataTypes.AssetType assetType,\n address token,\n address to,\n uint256 amountOrTokenId\n ) external;\n\n /**\n * @notice grant token's an unlimited allowance value to the 'to' address\n * @param token The ERC20 token address\n * @param to The address receive the grant\n */\n function unlimitedApproveTo(address token, address to) external;\n\n /**\n * @notice reset token's allowance value to the 'to' address\n * @param token The ERC20 token address\n * @param to The address receive the grant\n */\n function revokeUnlimitedApprove(address token, address to) external;\n\n /**\n * @notice undate fee percentage for claim ape for compound\n * @param fee new fee percentage\n */\n function setClaimApeForCompoundFee(uint256 fee) external;\n\n /**\n * @notice undate ape compound strategy\n * @param strategy new compound strategy\n */\n function setApeCompoundStrategy(\n DataTypes.ApeCompoundStrategy calldata strategy\n ) external;\n\n /**\n * @notice get user ape compound strategy\n * @param user The user address\n */\n function getUserApeCompoundStrategy(address user)\n external\n view\n returns (DataTypes.ApeCompoundStrategy memory);\n\n /**\n * @notice Set the auction recovery health factor\n * @param value The new auction health factor\n */\n function setAuctionRecoveryHealthFactor(uint64 value) external;\n\n /**\n * @notice Set auction validity time, all auctions triggered before the validity time will be considered as invalid\n * @param user The user address\n */\n function setAuctionValidityTime(address user) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n **/\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor,\n uint256 erc721HealthFactor\n );\n\n /**\n * @notice Returns Ltv and Liquidation Threshold for the asset\n * @param asset The address of the asset\n * @param tokenId The tokenId of the asset\n * @return ltv The loan to value of the asset\n * @return lt The liquidation threshold value of the asset\n **/\n function getAssetLtvAndLT(address asset, uint256 tokenId)\n external\n view\n returns (uint256 ltv, uint256 lt);\n}\n" }, "contracts/interfaces/IRewardController.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IRewardController\n *\n * @notice Defines the basic interface for an ParaSpace Incentives Controller.\n **/\ninterface IRewardController {\n /**\n * @dev Emitted during `handleAction`, `claimRewards` and `claimRewardsOnBehalf`\n * @param user The user that accrued rewards\n * @param amount The amount of accrued rewards\n */\n event RewardsAccrued(address indexed user, uint256 amount);\n\n event RewardsClaimed(\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted during `claimRewards` and `claimRewardsOnBehalf`\n * @param user The address that accrued rewards\n * @param to The address that will be receiving the rewards\n * @param claimer The address that performed the claim\n * @param amount The amount of rewards\n */\n event RewardsClaimed(\n address indexed user,\n address indexed to,\n address indexed claimer,\n uint256 amount\n );\n\n /**\n * @dev Emitted during `setClaimer`\n * @param user The address of the user\n * @param claimer The address of the claimer\n */\n event ClaimerSet(address indexed user, address indexed claimer);\n\n /**\n * @notice Returns the configuration of the distribution for a certain asset\n * @param asset The address of the reference asset of the distribution\n * @return The asset index\n * @return The emission per second\n * @return The last updated timestamp\n **/\n function getAssetData(address asset)\n external\n view\n returns (\n uint256,\n uint256,\n uint256\n );\n\n /**\n * LEGACY **************************\n * @dev Returns the configuration of the distribution for a certain asset\n * @param asset The address of the reference asset of the distribution\n * @return The asset index, the emission per second and the last updated timestamp\n **/\n function assets(address asset)\n external\n view\n returns (\n uint128,\n uint128,\n uint256\n );\n\n /**\n * @notice Whitelists an address to claim the rewards on behalf of another address\n * @param user The address of the user\n * @param claimer The address of the claimer\n */\n function setClaimer(address user, address claimer) external;\n\n /**\n * @notice Returns the whitelisted claimer for a certain address (0x0 if not set)\n * @param user The address of the user\n * @return The claimer address\n */\n function getClaimer(address user) external view returns (address);\n\n /**\n * @notice Configure assets for a certain rewards emission\n * @param assets The assets to incentivize\n * @param emissionsPerSecond The emission for each asset\n */\n function configureAssets(\n address[] calldata assets,\n uint256[] calldata emissionsPerSecond\n ) external;\n\n /**\n * @notice Called by the corresponding asset on any update that affects the rewards distribution\n * @param asset The address of the user\n * @param userBalance The balance of the user of the asset in the pool\n * @param totalSupply The total supply of the asset in the pool\n **/\n function handleAction(\n address asset,\n uint256 totalSupply,\n uint256 userBalance\n ) external;\n\n /**\n * @notice Returns the total of rewards of a user, already accrued + not yet accrued\n * @param assets The assets to accumulate rewards for\n * @param user The address of the user\n * @return The rewards\n **/\n function getRewardsBalance(address[] calldata assets, address user)\n external\n view\n returns (uint256);\n\n /**\n * @notice Claims reward for a user, on the assets of the pool, accumulating the pending rewards\n * @param assets The assets to accumulate rewards for\n * @param amount Amount of rewards to claim\n * @param to Address that will be receiving the rewards\n * @return Rewards claimed\n **/\n function claimRewards(\n address[] calldata assets,\n uint256 amount,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Claims reward for a user on its behalf, on the assets of the pool, accumulating the pending rewards.\n * @dev The caller must be whitelisted via \"allowClaimOnBehalf\" function by the RewardsAdmin role manager\n * @param assets The assets to accumulate rewards for\n * @param amount The amount of rewards to claim\n * @param user The address to check and claim rewards\n * @param to The address that will be receiving the rewards\n * @return The amount of rewards claimed\n **/\n function claimRewardsOnBehalf(\n address[] calldata assets,\n uint256 amount,\n address user,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Returns the unclaimed rewards of the user\n * @param user The address of the user\n * @return The unclaimed user rewards\n */\n function getUserUnclaimedRewards(address user)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the user index for a specific asset\n * @param user The address of the user\n * @param asset The asset to incentivize\n * @return The user index for the asset\n */\n function getUserAssetData(address user, address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice for backward compatibility with previous implementation of the Incentives controller\n * @return The address of the reward token\n */\n function REWARD_TOKEN() external view returns (address);\n\n /**\n * @notice for backward compatibility with previous implementation of the Incentives controller\n * @return The precision used in the incentives controller\n */\n function PRECISION() external view returns (uint8);\n\n /**\n * @dev Gets the distribution end timestamp of the emissions\n */\n function DISTRIBUTION_END() external view returns (uint256);\n}\n" }, "contracts/interfaces/IScaledBalanceToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IScaledBalanceToken\n *\n * @notice Defines the basic interface for a scaledbalance token.\n **/\ninterface IScaledBalanceToken {\n /**\n * @dev Emitted after the mint action\n * @param caller The address performing the mint\n * @param onBehalfOf The address of the user that will receive the minted scaled balance tokens\n * @param value The amount being minted (user entered amount + balance increase from interest)\n * @param balanceIncrease The increase in balance since the last action of the user\n * @param index The next liquidity index of the reserve\n **/\n event Mint(\n address indexed caller,\n address indexed onBehalfOf,\n uint256 value,\n uint256 balanceIncrease,\n uint256 index\n );\n\n /**\n * @dev Emitted after scaled balance tokens are burned\n * @param from The address from which the scaled tokens will be burned\n * @param target The address that will receive the underlying, if any\n * @param value The amount being burned (user entered amount - balance increase from interest)\n * @param balanceIncrease The increase in balance since the last action of the user\n * @param index The next liquidity index of the reserve\n **/\n event Burn(\n address indexed from,\n address indexed target,\n uint256 value,\n uint256 balanceIncrease,\n uint256 index\n );\n\n /**\n * @notice Returns the scaled balance of the user.\n * @dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index\n * 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 * @notice 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 total supply\n **/\n function getScaledUserBalanceAndSupply(address user)\n external\n view\n returns (uint256, uint256);\n\n /**\n * @notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index)\n * @return The scaled total supply\n **/\n function scaledTotalSupply() external view returns (uint256);\n\n /**\n * @notice Returns last index interest was accrued to the user's balance\n * @param user The address of the user\n * @return The last index interest was accrued to the user's balance, expressed in ray\n **/\n function getPreviousIndex(address user) external view returns (uint256);\n}\n" }, "contracts/interfaces/IVariableDebtToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IScaledBalanceToken} from \"./IScaledBalanceToken.sol\";\nimport {IInitializableDebtToken} from \"./IInitializableDebtToken.sol\";\n\n/**\n * @title IVariableDebtToken\n *\n * @notice Defines the basic interface for a variable debt token.\n **/\ninterface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {\n /**\n * @notice Mints debt token to the `onBehalfOf` address\n * @param user The address receiving the borrowed underlying, being the delegatee in case\n * of credit delegate, or same as `onBehalfOf` otherwise\n * @param onBehalfOf The address receiving the debt tokens\n * @param amount The amount of debt being minted\n * @param index The variable debt index of the reserve\n * @return True if the previous balance of the user is 0, false otherwise\n * @return The scaled total debt of the reserve\n **/\n function mint(\n address user,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) external returns (bool, uint256);\n\n /**\n * @notice Burns user variable debt\n * @dev In some instances, a burn transaction will emit a mint event\n * if the amount to burn is less than the interest that the user accrued\n * @param from The address from which the debt will be burned\n * @param amount The amount getting burned\n * @param index The variable debt index of the reserve\n * @return The scaled total debt of the reserve\n **/\n function burn(\n address from,\n uint256 amount,\n uint256 index\n ) external returns (uint256);\n\n /**\n * @notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH)\n * @return The address of the underlying asset\n **/\n function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n" }, "contracts/protocol/libraries/helpers/Errors.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\n/**\n * @title Errors library\n *\n * @notice Defines the error messages emitted by the different contracts of the ParaSpace protocol\n */\nlibrary Errors {\n string public constant CALLER_NOT_POOL_ADMIN = \"1\"; // 'The caller of the function is not a pool admin'\n string public constant CALLER_NOT_EMERGENCY_ADMIN = \"2\"; // 'The caller of the function is not an emergency admin'\n string public constant CALLER_NOT_POOL_OR_EMERGENCY_ADMIN = \"3\"; // 'The caller of the function is not a pool or emergency admin'\n string public constant CALLER_NOT_RISK_OR_POOL_ADMIN = \"4\"; // 'The caller of the function is not a risk or pool admin'\n string public constant CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN = \"5\"; // 'The caller of the function is not an asset listing or pool admin'\n string public constant CALLER_NOT_BRIDGE = \"6\"; // 'The caller of the function is not a bridge'\n string public constant ADDRESSES_PROVIDER_NOT_REGISTERED = \"7\"; // 'Pool addresses provider is not registered'\n string public constant INVALID_ADDRESSES_PROVIDER_ID = \"8\"; // 'Invalid id for the pool addresses provider'\n string public constant NOT_CONTRACT = \"9\"; // 'Address is not a contract'\n string public constant CALLER_NOT_POOL_CONFIGURATOR = \"10\"; // 'The caller of the function is not the pool configurator'\n string public constant CALLER_NOT_XTOKEN = \"11\"; // 'The caller of the function is not an PToken or NToken'\n string public constant INVALID_ADDRESSES_PROVIDER = \"12\"; // 'The address of the pool addresses provider is invalid'\n string public constant RESERVE_ALREADY_ADDED = \"14\"; // 'Reserve has already been added to reserve list'\n string public constant NO_MORE_RESERVES_ALLOWED = \"15\"; // 'Maximum amount of reserves in the pool reached'\n string public constant RESERVE_LIQUIDITY_NOT_ZERO = \"18\"; // 'The liquidity of the reserve needs to be 0'\n string public constant INVALID_RESERVE_PARAMS = \"20\"; // 'Invalid risk parameters for the reserve'\n string public constant CALLER_MUST_BE_POOL = \"23\"; // 'The caller of this function must be a pool'\n string public constant INVALID_MINT_AMOUNT = \"24\"; // 'Invalid amount to mint'\n string public constant INVALID_BURN_AMOUNT = \"25\"; // 'Invalid amount to burn'\n string public constant INVALID_AMOUNT = \"26\"; // 'Amount must be greater than 0'\n string public constant RESERVE_INACTIVE = \"27\"; // 'Action requires an active reserve'\n string public constant RESERVE_FROZEN = \"28\"; // 'Action cannot be performed because the reserve is frozen'\n string public constant RESERVE_PAUSED = \"29\"; // 'Action cannot be performed because the reserve is paused'\n string public constant BORROWING_NOT_ENABLED = \"30\"; // 'Borrowing is not enabled'\n string public constant STABLE_BORROWING_NOT_ENABLED = \"31\"; // 'Stable borrowing is not enabled'\n string public constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = \"32\"; // 'User cannot withdraw more than the available balance'\n string public constant INVALID_INTEREST_RATE_MODE_SELECTED = \"33\"; // 'Invalid interest rate mode selected'\n string public constant COLLATERAL_BALANCE_IS_ZERO = \"34\"; // 'The collateral balance is 0'\n string public constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD =\n \"35\"; // 'Health factor is lesser than the liquidation threshold'\n string public constant COLLATERAL_CANNOT_COVER_NEW_BORROW = \"36\"; // 'There is not enough collateral to cover a new borrow'\n string public constant COLLATERAL_SAME_AS_BORROWING_CURRENCY = \"37\"; // 'Collateral is (mostly) the same currency that is being borrowed'\n string public constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = \"38\"; // 'The requested amount is greater than the max loan size in stable rate mode'\n string public constant NO_DEBT_OF_SELECTED_TYPE = \"39\"; // 'For repayment of a specific type of debt, the user needs to have debt that type'\n string public constant NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = \"40\"; // 'To repay on behalf of a user an explicit amount to repay is needed'\n string public constant NO_OUTSTANDING_STABLE_DEBT = \"41\"; // 'User does not have outstanding stable rate debt on this reserve'\n string public constant NO_OUTSTANDING_VARIABLE_DEBT = \"42\"; // 'User does not have outstanding variable rate debt on this reserve'\n string public constant UNDERLYING_BALANCE_ZERO = \"43\"; // 'The underlying balance needs to be greater than 0'\n string public constant INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = \"44\"; // 'Interest rate rebalance conditions were not met'\n string public constant HEALTH_FACTOR_NOT_BELOW_THRESHOLD = \"45\"; // 'Health factor is not below the threshold'\n string public constant COLLATERAL_CANNOT_BE_AUCTIONED_OR_LIQUIDATED = \"46\"; // 'The collateral chosen cannot be auctioned OR liquidated'\n string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = \"47\"; // 'User did not borrow the specified currency'\n string public constant SAME_BLOCK_BORROW_REPAY = \"48\"; // 'Borrow and repay in same block is not allowed'\n string public constant BORROW_CAP_EXCEEDED = \"50\"; // 'Borrow cap is exceeded'\n string public constant SUPPLY_CAP_EXCEEDED = \"51\"; // 'Supply cap is exceeded'\n string public constant XTOKEN_SUPPLY_NOT_ZERO = \"54\"; // 'PToken supply is not zero'\n string public constant STABLE_DEBT_NOT_ZERO = \"55\"; // 'Stable debt supply is not zero'\n string public constant VARIABLE_DEBT_SUPPLY_NOT_ZERO = \"56\"; // 'Variable debt supply is not zero'\n string public constant LTV_VALIDATION_FAILED = \"57\"; // 'Ltv validation failed'\n string public constant PRICE_ORACLE_SENTINEL_CHECK_FAILED = \"59\"; // 'Price oracle sentinel validation failed'\n string public constant RESERVE_ALREADY_INITIALIZED = \"61\"; // 'Reserve has already been initialized'\n string public constant INVALID_LTV = \"63\"; // 'Invalid ltv parameter for the reserve'\n string public constant INVALID_LIQ_THRESHOLD = \"64\"; // 'Invalid liquidity threshold parameter for the reserve'\n string public constant INVALID_LIQ_BONUS = \"65\"; // 'Invalid liquidity bonus parameter for the reserve'\n string public constant INVALID_DECIMALS = \"66\"; // 'Invalid decimals parameter of the underlying asset of the reserve'\n string public constant INVALID_RESERVE_FACTOR = \"67\"; // 'Invalid reserve factor parameter for the reserve'\n string public constant INVALID_BORROW_CAP = \"68\"; // 'Invalid borrow cap for the reserve'\n string public constant INVALID_SUPPLY_CAP = \"69\"; // 'Invalid supply cap for the reserve'\n string public constant INVALID_LIQUIDATION_PROTOCOL_FEE = \"70\"; // 'Invalid liquidation protocol fee for the reserve'\n string public constant INVALID_DEBT_CEILING = \"73\"; // 'Invalid debt ceiling for the reserve\n string public constant INVALID_RESERVE_INDEX = \"74\"; // 'Invalid reserve index'\n string public constant ACL_ADMIN_CANNOT_BE_ZERO = \"75\"; // 'ACL admin cannot be set to the zero address'\n string public constant INCONSISTENT_PARAMS_LENGTH = \"76\"; // 'Array parameters that should be equal length are not'\n string public constant ZERO_ADDRESS_NOT_VALID = \"77\"; // 'Zero address not valid'\n string public constant INVALID_EXPIRATION = \"78\"; // 'Invalid expiration'\n string public constant INVALID_SIGNATURE = \"79\"; // 'Invalid signature'\n string public constant OPERATION_NOT_SUPPORTED = \"80\"; // 'Operation not supported'\n string public constant ASSET_NOT_LISTED = \"82\"; // 'Asset is not listed'\n string public constant INVALID_OPTIMAL_USAGE_RATIO = \"83\"; // 'Invalid optimal usage ratio'\n string public constant INVALID_OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO = \"84\"; // 'Invalid optimal stable to total debt ratio'\n string public constant UNDERLYING_CANNOT_BE_RESCUED = \"85\"; // 'The underlying asset cannot be rescued'\n string public constant ADDRESSES_PROVIDER_ALREADY_ADDED = \"86\"; // 'Reserve has already been added to reserve list'\n string public constant POOL_ADDRESSES_DO_NOT_MATCH = \"87\"; // 'The token implementation pool address and the pool address provided by the initializing pool do not match'\n string public constant STABLE_BORROWING_ENABLED = \"88\"; // 'Stable borrowing is enabled'\n string public constant SILOED_BORROWING_VIOLATION = \"89\"; // 'User is trying to borrow multiple assets including a siloed one'\n string public constant RESERVE_DEBT_NOT_ZERO = \"90\"; // the total debt of the reserve needs to be 0\n string public constant NOT_THE_OWNER = \"91\"; // user is not the owner of a given asset\n string public constant LIQUIDATION_AMOUNT_NOT_ENOUGH = \"92\";\n string public constant INVALID_ASSET_TYPE = \"93\"; // invalid asset type for action.\n string public constant INVALID_FLASH_CLAIM_RECEIVER = \"94\"; // invalid flash claim receiver.\n string public constant ERC721_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = \"95\"; // ERC721 Health factor is not below the threshold. Can only liquidate ERC20.\n string public constant UNDERLYING_ASSET_CAN_NOT_BE_TRANSFERRED = \"96\"; //underlying asset can not be transferred.\n string public constant TOKEN_TRANSFERRED_CAN_NOT_BE_SELF_ADDRESS = \"97\"; //token transferred can not be self address.\n string public constant INVALID_AIRDROP_CONTRACT_ADDRESS = \"98\"; //invalid airdrop contract address.\n string public constant INVALID_AIRDROP_PARAMETERS = \"99\"; //invalid airdrop parameters.\n string public constant CALL_AIRDROP_METHOD_FAILED = \"100\"; //call airdrop method failed.\n string public constant SUPPLIER_NOT_NTOKEN = \"101\"; //supplier is not the NToken contract\n string public constant CALL_MARKETPLACE_FAILED = \"102\"; //call marketplace failed.\n string public constant INVALID_MARKETPLACE_ID = \"103\"; //invalid marketplace id.\n string public constant INVALID_MARKETPLACE_ORDER = \"104\"; //invalid marketplace id.\n string public constant CREDIT_DOES_NOT_MATCH_ORDER = \"105\"; //credit doesn't match order.\n string public constant PAYNOW_NOT_ENOUGH = \"106\"; //paynow not enough.\n string public constant INVALID_CREDIT_SIGNATURE = \"107\"; //invalid credit signature.\n string public constant INVALID_ORDER_TAKER = \"108\"; //invalid order taker.\n string public constant MARKETPLACE_PAUSED = \"109\"; //marketplace paused.\n string public constant INVALID_AUCTION_RECOVERY_HEALTH_FACTOR = \"110\"; //invalid auction recovery health factor.\n string public constant AUCTION_ALREADY_STARTED = \"111\"; //auction already started.\n string public constant AUCTION_NOT_STARTED = \"112\"; //auction not started yet.\n string public constant AUCTION_NOT_ENABLED = \"113\"; //auction not enabled on the reserve.\n string public constant ERC721_HEALTH_FACTOR_NOT_ABOVE_THRESHOLD = \"114\"; //ERC721 Health factor is not above the threshold.\n string public constant TOKEN_IN_AUCTION = \"115\"; //tokenId is in auction.\n string public constant AUCTIONED_BALANCE_NOT_ZERO = \"116\"; //auctioned balance not zero.\n string public constant LIQUIDATOR_CAN_NOT_BE_SELF = \"117\"; //user can not liquidate himself.\n string public constant INVALID_RECIPIENT = \"118\"; //invalid recipient specified in order.\n string public constant UNIV3_NOT_ALLOWED = \"119\"; //flash claim is not allowed for UniswapV3.\n string public constant NTOKEN_BALANCE_EXCEEDED = \"120\"; //ntoken balance exceed limit.\n string public constant ORACLE_PRICE_NOT_READY = \"121\"; //oracle price not ready.\n string public constant SET_ORACLE_SOURCE_NOT_ALLOWED = \"122\"; //source of oracle not allowed to set.\n string public constant INVALID_LIQUIDATION_ASSET = \"123\"; //invalid liquidation asset.\n string public constant ONLY_UNIV3_ALLOWED = \"124\"; //only UniswapV3 allowed.\n string public constant GLOBAL_DEBT_IS_ZERO = \"125\"; //liquidation is not allowed when global debt is zero.\n string public constant ORACLE_PRICE_EXPIRED = \"126\"; //oracle price expired.\n string public constant APE_STAKING_POSITION_EXISTED = \"127\"; //ape staking position is existed.\n string public constant SAPE_NOT_ALLOWED = \"128\"; //operation is not allow for sApe.\n string public constant TOTAL_STAKING_AMOUNT_WRONG = \"129\"; //cash plus borrow amount not equal to total staking amount.\n string public constant NOT_THE_BAKC_OWNER = \"130\"; //user is not the bakc owner.\n string public constant CALLER_NOT_EOA = \"131\"; //The caller of the function is not an EOA account\n string public constant MAKER_SAME_AS_TAKER = \"132\"; //maker and taker shouldn't be the same address\n}\n" }, "contracts/protocol/libraries/math/WadRayMath.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\n/**\n * @title WadRayMath library\n *\n * @notice Provides functions to perform calculations with Wad and Ray units\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers\n * with 27 digits of precision)\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n **/\nlibrary WadRayMath {\n // HALF_WAD and HALF_RAY expressed with extended notation as constant with operations are not supported in Yul assembly\n uint256 internal constant WAD = 1e18;\n uint256 internal constant HALF_WAD = 0.5e18;\n\n uint256 internal constant RAY = 1e27;\n uint256 internal constant HALF_RAY = 0.5e27;\n\n uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n /**\n * @dev Multiplies two wad, rounding half up to the nearest wad\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Wad\n * @param b Wad\n * @return c = a*b, in wad\n **/\n function wadMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - HALF_WAD) / b\n assembly {\n if iszero(\n or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_WAD), b))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, b), HALF_WAD), WAD)\n }\n }\n\n /**\n * @dev Divides two wad, rounding half up to the nearest wad\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Wad\n * @param b Wad\n * @return c = a/b, in wad\n **/\n function wadDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - halfB) / WAD\n assembly {\n if or(\n iszero(b),\n iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), WAD))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, WAD), div(b, 2)), b)\n }\n }\n\n /**\n * @notice Multiplies two ray, rounding half up to the nearest ray\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Ray\n * @param b Ray\n * @return c = a raymul b\n **/\n function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b\n assembly {\n if iszero(\n or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, b), HALF_RAY), RAY)\n }\n }\n\n /**\n * @notice Divides two ray, rounding half up to the nearest ray\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Ray\n * @param b Ray\n * @return c = a raydiv b\n **/\n function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - halfB) / RAY\n assembly {\n if or(\n iszero(b),\n iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, RAY), div(b, 2)), b)\n }\n }\n\n /**\n * @dev Casts ray down to wad\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Ray\n * @return b = a converted to wad, rounded half up to the nearest wad\n **/\n function rayToWad(uint256 a) internal pure returns (uint256 b) {\n assembly {\n b := div(a, WAD_RAY_RATIO)\n let remainder := mod(a, WAD_RAY_RATIO)\n if iszero(lt(remainder, div(WAD_RAY_RATIO, 2))) {\n b := add(b, 1)\n }\n }\n }\n\n /**\n * @dev Converts wad up to ray\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Wad\n * @return b = a converted in ray\n **/\n function wadToRay(uint256 a) internal pure returns (uint256 b) {\n // to avoid overflow, b/WAD_RAY_RATIO == a\n assembly {\n b := mul(a, WAD_RAY_RATIO)\n\n if iszero(eq(div(b, WAD_RAY_RATIO), a)) {\n revert(0, 0)\n }\n }\n }\n}\n" }, "contracts/protocol/libraries/paraspace-upgradeability/VersionedInitializable.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title VersionedInitializable\n * , inspired by the OpenZeppelin Initializable contract\n * @notice Helper contract to implement initializer functions. To use it, replace\n * the constructor with a function that has the `initializer` modifier.\n * @dev WARNING: Unlike constructors, initializer functions must be manually\n * invoked. This applies both to deploying an Initializable contract, as well\n * as extending an Initializable contract via inheritance.\n * WARNING: When used with inheritance, manual care must be taken to not invoke\n * a parent initializer twice, or ensure that all initializers are idempotent,\n * because this is not dealt with automatically as with constructors.\n */\nabstract contract VersionedInitializable {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint256 private lastInitializedRevision = 0;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private initializing;\n\n /**\n * @dev Modifier to use in the initializer function of a contract.\n */\n modifier initializer() {\n uint256 revision = getRevision();\n require(\n initializing ||\n isConstructor() ||\n revision > lastInitializedRevision,\n \"Contract instance has already been initialized\"\n );\n\n bool isTopLevelCall = !initializing;\n if (isTopLevelCall) {\n initializing = true;\n lastInitializedRevision = revision;\n }\n\n _;\n\n if (isTopLevelCall) {\n initializing = false;\n }\n }\n\n /**\n * @notice Returns the revision number of the contract\n * @dev Needs to be defined in the inherited class as a constant.\n * @return The revision number\n **/\n function getRevision() internal pure virtual returns (uint256);\n\n /**\n * @notice Returns true if and only if the function is running in the constructor\n * @return True if the function is running in the constructor\n **/\n function isConstructor() private view returns (bool) {\n // extcodesize checks the size of the code stored in an address, and\n // address returns the current address. Since the code is still not\n // deployed when running a constructor, any checks on its code size will\n // yield zero, making it an effective way to detect if a contract is\n // under construction or not.\n uint256 cs;\n //solium-disable-next-line\n assembly {\n cs := extcodesize(address())\n }\n return cs == 0;\n }\n\n // Reserved storage space to allow for layout changes in the future.\n uint256[50] private ______gap;\n}\n" }, "contracts/protocol/libraries/types/DataTypes.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {OfferItem, ConsiderationItem} from \"../../../dependencies/seaport/contracts/lib/ConsiderationStructs.sol\";\n\nlibrary DataTypes {\n enum AssetType {\n ERC20,\n ERC721\n }\n\n address public constant SApeAddress = address(0x1);\n uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;\n\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //xToken address\n address xTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //address of the auction strategy\n address auctionStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62-63: reserved\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n // auction validity time for closing invalid auctions in one tx.\n uint256 auctionValidityTime;\n }\n\n struct ERC721SupplyParams {\n uint256 tokenId;\n bool useAsCollateral;\n }\n\n struct NTokenData {\n uint256 tokenId;\n uint256 multiplier;\n bool useAsCollateral;\n bool isAuctioned;\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address xTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidateParams {\n uint256 reservesCount;\n uint256 liquidationAmount;\n uint256 collateralTokenId;\n uint256 auctionRecoveryHealthFactor;\n address weth;\n address collateralAsset;\n address liquidationAsset;\n address borrower;\n address liquidator;\n bool receiveXToken;\n address priceOracle;\n address priceOracleSentinel;\n }\n\n struct ExecuteAuctionParams {\n uint256 reservesCount;\n uint256 auctionRecoveryHealthFactor;\n uint256 collateralTokenId;\n address collateralAsset;\n address user;\n address priceOracle;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n address payer;\n uint16 referralCode;\n }\n\n struct ExecuteSupplyERC721Params {\n address asset;\n DataTypes.ERC721SupplyParams[] tokenData;\n address onBehalfOf;\n address payer;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 reservesCount;\n address oracle;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n address payer;\n bool usePTokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n }\n\n struct ExecuteWithdrawERC721Params {\n address asset;\n uint256[] tokenIds;\n address to;\n uint256 reservesCount;\n address oracle;\n }\n\n struct ExecuteDecreaseUniswapV3LiquidityParams {\n address user;\n address asset;\n uint256 tokenId;\n uint256 reservesCount;\n uint128 liquidityDecrease;\n uint256 amount0Min;\n uint256 amount1Min;\n bool receiveEthAsWeth;\n address oracle;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n bool usedAsCollateral;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n }\n\n struct FinalizeTransferERC721Params {\n address asset;\n address from;\n address to;\n bool usedAsCollateral;\n uint256 tokenId;\n uint256 balanceFromBefore;\n uint256 reservesCount;\n address oracle;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n uint256 reservesCount;\n address oracle;\n address priceOracleSentinel;\n }\n\n struct ValidateLiquidateERC20Params {\n ReserveCache liquidationAssetReserveCache;\n address liquidationAsset;\n address weth;\n uint256 totalDebt;\n uint256 healthFactor;\n uint256 liquidationAmount;\n uint256 actualLiquidationAmount;\n address priceOracleSentinel;\n }\n\n struct ValidateLiquidateERC721Params {\n ReserveCache liquidationAssetReserveCache;\n address liquidationAsset;\n address liquidator;\n address borrower;\n uint256 globalDebt;\n uint256 healthFactor;\n address collateralAsset;\n uint256 tokenId;\n address weth;\n uint256 actualLiquidationAmount;\n uint256 maxLiquidationAmount;\n uint256 auctionRecoveryHealthFactor;\n address priceOracleSentinel;\n address xTokenAddress;\n bool auctionEnabled;\n }\n\n struct ValidateAuctionParams {\n address user;\n uint256 auctionRecoveryHealthFactor;\n uint256 erc721HealthFactor;\n address collateralAsset;\n uint256 tokenId;\n address xTokenAddress;\n }\n\n struct CalculateInterestRatesParams {\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalVariableDebt;\n uint256 reserveFactor;\n address reserve;\n address xToken;\n }\n\n struct InitReserveParams {\n address asset;\n address xTokenAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n address auctionStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n\n struct ExecuteFlashClaimParams {\n address receiverAddress;\n address[] nftAssets;\n uint256[][] nftTokenIds;\n bytes params;\n address oracle;\n }\n\n struct Credit {\n address token;\n uint256 amount;\n bytes orderId;\n uint8 v;\n bytes32 r;\n bytes32 s;\n }\n\n struct ExecuteMarketplaceParams {\n bytes32 marketplaceId;\n bytes payload;\n Credit credit;\n uint256 ethLeft;\n DataTypes.Marketplace marketplace;\n OrderInfo orderInfo;\n address weth;\n uint16 referralCode;\n uint256 reservesCount;\n address oracle;\n address priceOracleSentinel;\n }\n\n struct OrderInfo {\n address maker;\n address taker;\n bytes id;\n OfferItem[] offer;\n ConsiderationItem[] consideration;\n }\n\n struct Marketplace {\n address marketplace;\n address adapter;\n address operator;\n bool paused;\n }\n\n struct Auction {\n uint256 startTime;\n }\n\n struct AuctionData {\n address asset;\n uint256 tokenId;\n uint256 startTime;\n uint256 currentPriceMultiplier;\n uint256 maxPriceMultiplier;\n uint256 minExpPriceMultiplier;\n uint256 minPriceMultiplier;\n uint256 stepLinear;\n uint256 stepExp;\n uint256 tickLength;\n }\n\n struct TokenData {\n string symbol;\n address tokenAddress;\n }\n\n enum ApeCompoundType {\n SwapAndSupply\n }\n\n enum ApeCompoundTokenOut {\n USDC\n }\n\n struct ApeCompoundStrategy {\n ApeCompoundType ty;\n ApeCompoundTokenOut swapTokenOut;\n uint256 swapPercent;\n }\n\n struct PoolStorage {\n // Map of reserves and their data (underlyingAssetOfReserve => reserveData)\n mapping(address => ReserveData) _reserves;\n // Map of users address and their configuration data (userAddress => userConfiguration)\n mapping(address => UserConfigurationMap) _usersConfig;\n // List of reserves as a map (reserveId => reserve).\n // It is structured as a mapping for gas savings reasons, using the reserve id as index\n mapping(uint256 => address) _reservesList;\n // Maximum number of active reserves there have been in the protocol. It is the upper bound of the reserves list\n uint16 _reservesCount;\n // Auction recovery health factor\n uint64 _auctionRecoveryHealthFactor;\n // Incentive fee for claim ape reward to compound\n uint16 _apeCompoundFee;\n // Map of user's ape compound strategies\n mapping(address => ApeCompoundStrategy) _apeCompoundStrategies;\n }\n\n struct ReserveConfigData {\n uint256 decimals;\n uint256 ltv;\n uint256 liquidationThreshold;\n uint256 liquidationBonus;\n uint256 reserveFactor;\n bool usageAsCollateralEnabled;\n bool borrowingEnabled;\n bool isActive;\n bool isFrozen;\n bool isPaused;\n }\n}\n" }, "contracts/protocol/tokenization/VariableDebtToken.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {SafeCast} from \"../../dependencies/openzeppelin/contracts/SafeCast.sol\";\nimport {VersionedInitializable} from \"../libraries/paraspace-upgradeability/VersionedInitializable.sol\";\nimport {WadRayMath} from \"../libraries/math/WadRayMath.sol\";\nimport {Errors} from \"../libraries/helpers/Errors.sol\";\nimport {IPool} from \"../../interfaces/IPool.sol\";\nimport {IRewardController} from \"../../interfaces/IRewardController.sol\";\nimport {IInitializableDebtToken} from \"../../interfaces/IInitializableDebtToken.sol\";\nimport {IVariableDebtToken} from \"../../interfaces/IVariableDebtToken.sol\";\nimport {EIP712Base} from \"./base/EIP712Base.sol\";\nimport {DebtTokenBase} from \"./base/DebtTokenBase.sol\";\nimport {ScaledBalanceTokenBaseERC20} from \"./base/ScaledBalanceTokenBaseERC20.sol\";\n\n/**\n * @title VariableDebtToken\n *\n * @notice Implements a variable debt token to track the borrowing positions of users\n * at variable rate mode\n * @dev Transfer and approve functionalities are disabled since its a non-transferable token\n **/\ncontract VariableDebtToken is\n DebtTokenBase,\n ScaledBalanceTokenBaseERC20,\n IVariableDebtToken\n{\n using WadRayMath for uint256;\n using SafeCast for uint256;\n\n uint256 public constant DEBT_TOKEN_REVISION = 145;\n uint256[50] private __gap;\n\n /**\n * @dev Constructor.\n * @param pool The address of the Pool contract\n */\n constructor(IPool pool)\n DebtTokenBase()\n ScaledBalanceTokenBaseERC20(\n pool,\n \"VARIABLE_DEBT_TOKEN_IMPL\",\n \"VARIABLE_DEBT_TOKEN_IMPL\",\n 0\n )\n {\n // Intentionally left blank\n }\n\n /// @inheritdoc IInitializableDebtToken\n function initialize(\n IPool initializingPool,\n address underlyingAsset,\n IRewardController incentivesController,\n uint8 debtTokenDecimals,\n string memory debtTokenName,\n string memory debtTokenSymbol,\n bytes calldata params\n ) external override initializer {\n require(initializingPool == POOL, Errors.POOL_ADDRESSES_DO_NOT_MATCH);\n _setName(debtTokenName);\n _setSymbol(debtTokenSymbol);\n _setDecimals(debtTokenDecimals);\n\n _underlyingAsset = underlyingAsset;\n _rewardController = incentivesController;\n\n _domainSeparator = _calculateDomainSeparator();\n\n emit Initialized(\n underlyingAsset,\n address(POOL),\n address(incentivesController),\n debtTokenDecimals,\n debtTokenName,\n debtTokenSymbol,\n params\n );\n }\n\n /// @inheritdoc VersionedInitializable\n function getRevision() internal pure virtual override returns (uint256) {\n return DEBT_TOKEN_REVISION;\n }\n\n /// @inheritdoc IERC20\n function balanceOf(address user)\n public\n view\n virtual\n override\n returns (uint256)\n {\n uint256 scaledBalance = super.balanceOf(user);\n\n if (scaledBalance == 0) {\n return 0;\n }\n\n return\n scaledBalance.rayMul(\n POOL.getReserveNormalizedVariableDebt(_underlyingAsset)\n );\n }\n\n /// @inheritdoc IVariableDebtToken\n function mint(\n address user,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) external virtual override onlyPool returns (bool, uint256) {\n if (user != onBehalfOf) {\n _decreaseBorrowAllowance(onBehalfOf, user, amount);\n }\n return (\n _mintScaled(user, onBehalfOf, amount, index),\n scaledTotalSupply()\n );\n }\n\n /// @inheritdoc IVariableDebtToken\n function burn(\n address from,\n uint256 amount,\n uint256 index\n ) external virtual override onlyPool returns (uint256) {\n _burnScaled(from, address(0), amount, index);\n return scaledTotalSupply();\n }\n\n /// @inheritdoc IERC20\n function totalSupply() public view virtual override returns (uint256) {\n return\n super.totalSupply().rayMul(\n POOL.getReserveNormalizedVariableDebt(_underlyingAsset)\n );\n }\n\n /// @inheritdoc EIP712Base\n function _EIP712BaseId() internal view override returns (string memory) {\n return name();\n }\n\n /**\n * @dev Being non transferrable, the debt token does not implement any of the\n * standard ERC20 functions for transfer and allowance.\n **/\n function transfer(address, uint256)\n external\n virtual\n override\n returns (bool)\n {\n revert(Errors.OPERATION_NOT_SUPPORTED);\n }\n\n function allowance(address, address)\n external\n view\n virtual\n override\n returns (uint256)\n {\n revert(Errors.OPERATION_NOT_SUPPORTED);\n }\n\n function approve(address, uint256)\n external\n virtual\n override\n returns (bool)\n {\n revert(Errors.OPERATION_NOT_SUPPORTED);\n }\n\n function transferFrom(\n address,\n address,\n uint256\n ) external virtual override returns (bool) {\n revert(Errors.OPERATION_NOT_SUPPORTED);\n }\n\n function increaseAllowance(address, uint256)\n external\n virtual\n override\n returns (bool)\n {\n revert(Errors.OPERATION_NOT_SUPPORTED);\n }\n\n function decreaseAllowance(address, uint256)\n external\n virtual\n override\n returns (bool)\n {\n revert(Errors.OPERATION_NOT_SUPPORTED);\n }\n\n /// @inheritdoc IVariableDebtToken\n function UNDERLYING_ASSET_ADDRESS()\n external\n view\n override\n returns (address)\n {\n return _underlyingAsset;\n }\n}\n" }, "contracts/protocol/tokenization/base/DebtTokenBase.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {Context} from \"../../../dependencies/openzeppelin/contracts/Context.sol\";\nimport {Errors} from \"../../libraries/helpers/Errors.sol\";\nimport {VersionedInitializable} from \"../../libraries/paraspace-upgradeability/VersionedInitializable.sol\";\nimport {ICreditDelegationToken} from \"../../../interfaces/ICreditDelegationToken.sol\";\nimport {EIP712Base} from \"./EIP712Base.sol\";\n\n/**\n * @title DebtTokenBase\n *\n * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken\n */\nabstract contract DebtTokenBase is\n VersionedInitializable,\n EIP712Base,\n Context,\n ICreditDelegationToken\n{\n // Map of borrow allowances (delegator => delegatee => borrowAllowanceAmount)\n mapping(address => mapping(address => uint256)) internal _borrowAllowances;\n\n // Credit Delegation Typehash\n bytes32 public constant DELEGATION_WITH_SIG_TYPEHASH =\n keccak256(\n \"DelegationWithSig(address delegatee,uint256 value,uint256 nonce,uint256 deadline)\"\n );\n\n address internal _underlyingAsset;\n\n /**\n * @dev Constructor.\n */\n constructor() EIP712Base() {\n // Intentionally left blank\n }\n\n /// @inheritdoc ICreditDelegationToken\n function approveDelegation(address delegatee, uint256 amount)\n external\n override\n {\n _approveDelegation(_msgSender(), delegatee, amount);\n }\n\n /// @inheritdoc ICreditDelegationToken\n function delegationWithSig(\n address delegator,\n address delegatee,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external {\n require(delegator != address(0), Errors.ZERO_ADDRESS_NOT_VALID);\n //solium-disable-next-line\n require(block.timestamp <= deadline, Errors.INVALID_EXPIRATION);\n uint256 currentValidNonce = _nonces[delegator];\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n DELEGATION_WITH_SIG_TYPEHASH,\n delegatee,\n value,\n currentValidNonce,\n deadline\n )\n )\n )\n );\n require(\n delegator == ecrecover(digest, v, r, s),\n Errors.INVALID_SIGNATURE\n );\n _nonces[delegator] = currentValidNonce + 1;\n _approveDelegation(delegator, delegatee, value);\n }\n\n /// @inheritdoc ICreditDelegationToken\n function borrowAllowance(address fromUser, address toUser)\n external\n view\n override\n returns (uint256)\n {\n return _borrowAllowances[fromUser][toUser];\n }\n\n /**\n * @notice Updates the borrow allowance of a user on the specific debt token.\n * @param delegator The address delegating the borrowing power\n * @param delegatee The address receiving the delegated borrowing power\n * @param amount The allowance amount being delegated.\n **/\n function _approveDelegation(\n address delegator,\n address delegatee,\n uint256 amount\n ) internal {\n _borrowAllowances[delegator][delegatee] = amount;\n emit BorrowAllowanceDelegated(\n delegator,\n delegatee,\n _underlyingAsset,\n amount\n );\n }\n\n /**\n * @notice Decreases the borrow allowance of a user on the specific debt token.\n * @param delegator The address delegating the borrowing power\n * @param delegatee The address receiving the delegated borrowing power\n * @param amount The amount to subtract from the current allowance\n **/\n function _decreaseBorrowAllowance(\n address delegator,\n address delegatee,\n uint256 amount\n ) internal {\n uint256 newAllowance = _borrowAllowances[delegator][delegatee] - amount;\n\n _borrowAllowances[delegator][delegatee] = newAllowance;\n\n emit BorrowAllowanceDelegated(\n delegator,\n delegatee,\n _underlyingAsset,\n newAllowance\n );\n }\n}\n" }, "contracts/protocol/tokenization/base/EIP712Base.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\n/**\n * @title EIP712Base\n *\n * @notice Base contract implementation of EIP712.\n */\nabstract contract EIP712Base {\n bytes public constant EIP712_REVISION = bytes(\"1\");\n bytes32 internal constant EIP712_DOMAIN =\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n );\n\n // Map of address nonces (address => nonce)\n mapping(address => uint256) internal _nonces;\n\n bytes32 internal _domainSeparator;\n uint256 internal immutable _chainId;\n\n /**\n * @dev Constructor.\n */\n constructor() {\n _chainId = block.chainid;\n }\n\n /**\n * @notice Get the domain separator for the token\n * @dev Return cached value if chainId matches cache, otherwise recomputes separator\n * @return The domain separator of the token at current chain\n */\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n if (block.chainid == _chainId) {\n return _domainSeparator;\n }\n return _calculateDomainSeparator();\n }\n\n /**\n * @notice Returns the nonce value for address specified as parameter\n * @param owner The address for which the nonce is being returned\n * @return The nonce value for the input address`\n */\n function nonces(address owner) public view virtual returns (uint256) {\n return _nonces[owner];\n }\n\n /**\n * @notice Compute the current domain separator\n * @return The domain separator for the token\n */\n function _calculateDomainSeparator() internal view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n EIP712_DOMAIN,\n keccak256(bytes(_EIP712BaseId())),\n keccak256(EIP712_REVISION),\n block.chainid,\n address(this)\n )\n );\n }\n\n /**\n * @notice Returns the user readable name of signing domain (e.g. token name)\n * @return The name of the signing domain\n */\n function _EIP712BaseId() internal view virtual returns (string memory);\n}\n" }, "contracts/protocol/tokenization/base/IncentivizedERC20.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {Context} from \"../../../dependencies/openzeppelin/contracts/Context.sol\";\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IERC20Detailed} from \"../../../dependencies/openzeppelin/contracts/IERC20Detailed.sol\";\nimport {SafeCast} from \"../../../dependencies/openzeppelin/contracts/SafeCast.sol\";\nimport {WadRayMath} from \"../../libraries/math/WadRayMath.sol\";\nimport {Errors} from \"../../libraries/helpers/Errors.sol\";\nimport {IRewardController} from \"../../../interfaces/IRewardController.sol\";\nimport {IPoolAddressesProvider} from \"../../../interfaces/IPoolAddressesProvider.sol\";\nimport {IPool} from \"../../../interfaces/IPool.sol\";\nimport {IACLManager} from \"../../../interfaces/IACLManager.sol\";\n\n/**\n * @title IncentivizedERC20\n * , inspired by the Openzeppelin ERC20 implementation\n * @notice Basic ERC20 implementation\n **/\nabstract contract IncentivizedERC20 is Context, IERC20Detailed {\n using WadRayMath for uint256;\n using SafeCast for uint256;\n\n /**\n * @dev Only pool admin can call functions marked by this modifier.\n **/\n modifier onlyPoolAdmin() {\n IACLManager aclManager = IACLManager(\n _addressesProvider.getACLManager()\n );\n require(\n aclManager.isPoolAdmin(msg.sender),\n Errors.CALLER_NOT_POOL_ADMIN\n );\n _;\n }\n\n /**\n * @dev Only pool can call functions marked by this modifier.\n **/\n modifier onlyPool() {\n require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_POOL);\n _;\n }\n\n /**\n * @dev UserState - additionalData is a flexible field.\n * PTokens and VariableDebtTokens use this field store the index of the\n * user's last supply/withdrawal/borrow/repayment. StableDebtTokens use\n * this field to store the user's stable rate.\n */\n struct UserState {\n uint128 balance;\n uint128 additionalData;\n }\n // Map of users address and their state data (userAddress => userStateData)\n mapping(address => UserState) internal _userState;\n\n // Map of allowances (delegator => delegatee => allowanceAmount)\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 internal _totalSupply;\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n IRewardController internal _rewardController;\n IPoolAddressesProvider internal immutable _addressesProvider;\n IPool public immutable POOL;\n\n /**\n * @dev Constructor.\n * @param pool The reference to the main Pool contract\n * @param name_ The name of the token\n * @param symbol_ The symbol of the token\n * @param decimals_ The number of decimals of the token\n */\n constructor(\n IPool pool,\n string memory name_,\n string memory symbol_,\n uint8 decimals_\n ) {\n _addressesProvider = pool.ADDRESSES_PROVIDER();\n _name = name_;\n _symbol = symbol_;\n _decimals = decimals_;\n POOL = pool;\n }\n\n /// @inheritdoc IERC20Detailed\n function name() public view override returns (string memory) {\n return _name;\n }\n\n /// @inheritdoc IERC20Detailed\n function symbol() external view override returns (string memory) {\n return _symbol;\n }\n\n /// @inheritdoc IERC20Detailed\n function decimals() external view override returns (uint8) {\n return _decimals;\n }\n\n /// @inheritdoc IERC20\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /// @inheritdoc IERC20\n function balanceOf(address account)\n public\n view\n virtual\n override\n returns (uint256)\n {\n return _userState[account].balance;\n }\n\n /**\n * @notice Returns the address of the Incentives Controller contract\n * @return The address of the Incentives Controller\n **/\n function getIncentivesController()\n external\n view\n virtual\n returns (IRewardController)\n {\n return _rewardController;\n }\n\n /**\n * @notice Sets a new Incentives Controller\n * @param controller the new Incentives controller\n **/\n function setIncentivesController(IRewardController controller)\n external\n onlyPoolAdmin\n {\n _rewardController = controller;\n }\n\n /// @inheritdoc IERC20\n function transfer(address recipient, uint256 amount)\n external\n virtual\n override\n returns (bool)\n {\n uint128 castAmount = amount.toUint128();\n _transfer(_msgSender(), recipient, castAmount);\n return true;\n }\n\n /// @inheritdoc IERC20\n function allowance(address owner, address spender)\n external\n view\n virtual\n override\n returns (uint256)\n {\n return _allowances[owner][spender];\n }\n\n /// @inheritdoc IERC20\n function approve(address spender, uint256 amount)\n external\n virtual\n override\n returns (bool)\n {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /// @inheritdoc IERC20\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external virtual override returns (bool) {\n uint128 castAmount = amount.toUint128();\n _approve(\n sender,\n _msgSender(),\n _allowances[sender][_msgSender()] - castAmount\n );\n _transfer(sender, recipient, castAmount);\n return true;\n }\n\n /**\n * @notice Increases the allowance of spender to spend _msgSender() tokens\n * @param spender The user allowed to spend on behalf of _msgSender()\n * @param addedValue The amount being added to the allowance\n * @return `true`\n **/\n function increaseAllowance(address spender, uint256 addedValue)\n external\n virtual\n returns (bool)\n {\n _approve(\n _msgSender(),\n spender,\n _allowances[_msgSender()][spender] + addedValue\n );\n return true;\n }\n\n /**\n * @notice Decreases the allowance of spender to spend _msgSender() tokens\n * @param spender The user allowed to spend on behalf of _msgSender()\n * @param subtractedValue The amount being subtracted to the allowance\n * @return `true`\n **/\n function decreaseAllowance(address spender, uint256 subtractedValue)\n external\n virtual\n returns (bool)\n {\n _approve(\n _msgSender(),\n spender,\n _allowances[_msgSender()][spender] - subtractedValue\n );\n return true;\n }\n\n /**\n * @notice Transfers tokens between two users and apply incentives if defined.\n * @param sender The source address\n * @param recipient The destination address\n * @param amount The amount getting transferred\n */\n function _transfer(\n address sender,\n address recipient,\n uint128 amount\n ) internal virtual {\n uint128 oldSenderBalance = _userState[sender].balance;\n _userState[sender].balance = oldSenderBalance - amount;\n uint128 oldRecipientBalance = _userState[recipient].balance;\n _userState[recipient].balance = oldRecipientBalance + amount;\n\n IRewardController rewardControllerLocal = _rewardController;\n if (address(rewardControllerLocal) != address(0)) {\n uint256 currentTotalSupply = _totalSupply;\n rewardControllerLocal.handleAction(\n sender,\n currentTotalSupply,\n oldSenderBalance\n );\n if (sender != recipient) {\n rewardControllerLocal.handleAction(\n recipient,\n currentTotalSupply,\n oldRecipientBalance\n );\n }\n }\n }\n\n /**\n * @notice Approve `spender` to use `amount` of `owner`s balance\n * @param owner The address owning the tokens\n * @param spender The address approved for spending\n * @param amount The amount of tokens to approve spending of\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @notice Update the name of the token\n * @param newName The new name for the token\n */\n function _setName(string memory newName) internal {\n _name = newName;\n }\n\n /**\n * @notice Update the symbol for the token\n * @param newSymbol The new symbol for the token\n */\n function _setSymbol(string memory newSymbol) internal {\n _symbol = newSymbol;\n }\n\n /**\n * @notice Update the number of decimals for the token\n * @param newDecimals The new number of decimals for the token\n */\n function _setDecimals(uint8 newDecimals) internal {\n _decimals = newDecimals;\n }\n}\n" }, "contracts/protocol/tokenization/base/MintableIncentivizedERC20.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\nimport {IRewardController} from \"../../../interfaces/IRewardController.sol\";\nimport {IPool} from \"../../../interfaces/IPool.sol\";\nimport {IncentivizedERC20} from \"./IncentivizedERC20.sol\";\n\n/**\n * @title MintableIncentivizedERC20\n *\n * @notice Implements mint and burn functions for IncentivizedERC20\n **/\nabstract contract MintableIncentivizedERC20 is IncentivizedERC20 {\n /**\n * @dev Constructor.\n * @param pool The reference to the main Pool contract\n * @param name The name of the token\n * @param symbol The symbol of the token\n * @param decimals The number of decimals of the token\n */\n constructor(\n IPool pool,\n string memory name,\n string memory symbol,\n uint8 decimals\n ) IncentivizedERC20(pool, name, symbol, decimals) {\n // Intentionally left blank\n }\n\n /**\n * @notice Mints tokens to an account and apply incentives if defined\n * @param account The address receiving tokens\n * @param amount The amount of tokens to mint\n */\n function _mint(address account, uint128 amount) internal virtual {\n uint256 oldTotalSupply = _totalSupply;\n _totalSupply = oldTotalSupply + amount;\n\n uint128 oldAccountBalance = _userState[account].balance;\n _userState[account].balance = oldAccountBalance + amount;\n\n IRewardController rewardControllerLocal = _rewardController;\n if (address(rewardControllerLocal) != address(0)) {\n rewardControllerLocal.handleAction(\n account,\n oldTotalSupply,\n oldAccountBalance\n );\n }\n }\n\n /**\n * @notice Burns tokens from an account and apply incentives if defined\n * @param account The account whose tokens are burnt\n * @param amount The amount of tokens to burn\n */\n function _burn(address account, uint128 amount) internal virtual {\n uint256 oldTotalSupply = _totalSupply;\n _totalSupply = oldTotalSupply - amount;\n\n uint128 oldAccountBalance = _userState[account].balance;\n _userState[account].balance = oldAccountBalance - amount;\n\n IRewardController rewardControllerLocal = _rewardController;\n\n if (address(rewardControllerLocal) != address(0)) {\n rewardControllerLocal.handleAction(\n account,\n oldTotalSupply,\n oldAccountBalance\n );\n }\n }\n}\n" }, "contracts/protocol/tokenization/base/ScaledBalanceTokenBaseERC20.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\nimport {SafeCast} from \"../../../dependencies/openzeppelin/contracts/SafeCast.sol\";\nimport {Errors} from \"../../libraries/helpers/Errors.sol\";\nimport {WadRayMath} from \"../../libraries/math/WadRayMath.sol\";\nimport {IPool} from \"../../../interfaces/IPool.sol\";\nimport {IScaledBalanceToken} from \"../../../interfaces/IScaledBalanceToken.sol\";\nimport {MintableIncentivizedERC20} from \"./MintableIncentivizedERC20.sol\";\n\n/**\n * @title ScaledBalanceTokenBase\n *\n * @notice Basic ERC20 implementation of scaled balance token\n **/\nabstract contract ScaledBalanceTokenBaseERC20 is\n MintableIncentivizedERC20,\n IScaledBalanceToken\n{\n using WadRayMath for uint256;\n using SafeCast for uint256;\n\n /**\n * @dev Constructor.\n * @param pool The reference to the main Pool contract\n * @param name The name of the token\n * @param symbol The symbol of the token\n * @param decimals The number of decimals of the token\n */\n constructor(\n IPool pool,\n string memory name,\n string memory symbol,\n uint8 decimals\n ) MintableIncentivizedERC20(pool, name, symbol, decimals) {\n // Intentionally left blank\n }\n\n /// @inheritdoc IScaledBalanceToken\n function scaledBalanceOf(address user)\n public\n view\n virtual\n override\n returns (uint256)\n {\n return super.balanceOf(user);\n }\n\n /// @inheritdoc IScaledBalanceToken\n function getScaledUserBalanceAndSupply(address user)\n external\n view\n virtual\n override\n returns (uint256, uint256)\n {\n return (super.balanceOf(user), super.totalSupply());\n }\n\n /// @inheritdoc IScaledBalanceToken\n function scaledTotalSupply()\n public\n view\n virtual\n override\n returns (uint256)\n {\n return super.totalSupply();\n }\n\n /// @inheritdoc IScaledBalanceToken\n function getPreviousIndex(address user)\n external\n view\n virtual\n override\n returns (uint256)\n {\n return _userState[user].additionalData;\n }\n\n /**\n * @notice Implements the basic logic to mint a scaled balance token.\n * @param caller The address performing the mint\n * @param onBehalfOf The address of the user that will receive the scaled tokens\n * @param amount The amount of tokens getting minted\n * @param index The next liquidity index of the reserve\n * @return `true` if the the previous balance of the user was 0\n **/\n function _mintScaled(\n address caller,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) internal virtual returns (bool) {\n uint256 amountScaled = amount.rayDiv(index);\n require(amountScaled != 0, Errors.INVALID_MINT_AMOUNT);\n\n uint256 scaledBalance = super.balanceOf(onBehalfOf);\n uint256 balanceIncrease = scaledBalance.rayMul(index) -\n scaledBalance.rayMul(_userState[onBehalfOf].additionalData);\n\n _userState[onBehalfOf].additionalData = index.toUint128();\n\n _mint(onBehalfOf, amountScaled.toUint128());\n\n uint256 amountToMint = amount + balanceIncrease;\n emit Transfer(address(0), onBehalfOf, amountToMint);\n emit Mint(caller, onBehalfOf, amountToMint, balanceIncrease, index);\n\n return (scaledBalance == 0);\n }\n\n /**\n * @notice Implements the basic logic to burn a scaled balance token.\n * @dev In some instances, a burn transaction will emit a mint event\n * if the amount to burn is less than the interest that the user accrued\n * @param user The user which debt is burnt\n * @param target The address that will receive the underlying, if any\n * @param amount The amount getting burned\n * @param index The variable debt index of the reserve\n **/\n function _burnScaled(\n address user,\n address target,\n uint256 amount,\n uint256 index\n ) internal virtual {\n uint256 amountScaled = amount.rayDiv(index);\n require(amountScaled != 0, Errors.INVALID_BURN_AMOUNT);\n\n uint256 scaledBalance = super.balanceOf(user);\n uint256 balanceIncrease = scaledBalance.rayMul(index) -\n scaledBalance.rayMul(_userState[user].additionalData);\n\n _userState[user].additionalData = index.toUint128();\n\n _burn(user, amountScaled.toUint128());\n\n if (balanceIncrease > amount) {\n uint256 amountToMint = balanceIncrease - amount;\n emit Transfer(address(0), user, amountToMint);\n emit Mint(user, user, amountToMint, balanceIncrease, index);\n } else {\n uint256 amountToBurn = amount - balanceIncrease;\n emit Transfer(user, address(0), amountToBurn);\n emit Burn(user, target, amountToBurn, balanceIncrease, index);\n }\n }\n\n function _transferScaled(\n address from,\n address to,\n uint256 amount,\n uint256 index\n ) internal virtual {\n super._transfer(from, to, amount.rayDiv(index).toUint128());\n }\n}\n" } }, "settings": { "remappings": [ "contracts/=contracts/", "ds-test/=lib/ds-test/src/", "forge-std/=lib/forge-std/src/", "pnm-contracts/=lib/pnm-contracts/" ], "optimizer": { "enabled": true, "runs": 1000 }, "metadata": { "bytecodeHash": "ipfs" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "london", "libraries": {} } }