ERC721Enumerable.sol 8.5 KB

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