ERC721Enumerable.sol 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)
  3. pragma solidity ^0.8.19;
  4. import {ERC721} from "../ERC721.sol";
  5. import {IERC721Enumerable} from "./IERC721Enumerable.sol";
  6. import {IERC165} from "../../../utils/introspection/ERC165.sol";
  7. /**
  8. * @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability
  9. * of all the token ids in the contract as well as all token ids owned by each account.
  10. *
  11. * CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`,
  12. * interfere with enumerability and should not be used together with `ERC721Enumerable`.
  13. */
  14. abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
  15. // Mapping from owner to list of owned token IDs
  16. mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
  17. // Mapping from token ID to index of the owner tokens list
  18. mapping(uint256 => uint256) private _ownedTokensIndex;
  19. // Array with all token ids, used for enumeration
  20. uint256[] private _allTokens;
  21. // Mapping from token id to position in the allTokens array
  22. mapping(uint256 => uint256) private _allTokensIndex;
  23. /**
  24. * @dev An `owner`'s token query was out of bounds for `index`.
  25. *
  26. * NOTE: The owner being `address(0)` indicates a global out of bounds index.
  27. */
  28. error ERC721OutOfBoundsIndex(address owner, uint256 index);
  29. /**
  30. * @dev Batch mint is not allowed.
  31. */
  32. error ERC721EnumerableForbiddenBatchMint();
  33. /**
  34. * @dev See {IERC165-supportsInterface}.
  35. */
  36. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
  37. return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
  38. }
  39. /**
  40. * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
  41. */
  42. function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
  43. if (index >= balanceOf(owner)) {
  44. revert ERC721OutOfBoundsIndex(owner, index);
  45. }
  46. return _ownedTokens[owner][index];
  47. }
  48. /**
  49. * @dev See {IERC721Enumerable-totalSupply}.
  50. */
  51. function totalSupply() public view virtual returns (uint256) {
  52. return _allTokens.length;
  53. }
  54. /**
  55. * @dev See {IERC721Enumerable-tokenByIndex}.
  56. */
  57. function tokenByIndex(uint256 index) public view virtual returns (uint256) {
  58. if (index >= totalSupply()) {
  59. revert ERC721OutOfBoundsIndex(address(0), index);
  60. }
  61. return _allTokens[index];
  62. }
  63. /**
  64. * @dev See {ERC721-_beforeTokenTransfer}.
  65. */
  66. function _beforeTokenTransfer(
  67. address from,
  68. address to,
  69. uint256 firstTokenId,
  70. uint256 batchSize
  71. ) internal virtual override {
  72. super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
  73. if (batchSize > 1) {
  74. // Will only trigger during construction. Batch transferring (minting) is not available afterwards.
  75. revert ERC721EnumerableForbiddenBatchMint();
  76. }
  77. uint256 tokenId = firstTokenId;
  78. if (from == address(0)) {
  79. _addTokenToAllTokensEnumeration(tokenId);
  80. } else if (from != to) {
  81. _removeTokenFromOwnerEnumeration(from, tokenId);
  82. }
  83. if (to == address(0)) {
  84. _removeTokenFromAllTokensEnumeration(tokenId);
  85. } else if (to != from) {
  86. _addTokenToOwnerEnumeration(to, tokenId);
  87. }
  88. }
  89. /**
  90. * @dev Private function to add a token to this extension's ownership-tracking data structures.
  91. * @param to address representing the new owner of the given token ID
  92. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  93. */
  94. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
  95. uint256 length = balanceOf(to);
  96. _ownedTokens[to][length] = tokenId;
  97. _ownedTokensIndex[tokenId] = length;
  98. }
  99. /**
  100. * @dev Private function to add a token to this extension's token tracking data structures.
  101. * @param tokenId uint256 ID of the token to be added to the tokens list
  102. */
  103. function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
  104. _allTokensIndex[tokenId] = _allTokens.length;
  105. _allTokens.push(tokenId);
  106. }
  107. /**
  108. * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
  109. * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
  110. * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
  111. * This has O(1) time complexity, but alters the order of the _ownedTokens array.
  112. * @param from address representing the previous owner of the given token ID
  113. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  114. */
  115. function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
  116. // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
  117. // then delete the last slot (swap and pop).
  118. uint256 lastTokenIndex = balanceOf(from) - 1;
  119. uint256 tokenIndex = _ownedTokensIndex[tokenId];
  120. // When the token to delete is the last token, the swap operation is unnecessary
  121. if (tokenIndex != lastTokenIndex) {
  122. uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
  123. _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  124. _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  125. }
  126. // This also deletes the contents at the last position of the array
  127. delete _ownedTokensIndex[tokenId];
  128. delete _ownedTokens[from][lastTokenIndex];
  129. }
  130. /**
  131. * @dev Private function to remove a token from this extension's token tracking data structures.
  132. * This has O(1) time complexity, but alters the order of the _allTokens array.
  133. * @param tokenId uint256 ID of the token to be removed from the tokens list
  134. */
  135. function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
  136. // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
  137. // then delete the last slot (swap and pop).
  138. uint256 lastTokenIndex = _allTokens.length - 1;
  139. uint256 tokenIndex = _allTokensIndex[tokenId];
  140. // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
  141. // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
  142. // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
  143. uint256 lastTokenId = _allTokens[lastTokenIndex];
  144. _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  145. _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  146. // This also deletes the contents at the last position of the array
  147. delete _allTokensIndex[tokenId];
  148. _allTokens.pop();
  149. }
  150. }