ERC721Enumerable.sol 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. pragma solidity ^0.6.0;
  2. import "../../GSN/Context.sol";
  3. import "./IERC721Enumerable.sol";
  4. import "./ERC721.sol";
  5. import "../../introspection/ERC165.sol";
  6. /**
  7. * @title ERC-721 Non-Fungible Token with optional enumeration extension logic
  8. * @dev See https://eips.ethereum.org/EIPS/eip-721
  9. */
  10. contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
  11. // Mapping from owner to list of owned token IDs
  12. mapping(address => uint256[]) private _ownedTokens;
  13. // Mapping from token ID to index of the owner tokens list
  14. mapping(uint256 => uint256) private _ownedTokensIndex;
  15. // Array with all token ids, used for enumeration
  16. uint256[] private _allTokens;
  17. // Mapping from token id to position in the allTokens array
  18. mapping(uint256 => uint256) private _allTokensIndex;
  19. /*
  20. * bytes4(keccak256('totalSupply()')) == 0x18160ddd
  21. * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
  22. * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
  23. *
  24. * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
  25. */
  26. bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
  27. /**
  28. * @dev Constructor function.
  29. */
  30. constructor () public {
  31. // register the supported interface to conform to ERC721Enumerable via ERC165
  32. _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
  33. }
  34. /**
  35. * @dev Gets the token ID at a given index of the tokens list of the requested owner.
  36. * @param owner address owning the tokens list to be accessed
  37. * @param index uint256 representing the index to be accessed of the requested tokens list
  38. * @return uint256 token ID at the given index of the tokens list owned by the requested address
  39. */
  40. function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
  41. require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
  42. return _ownedTokens[owner][index];
  43. }
  44. /**
  45. * @dev Gets the total amount of tokens stored by the contract.
  46. * @return uint256 representing the total amount of tokens
  47. */
  48. function totalSupply() public view override returns (uint256) {
  49. return _allTokens.length;
  50. }
  51. /**
  52. * @dev Gets the token ID at a given index of all the tokens in this contract
  53. * Reverts if the index is greater or equal to the total number of tokens.
  54. * @param index uint256 representing the index to be accessed of the tokens list
  55. * @return uint256 token ID at the given index of the tokens list
  56. */
  57. function tokenByIndex(uint256 index) public view override returns (uint256) {
  58. require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
  59. return _allTokens[index];
  60. }
  61. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
  62. super._beforeTokenTransfer(from, to, tokenId);
  63. if (from == address(0)) {
  64. // When minting
  65. _addTokenToOwnerEnumeration(to, tokenId);
  66. _addTokenToAllTokensEnumeration(tokenId);
  67. } else if (to == address(0)) {
  68. // When burning
  69. _removeTokenFromOwnerEnumeration(from, tokenId);
  70. // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
  71. _ownedTokensIndex[tokenId] = 0;
  72. _removeTokenFromAllTokensEnumeration(tokenId);
  73. } else {
  74. _removeTokenFromOwnerEnumeration(from, tokenId);
  75. _addTokenToOwnerEnumeration(to, tokenId);
  76. }
  77. }
  78. /**
  79. * @dev Gets the list of token IDs of the requested owner.
  80. * @param owner address owning the tokens
  81. * @return uint256[] List of token IDs owned by the requested address
  82. */
  83. function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
  84. return _ownedTokens[owner];
  85. }
  86. /**
  87. * @dev Private function to add a token to this extension's ownership-tracking data structures.
  88. * @param to address representing the new owner of the given token ID
  89. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  90. */
  91. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
  92. _ownedTokensIndex[tokenId] = _ownedTokens[to].length;
  93. _ownedTokens[to].push(tokenId);
  94. }
  95. /**
  96. * @dev Private function to add a token to this extension's token tracking data structures.
  97. * @param tokenId uint256 ID of the token to be added to the tokens list
  98. */
  99. function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
  100. _allTokensIndex[tokenId] = _allTokens.length;
  101. _allTokens.push(tokenId);
  102. }
  103. /**
  104. * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
  105. * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
  106. * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
  107. * This has O(1) time complexity, but alters the order of the _ownedTokens array.
  108. * @param from address representing the previous owner of the given token ID
  109. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  110. */
  111. function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
  112. // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
  113. // then delete the last slot (swap and pop).
  114. uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
  115. uint256 tokenIndex = _ownedTokensIndex[tokenId];
  116. // When the token to delete is the last token, the swap operation is unnecessary
  117. if (tokenIndex != lastTokenIndex) {
  118. uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
  119. _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  120. _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  121. }
  122. // Deletes the contents at the last position of the array
  123. _ownedTokens[from].pop();
  124. // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
  125. // lastTokenId, or just over the end of the array if the token was the last one).
  126. }
  127. /**
  128. * @dev Private function to remove a token from this extension's token tracking data structures.
  129. * This has O(1) time complexity, but alters the order of the _allTokens array.
  130. * @param tokenId uint256 ID of the token to be removed from the tokens list
  131. */
  132. function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
  133. // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
  134. // then delete the last slot (swap and pop).
  135. uint256 lastTokenIndex = _allTokens.length.sub(1);
  136. uint256 tokenIndex = _allTokensIndex[tokenId];
  137. // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
  138. // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
  139. // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
  140. uint256 lastTokenId = _allTokens[lastTokenIndex];
  141. _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  142. _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  143. // Delete the contents at the last position of the array
  144. _allTokens.pop();
  145. _allTokensIndex[tokenId] = 0;
  146. }
  147. }