ERC721Enumerable.sol 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. pragma solidity ^0.4.24;
  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://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
  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. bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
  19. /**
  20. * 0x780e9d63 ===
  21. * bytes4(keccak256('totalSupply()')) ^
  22. * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
  23. * bytes4(keccak256('tokenByIndex(uint256)'))
  24. */
  25. /**
  26. * @dev Constructor function
  27. */
  28. constructor () public {
  29. // register the supported interface to conform to ERC721 via ERC165
  30. _registerInterface(_InterfaceId_ERC721Enumerable);
  31. }
  32. /**
  33. * @dev Gets the token ID at a given index of the tokens list of the requested owner
  34. * @param owner address owning the tokens list to be accessed
  35. * @param index uint256 representing the index to be accessed of the requested tokens list
  36. * @return uint256 token ID at the given index of the tokens list owned by the requested address
  37. */
  38. function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
  39. require(index < balanceOf(owner));
  40. return _ownedTokens[owner][index];
  41. }
  42. /**
  43. * @dev Gets the total amount of tokens stored by the contract
  44. * @return uint256 representing the total amount of tokens
  45. */
  46. function totalSupply() public view returns (uint256) {
  47. return _allTokens.length;
  48. }
  49. /**
  50. * @dev Gets the token ID at a given index of all the tokens in this contract
  51. * Reverts if the index is greater or equal to the total number of tokens
  52. * @param index uint256 representing the index to be accessed of the tokens list
  53. * @return uint256 token ID at the given index of the tokens list
  54. */
  55. function tokenByIndex(uint256 index) public view returns (uint256) {
  56. require(index < totalSupply());
  57. return _allTokens[index];
  58. }
  59. /**
  60. * @dev Internal function to add a token ID to the list of a given address
  61. * This function is internal due to language limitations, see the note in ERC721.sol.
  62. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event.
  63. * @param to address representing the new owner of the given token ID
  64. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  65. */
  66. function _addTokenTo(address to, uint256 tokenId) internal {
  67. super._addTokenTo(to, tokenId);
  68. _addTokenToOwnerEnumeration(to, tokenId);
  69. }
  70. /**
  71. * @dev Internal function to remove a token ID from the list of a given address
  72. * This function is internal due to language limitations, see the note in ERC721.sol.
  73. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,
  74. * and doesn't clear approvals.
  75. * @param from address representing the previous owner of the given token ID
  76. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  77. */
  78. function _removeTokenFrom(address from, uint256 tokenId) internal {
  79. super._removeTokenFrom(from, tokenId);
  80. _removeTokenFromOwnerEnumeration(from, tokenId);
  81. // Since the token is being destroyed, we also clear its index
  82. // TODO(nventuro): 0 is still a valid index, so arguably this isnt really helpful, remove?
  83. _ownedTokensIndex[tokenId] = 0;
  84. }
  85. /**
  86. * @dev Internal function to transfer ownership of a given token ID to another address.
  87. * As opposed to transferFrom, this imposes no restrictions on msg.sender.
  88. * @param from current owner of the token
  89. * @param to address to receive the ownership of the given token ID
  90. * @param tokenId uint256 ID of the token to be transferred
  91. */
  92. function _transferFrom(address from, address to, uint256 tokenId) internal {
  93. super._transferFrom(from, to, tokenId);
  94. _removeTokenFromOwnerEnumeration(from, tokenId);
  95. _addTokenToOwnerEnumeration(to, tokenId);
  96. }
  97. /**
  98. * @dev Internal function to mint a new token
  99. * Reverts if the given token ID already exists
  100. * @param to address the beneficiary that will own the minted token
  101. * @param tokenId uint256 ID of the token to be minted
  102. */
  103. function _mint(address to, uint256 tokenId) internal {
  104. super._mint(to, tokenId);
  105. _allTokensIndex[tokenId] = _allTokens.length;
  106. _allTokens.push(tokenId);
  107. }
  108. /**
  109. * @dev Internal function to burn a specific token
  110. * Reverts if the token does not exist
  111. * Deprecated, use _burn(uint256) instead
  112. * @param owner owner of the token to burn
  113. * @param tokenId uint256 ID of the token being burned
  114. */
  115. function _burn(address owner, uint256 tokenId) internal {
  116. super._burn(owner, tokenId);
  117. // Reorg all tokens array
  118. uint256 tokenIndex = _allTokensIndex[tokenId];
  119. uint256 lastTokenIndex = _allTokens.length.sub(1);
  120. uint256 lastToken = _allTokens[lastTokenIndex];
  121. _allTokens[tokenIndex] = lastToken;
  122. _allTokens[lastTokenIndex] = 0;
  123. _allTokens.length--;
  124. _allTokensIndex[tokenId] = 0;
  125. _allTokensIndex[lastToken] = tokenIndex;
  126. }
  127. /**
  128. * @dev Gets the list of token IDs of the requested owner
  129. * @param owner address owning the tokens
  130. * @return uint256[] List of token IDs owned by the requested address
  131. */
  132. function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
  133. return _ownedTokens[owner];
  134. }
  135. /**
  136. * @dev Private function to add a token to this extension's ownership-tracking data structures.
  137. * @param to address representing the new owner of the given token ID
  138. * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
  139. */
  140. function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
  141. uint256 newOwnedTokensLength = _ownedTokens[to].push(tokenId);
  142. // No need to use SafeMath since the length after a push cannot be zero
  143. _ownedTokensIndex[tokenId] = newOwnedTokensLength - 1;
  144. }
  145. /**
  146. * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
  147. * while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for
  148. * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
  149. * This has O(1) time complexity, but alters the order of the _ownedTokens array.
  150. * @param from address representing the previous owner of the given token ID
  151. * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
  152. */
  153. function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
  154. // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
  155. // then delete the last slot (swap and pop).
  156. uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
  157. uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
  158. uint256 tokenIndex = _ownedTokensIndex[tokenId];
  159. _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
  160. _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
  161. // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going
  162. // to be zero. The swap operation will therefore have no effect, but the token _will_ be deleted during the
  163. // 'pop' operation.
  164. // This also deletes the contents at the last position of the array
  165. _ownedTokens[from].length--;
  166. // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occcupied by
  167. // lasTokenId).
  168. }
  169. }