ERC721Enumerable.sol 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.8.0-rc.0) (token/ERC721/extensions/ERC721Enumerable.sol)
  3. pragma solidity ^0.8.0;
  4. import "../ERC721.sol";
  5. import "./IERC721Enumerable.sol";
  6. /**
  7. * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
  8. * enumerability of all the token ids in the contract as well as all token ids owned by each
  9. * account.
  10. */
  11. abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
  12. // Mapping from owner to list of owned token IDs
  13. mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
  14. // Mapping from token ID to index of the owner tokens list
  15. mapping(uint256 => uint256) private _ownedTokensIndex;
  16. // Array with all token ids, used for enumeration
  17. uint256[] private _allTokens;
  18. // Mapping from token id to position in the allTokens array
  19. mapping(uint256 => uint256) private _allTokensIndex;
  20. /**
  21. * @dev See {IERC165-supportsInterface}.
  22. */
  23. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
  24. return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
  25. }
  26. /**
  27. * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
  28. */
  29. function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
  30. require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
  31. return _ownedTokens[owner][index];
  32. }
  33. /**
  34. * @dev See {IERC721Enumerable-totalSupply}.
  35. */
  36. function totalSupply() public view virtual override returns (uint256) {
  37. return _allTokens.length;
  38. }
  39. /**
  40. * @dev See {IERC721Enumerable-tokenByIndex}.
  41. */
  42. function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
  43. require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
  44. return _allTokens[index];
  45. }
  46. /**
  47. * @dev Hook that is called before any token transfer. This includes minting
  48. * and burning.
  49. *
  50. * Calling conditions:
  51. *
  52. * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
  53. * transferred to `to`.
  54. * - When `from` is zero, `tokenId` will be minted for `to`.
  55. * - When `to` is zero, ``from``'s `tokenId` will be burned.
  56. * - `from` and 'to' cannot be the zero address at the same time.
  57. *
  58. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  59. */
  60. function _beforeTokenTransfer(
  61. address from,
  62. address to,
  63. uint256 tokenId
  64. ) internal virtual override {
  65. super._beforeTokenTransfer(from, to, tokenId);
  66. if (from == address(0)) {
  67. _addTokenToAllTokensEnumeration(tokenId);
  68. } else if (from != to) {
  69. _removeTokenFromOwnerEnumeration(from, tokenId);
  70. }
  71. if (to == address(0)) {
  72. _removeTokenFromAllTokensEnumeration(tokenId);
  73. } else if (to != from) {
  74. _addTokenToOwnerEnumeration(to, tokenId);
  75. }
  76. }
  77. /**
  78. * @dev Hook that is called before any batch token transfer. For now this is limited
  79. * to batch minting by the {ERC721Consecutive} extension.
  80. *
  81. * Calling conditions:
  82. *
  83. * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
  84. * transferred to `to`.
  85. * - When `from` is zero, `tokenId` will be minted for `to`.
  86. * - When `to` is zero, ``from``'s `tokenId` will be burned.
  87. * - `from` cannot be the zero address.
  88. * - `to` cannot be the zero address.
  89. *
  90. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  91. */
  92. function _beforeConsecutiveTokenTransfer(
  93. address,
  94. address,
  95. uint256,
  96. uint96 size
  97. ) internal virtual override {
  98. // We revert because enumerability is not supported with consecutive batch minting.
  99. // This conditional is only needed to silence spurious warnings about unreachable code.
  100. if (size > 0) {
  101. revert("ERC721Enumerable: consecutive transfers not supported");
  102. }
  103. }
  104. /**
  105. * @dev Private function to add a token to this extension's ownership-tracking data structures.
  106. * @param to address representing the new owner of the given token ID
  107. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  108. */
  109. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
  110. uint256 length = ERC721.balanceOf(to);
  111. _ownedTokens[to][length] = tokenId;
  112. _ownedTokensIndex[tokenId] = length;
  113. }
  114. /**
  115. * @dev Private function to add a token to this extension's token tracking data structures.
  116. * @param tokenId uint256 ID of the token to be added to the tokens list
  117. */
  118. function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
  119. _allTokensIndex[tokenId] = _allTokens.length;
  120. _allTokens.push(tokenId);
  121. }
  122. /**
  123. * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
  124. * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
  125. * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
  126. * This has O(1) time complexity, but alters the order of the _ownedTokens array.
  127. * @param from address representing the previous owner of the given token ID
  128. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  129. */
  130. function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
  131. // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
  132. // then delete the last slot (swap and pop).
  133. uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
  134. uint256 tokenIndex = _ownedTokensIndex[tokenId];
  135. // When the token to delete is the last token, the swap operation is unnecessary
  136. if (tokenIndex != lastTokenIndex) {
  137. uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
  138. _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  139. _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  140. }
  141. // This also deletes the contents at the last position of the array
  142. delete _ownedTokensIndex[tokenId];
  143. delete _ownedTokens[from][lastTokenIndex];
  144. }
  145. /**
  146. * @dev Private function to remove a token from this extension's token tracking data structures.
  147. * This has O(1) time complexity, but alters the order of the _allTokens array.
  148. * @param tokenId uint256 ID of the token to be removed from the tokens list
  149. */
  150. function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
  151. // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
  152. // then delete the last slot (swap and pop).
  153. uint256 lastTokenIndex = _allTokens.length - 1;
  154. uint256 tokenIndex = _allTokensIndex[tokenId];
  155. // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
  156. // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
  157. // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
  158. uint256 lastTokenId = _allTokens[lastTokenIndex];
  159. _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  160. _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  161. // This also deletes the contents at the last position of the array
  162. delete _allTokensIndex[tokenId];
  163. _allTokens.pop();
  164. }
  165. }