ERC721EnumerableUpgradeable.sol 7.5 KB

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