ERC721Enumerable.sol 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0-rc.0) (token/ERC721/extensions/ERC721Enumerable.sol)
  3. pragma solidity ^0.8.20;
  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 ERC 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(address owner => mapping(uint256 index => uint256)) private _ownedTokens;
  16. mapping(uint256 tokenId => uint256) private _ownedTokensIndex;
  17. uint256[] private _allTokens;
  18. mapping(uint256 tokenId => uint256) private _allTokensIndex;
  19. /**
  20. * @dev An `owner`'s token query was out of bounds for `index`.
  21. *
  22. * NOTE: The owner being `address(0)` indicates a global out of bounds index.
  23. */
  24. error ERC721OutOfBoundsIndex(address owner, uint256 index);
  25. /**
  26. * @dev Batch mint is not allowed.
  27. */
  28. error ERC721EnumerableForbiddenBatchMint();
  29. /**
  30. * @dev See {IERC165-supportsInterface}.
  31. */
  32. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
  33. return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
  34. }
  35. /**
  36. * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
  37. */
  38. function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
  39. if (index >= balanceOf(owner)) {
  40. revert ERC721OutOfBoundsIndex(owner, index);
  41. }
  42. return _ownedTokens[owner][index];
  43. }
  44. /**
  45. * @dev See {IERC721Enumerable-totalSupply}.
  46. */
  47. function totalSupply() public view virtual returns (uint256) {
  48. return _allTokens.length;
  49. }
  50. /**
  51. * @dev See {IERC721Enumerable-tokenByIndex}.
  52. */
  53. function tokenByIndex(uint256 index) public view virtual returns (uint256) {
  54. if (index >= totalSupply()) {
  55. revert ERC721OutOfBoundsIndex(address(0), index);
  56. }
  57. return _allTokens[index];
  58. }
  59. /**
  60. * @dev See {ERC721-_update}.
  61. */
  62. function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {
  63. address previousOwner = super._update(to, tokenId, auth);
  64. if (previousOwner == address(0)) {
  65. _addTokenToAllTokensEnumeration(tokenId);
  66. } else if (previousOwner != to) {
  67. _removeTokenFromOwnerEnumeration(previousOwner, tokenId);
  68. }
  69. if (to == address(0)) {
  70. _removeTokenFromAllTokensEnumeration(tokenId);
  71. } else if (previousOwner != to) {
  72. _addTokenToOwnerEnumeration(to, tokenId);
  73. }
  74. return previousOwner;
  75. }
  76. /**
  77. * @dev Private function to add a token to this extension's ownership-tracking data structures.
  78. * @param to address representing the new owner of the given token ID
  79. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  80. */
  81. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
  82. uint256 length = balanceOf(to) - 1;
  83. _ownedTokens[to][length] = tokenId;
  84. _ownedTokensIndex[tokenId] = length;
  85. }
  86. /**
  87. * @dev Private function to add a token to this extension's token tracking data structures.
  88. * @param tokenId uint256 ID of the token to be added to the tokens list
  89. */
  90. function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
  91. _allTokensIndex[tokenId] = _allTokens.length;
  92. _allTokens.push(tokenId);
  93. }
  94. /**
  95. * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
  96. * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
  97. * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
  98. * This has O(1) time complexity, but alters the order of the _ownedTokens array.
  99. * @param from address representing the previous owner of the given token ID
  100. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  101. */
  102. function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
  103. // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
  104. // then delete the last slot (swap and pop).
  105. uint256 lastTokenIndex = balanceOf(from);
  106. uint256 tokenIndex = _ownedTokensIndex[tokenId];
  107. mapping(uint256 index => uint256) storage _ownedTokensByOwner = _ownedTokens[from];
  108. // When the token to delete is the last token, the swap operation is unnecessary
  109. if (tokenIndex != lastTokenIndex) {
  110. uint256 lastTokenId = _ownedTokensByOwner[lastTokenIndex];
  111. _ownedTokensByOwner[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  112. _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  113. }
  114. // This also deletes the contents at the last position of the array
  115. delete _ownedTokensIndex[tokenId];
  116. delete _ownedTokensByOwner[lastTokenIndex];
  117. }
  118. /**
  119. * @dev Private function to remove a token from this extension's token tracking data structures.
  120. * This has O(1) time complexity, but alters the order of the _allTokens array.
  121. * @param tokenId uint256 ID of the token to be removed from the tokens list
  122. */
  123. function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
  124. // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
  125. // then delete the last slot (swap and pop).
  126. uint256 lastTokenIndex = _allTokens.length - 1;
  127. uint256 tokenIndex = _allTokensIndex[tokenId];
  128. // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
  129. // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
  130. // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
  131. uint256 lastTokenId = _allTokens[lastTokenIndex];
  132. _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  133. _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  134. // This also deletes the contents at the last position of the array
  135. delete _allTokensIndex[tokenId];
  136. _allTokens.pop();
  137. }
  138. /**
  139. * See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch
  140. */
  141. function _increaseBalance(address account, uint128 amount) internal virtual override {
  142. if (amount > 0) {
  143. revert ERC721EnumerableForbiddenBatchMint();
  144. }
  145. super._increaseBalance(account, amount);
  146. }
  147. }