ERC721Enumerable.sol 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. pragma solidity ^0.5.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 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 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 returns (uint256) {
  58. require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
  59. return _allTokens[index];
  60. }
  61. /**
  62. * @dev Internal function to transfer ownership of a given token ID to another address.
  63. * As opposed to transferFrom, this imposes no restrictions on msg.sender.
  64. * @param from current owner of the token
  65. * @param to address to receive the ownership of the given token ID
  66. * @param tokenId uint256 ID of the token to be transferred
  67. */
  68. function _transferFrom(address from, address to, uint256 tokenId) internal {
  69. super._transferFrom(from, to, tokenId);
  70. _removeTokenFromOwnerEnumeration(from, tokenId);
  71. _addTokenToOwnerEnumeration(to, tokenId);
  72. }
  73. /**
  74. * @dev Internal function to mint a new token.
  75. * Reverts if the given token ID already exists.
  76. * @param to address the beneficiary that will own the minted token
  77. * @param tokenId uint256 ID of the token to be minted
  78. */
  79. function _mint(address to, uint256 tokenId) internal {
  80. super._mint(to, tokenId);
  81. _addTokenToOwnerEnumeration(to, tokenId);
  82. _addTokenToAllTokensEnumeration(tokenId);
  83. }
  84. /**
  85. * @dev Internal function to burn a specific token.
  86. * Reverts if the token does not exist.
  87. * Deprecated, use {ERC721-_burn} instead.
  88. * @param owner owner of the token to burn
  89. * @param tokenId uint256 ID of the token being burned
  90. */
  91. function _burn(address owner, uint256 tokenId) internal {
  92. super._burn(owner, tokenId);
  93. _removeTokenFromOwnerEnumeration(owner, tokenId);
  94. // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
  95. _ownedTokensIndex[tokenId] = 0;
  96. _removeTokenFromAllTokensEnumeration(tokenId);
  97. }
  98. /**
  99. * @dev Gets the list of token IDs of the requested owner.
  100. * @param owner address owning the tokens
  101. * @return uint256[] List of token IDs owned by the requested address
  102. */
  103. function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
  104. return _ownedTokens[owner];
  105. }
  106. /**
  107. * @dev Private function to add a token to this extension's ownership-tracking data structures.
  108. * @param to address representing the new owner of the given token ID
  109. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  110. */
  111. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
  112. _ownedTokensIndex[tokenId] = _ownedTokens[to].length;
  113. _ownedTokens[to].push(tokenId);
  114. }
  115. /**
  116. * @dev Private function to add a token to this extension's token tracking data structures.
  117. * @param tokenId uint256 ID of the token to be added to the tokens list
  118. */
  119. function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
  120. _allTokensIndex[tokenId] = _allTokens.length;
  121. _allTokens.push(tokenId);
  122. }
  123. /**
  124. * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
  125. * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
  126. * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
  127. * This has O(1) time complexity, but alters the order of the _ownedTokens array.
  128. * @param from address representing the previous owner of the given token ID
  129. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  130. */
  131. function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
  132. // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
  133. // then delete the last slot (swap and pop).
  134. uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
  135. uint256 tokenIndex = _ownedTokensIndex[tokenId];
  136. // When the token to delete is the last token, the swap operation is unnecessary
  137. if (tokenIndex != lastTokenIndex) {
  138. uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
  139. _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  140. _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  141. }
  142. // This also deletes the contents at the last position of the array
  143. _ownedTokens[from].length--;
  144. // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
  145. // lastTokenId, or just over the end of the array if the token was the last one).
  146. }
  147. /**
  148. * @dev Private function to remove a token from this extension's token tracking data structures.
  149. * This has O(1) time complexity, but alters the order of the _allTokens array.
  150. * @param tokenId uint256 ID of the token to be removed from the tokens list
  151. */
  152. function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
  153. // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
  154. // then delete the last slot (swap and pop).
  155. uint256 lastTokenIndex = _allTokens.length.sub(1);
  156. uint256 tokenIndex = _allTokensIndex[tokenId];
  157. // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
  158. // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
  159. // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
  160. uint256 lastTokenId = _allTokens[lastTokenIndex];
  161. _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  162. _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  163. // This also deletes the contents at the last position of the array
  164. _allTokens.length--;
  165. _allTokensIndex[tokenId] = 0;
  166. }
  167. }