Unverified Commit 09734e80 by Hadrien Croubois Committed by GitHub

Remove enumerable from ERC721 and add an ERC721Enumerable extension (#2511)

Co-authored-by: Francisco Giordano <frangio.1@gmail.com>
parent 7d20d0e2
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
* `GSN`: Deprecate GSNv1 support in favor of upcomming support for GSNv2. ([#2521](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2521)) * `GSN`: Deprecate GSNv1 support in favor of upcomming support for GSNv2. ([#2521](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2521))
* `ERC165`: Remove uses of storage in the base ERC165 implementation. ERC165 based contracts now use storage-less virtual functions. Old behaviour remains available in the `ERC165Storage` extension. ([#2505](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2505)) * `ERC165`: Remove uses of storage in the base ERC165 implementation. ERC165 based contracts now use storage-less virtual functions. Old behaviour remains available in the `ERC165Storage` extension. ([#2505](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2505))
* `Initializable`: Make initializer check stricter during construction. ([#2531](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2531)) * `Initializable`: Make initializer check stricter during construction. ([#2531](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2531))
* `ERC721`: remove enumerability of tokens from the base implementation. This feature is now provided separately through the `ERC721Enumerable` extension. ([#2511](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2511))
## 3.4.0 (2021-02-02) ## 3.4.0 (2021-02-02)
......
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/ERC721Enumerable.sol";
/**
* @title ERC721Mock
* This mock just provides a public safeMint, mint, and burn functions for testing purposes
*/
contract ERC721EnumerableMock is ERC721Enumerable {
string private _baseTokenURI;
constructor (string memory name, string memory symbol) ERC721(name, symbol) { }
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata newBaseTokenURI) public {
_baseTokenURI = newBaseTokenURI;
}
function baseURI() public view returns (string memory) {
return _baseURI();
}
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
function safeMint(address to, uint256 tokenId) public {
_safeMint(to, tokenId);
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public {
_safeMint(to, tokenId, _data);
}
function burn(uint256 tokenId) public {
_burn(tokenId);
}
}
...@@ -9,18 +9,24 @@ import "../token/ERC721/ERC721.sol"; ...@@ -9,18 +9,24 @@ import "../token/ERC721/ERC721.sol";
* This mock just provides a public safeMint, mint, and burn functions for testing purposes * This mock just provides a public safeMint, mint, and burn functions for testing purposes
*/ */
contract ERC721Mock is ERC721 { contract ERC721Mock is ERC721 {
string private _baseTokenURI;
constructor (string memory name, string memory symbol) ERC721(name, symbol) { } constructor (string memory name, string memory symbol) ERC721(name, symbol) { }
function exists(uint256 tokenId) public view returns (bool) { function _baseURI() internal view virtual override returns (string memory) {
return _exists(tokenId); return _baseTokenURI;
} }
function setTokenURI(uint256 tokenId, string memory uri) public { function setBaseURI(string calldata newBaseTokenURI) public {
_setTokenURI(tokenId, uri); _baseTokenURI = newBaseTokenURI;
} }
function setBaseURI(string memory baseURI) public { function baseURI() public view returns (string memory) {
_setBaseURI(baseURI); return _baseURI();
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
} }
function mint(address to, uint256 tokenId) public { function mint(address to, uint256 tokenId) public {
......
...@@ -6,6 +6,7 @@ import "../access/AccessControl.sol"; ...@@ -6,6 +6,7 @@ import "../access/AccessControl.sol";
import "../utils/Context.sol"; import "../utils/Context.sol";
import "../utils/Counters.sol"; import "../utils/Counters.sol";
import "../token/ERC721/ERC721.sol"; import "../token/ERC721/ERC721.sol";
import "../token/ERC721/ERC721Enumerable.sol";
import "../token/ERC721/ERC721Burnable.sol"; import "../token/ERC721/ERC721Burnable.sol";
import "../token/ERC721/ERC721Pausable.sol"; import "../token/ERC721/ERC721Pausable.sol";
...@@ -24,7 +25,7 @@ import "../token/ERC721/ERC721Pausable.sol"; ...@@ -24,7 +25,7 @@ import "../token/ERC721/ERC721Pausable.sol";
* roles, as well as the default admin role, which will let it grant both minter * roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts. * and pauser roles to other accounts.
*/ */
contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnable, ERC721Pausable { contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Enumerable, ERC721Burnable, ERC721Pausable {
using Counters for Counters.Counter; using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
...@@ -32,6 +33,8 @@ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnabl ...@@ -32,6 +33,8 @@ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnabl
Counters.Counter private _tokenIdTracker; Counters.Counter private _tokenIdTracker;
string private _baseTokenURI;
/** /**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract. * account that deploys the contract.
...@@ -39,13 +42,17 @@ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnabl ...@@ -39,13 +42,17 @@ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnabl
* Token URIs will be autogenerated based on `baseURI` and their token IDs. * Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}. * See {ERC721-tokenURI}.
*/ */
constructor(string memory name, string memory symbol, string memory baseURI) ERC721(name, symbol) { constructor(string memory name, string memory symbol, string memory baseTokenURI) ERC721(name, symbol) {
_baseTokenURI = baseTokenURI;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender());
}
_setBaseURI(baseURI); function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
} }
/** /**
...@@ -96,7 +103,14 @@ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnabl ...@@ -96,7 +103,14 @@ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnabl
_unpause(); _unpause();
} }
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) { function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId); super._beforeTokenTransfer(from, to, tokenId);
} }
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
} }
...@@ -5,47 +5,37 @@ pragma solidity ^0.8.0; ...@@ -5,47 +5,37 @@ pragma solidity ^0.8.0;
import "../../utils/Context.sol"; import "../../utils/Context.sol";
import "./IERC721.sol"; import "./IERC721.sol";
import "./IERC721Metadata.sol"; import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol"; import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol"; import "../../introspection/ERC165.sol";
import "../../utils/Address.sol"; import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol"; import "../../utils/Strings.sol";
/** /**
* @title ERC721 Non-Fungible Token Standard basic implementation * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* @dev see https://eips.ethereum.org/EIPS/eip-721 * the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/ */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address; using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256; using Strings for uint256;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name // Token name
string private _name; string private _name;
// Token symbol // Token symbol
string private _symbol; string private _symbol;
// Optional mapping for token URIs // Mapping from token ID to owner address
mapping (uint256 => string) private _tokenURIs; mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Base URI // Mapping from token ID to approved address
string private _baseURI; mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/** /**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
...@@ -61,7 +51,6 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -61,7 +51,6 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Metadata).interfaceId
|| interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId); || super.supportsInterface(interfaceId);
} }
...@@ -70,14 +59,16 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -70,14 +59,16 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
*/ */
function balanceOf(address owner) public view virtual override returns (uint256) { function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address"); require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length(); return _balances[owner];
} }
/** /**
* @dev See {IERC721-ownerOf}. * @dev See {IERC721-ownerOf}.
*/ */
function ownerOf(uint256 tokenId) public view virtual override returns (address) { function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
} }
/** /**
...@@ -100,51 +91,18 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -100,51 +91,18 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId]; string memory baseURI = _baseURI();
string memory base = baseURI(); return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
// If there is no base URI, return the token URI. : '';
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
} }
/** /**
* @dev See {IERC721Enumerable-tokenByIndex}. * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/ */
function tokenByIndex(uint256 index) public view virtual override returns (uint256) { function _baseURI() internal view virtual returns (string memory) {
(uint256 tokenId, ) = _tokenOwners.at(index); return "";
return tokenId;
} }
/** /**
...@@ -244,7 +202,7 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -244,7 +202,7 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
* and stop existing when they are burned (`_burn`). * and stop existing when they are burned (`_burn`).
*/ */
function _exists(uint256 tokenId) internal view virtual returns (bool) { function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId); return _owners[tokenId] != address(0);
} }
/** /**
...@@ -301,9 +259,8 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -301,9 +259,8 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
_beforeTokenTransfer(address(0), to, tokenId); _beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId); _balances[to] += 1;
_owners[tokenId] = to;
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId); emit Transfer(address(0), to, tokenId);
} }
...@@ -319,21 +276,15 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -319,21 +276,15 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function _burn(uint256 tokenId) internal virtual { function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId); _beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals // Clear approvals
_approve(address(0), tokenId); _approve(address(0), tokenId);
// Clear metadata (if any) _balances[owner] -= 1;
if (bytes(_tokenURIs[tokenId]).length != 0) { delete _owners[tokenId];
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId); emit Transfer(owner, address(0), tokenId);
} }
...@@ -350,7 +301,7 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -350,7 +301,7 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
* Emits a {Transfer} event. * Emits a {Transfer} event.
*/ */
function _transfer(address from, address to, uint256 tokenId) internal virtual { function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address"); require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId); _beforeTokenTransfer(from, to, tokenId);
...@@ -358,33 +309,21 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -358,33 +309,21 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
// Clear approvals from the previous owner // Clear approvals from the previous owner
_approve(address(0), tokenId); _approve(address(0), tokenId);
_holderTokens[from].remove(tokenId); _balances[from] -= 1;
_holderTokens[to].add(tokenId); _balances[to] += 1;
_owners[tokenId] = to;
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId); emit Transfer(from, to, tokenId);
} }
/** /**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * @dev Approve `to` to operate on `tokenId`
* *
* Requirements: * Emits a {Approval} event.
*
* - `tokenId` must exist.
*/ */
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { function _approve(address to, uint256 tokenId) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenApprovals[tokenId] = to;
_tokenURIs[tokenId] = _tokenURI; emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
} }
/** /**
...@@ -418,11 +357,6 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable ...@@ -418,11 +357,6 @@ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable
} }
} }
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/** /**
* @dev Hook that is called before any token transfer. This includes minting * @dev Hook that is called before any token transfer. This includes minting
* and burning. * and burning.
......
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
...@@ -7,7 +7,7 @@ This set of interfaces, contracts, and utilities are all related to the https:// ...@@ -7,7 +7,7 @@ This set of interfaces, contracts, and utilities are all related to the https://
TIP: For a walk through on how to create an ERC721 token read our xref:ROOT:erc721.adoc[ERC721 guide]. TIP: For a walk through on how to create an ERC721 token read our xref:ROOT:erc721.adoc[ERC721 guide].
The EIP consists of three interfaces, found here as {IERC721}, {IERC721Metadata}, and {IERC721Enumerable}. Only the first one is required in a contract to be ERC721 compliant. However, all three are implemented in {ERC721}. The EIP consists of three interfaces, found here as {IERC721}, {IERC721Metadata}, and {IERC721Enumerable}. Only the first one is required in a contract to be ERC721 compliant. The core interface and the metadata extension are both implemented in {ERC721}. The enumerable extension is provided separately in {ERC721Enumerable}.
Additionally, {IERC721Receiver} can be used to prevent tokens from becoming forever locked in contracts. Imagine sending an in-game item to an exchange address that can't send it back!. When using <<IERC721-safeTransferFrom,`safeTransferFrom`>>, the token contract checks to see that the receiver is an {IERC721Receiver}, which implies that it knows how to handle {ERC721} tokens. If you're writing a contract that needs to receive {ERC721} tokens, you'll want to include this interface. Additionally, {IERC721Receiver} can be used to prevent tokens from becoming forever locked in contracts. Imagine sending an in-game item to an exchange address that can't send it back!. When using <<IERC721-safeTransferFrom,`safeTransferFrom`>>, the token contract checks to see that the receiver is an {IERC721Receiver}, which implies that it knows how to handle {ERC721} tokens. If you're writing a contract that needs to receive {ERC721} tokens, you'll want to include this interface.
...@@ -29,6 +29,8 @@ NOTE: This core set of contracts is designed to be unopinionated, allowing devel ...@@ -29,6 +29,8 @@ NOTE: This core set of contracts is designed to be unopinionated, allowing devel
{{ERC721}} {{ERC721}}
{{ERC721Enumerable}}
{{IERC721Receiver}} {{IERC721Receiver}}
== Extensions == Extensions
......
...@@ -27,10 +27,6 @@ contract('ERC721PresetMinterPauserAutoId', function (accounts) { ...@@ -27,10 +27,6 @@ contract('ERC721PresetMinterPauserAutoId', function (accounts) {
expect(await this.token.symbol()).to.equal(symbol); expect(await this.token.symbol()).to.equal(symbol);
}); });
it('token has correct base URI', async function () {
expect(await this.token.baseURI()).to.equal(baseURI);
});
it('deployer has the default admin role', async function () { it('deployer has the default admin role', async function () {
expect(await this.token.getRoleMemberCount(DEFAULT_ADMIN_ROLE)).to.be.bignumber.equal('1'); expect(await this.token.getRoleMemberCount(DEFAULT_ADMIN_ROLE)).to.be.bignumber.equal('1');
expect(await this.token.getRoleMember(DEFAULT_ADMIN_ROLE, 0)).to.equal(deployer); expect(await this.token.getRoleMember(DEFAULT_ADMIN_ROLE, 0)).to.equal(deployer);
......
const {
shouldBehaveLikeERC721,
shouldBehaveLikeERC721Metadata,
shouldBehaveLikeERC721Enumerable,
} = require('./ERC721.behavior');
const ERC721Mock = artifacts.require('ERC721EnumerableMock');
contract('ERC721Enumerable', function (accounts) {
const name = 'Non Fungible Token';
const symbol = 'NFT';
beforeEach(async function () {
this.token = await ERC721Mock.new(name, symbol);
});
shouldBehaveLikeERC721('ERC721', ...accounts);
shouldBehaveLikeERC721Metadata('ERC721', name, symbol, ...accounts);
shouldBehaveLikeERC721Enumerable('ERC721', ...accounts);
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment