ERC721.sol 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. pragma solidity ^0.6.0;
  2. import "../../GSN/Context.sol";
  3. import "./IERC721.sol";
  4. import "./IERC721Metadata.sol";
  5. import "./IERC721Enumerable.sol";
  6. import "./IERC721Receiver.sol";
  7. import "../../introspection/ERC165.sol";
  8. import "../../math/SafeMath.sol";
  9. import "../../utils/Address.sol";
  10. import "../../utils/EnumerableSet.sol";
  11. import "../../utils/EnumerableMap.sol";
  12. import "../../utils/Strings.sol";
  13. /**
  14. * @title ERC721 Non-Fungible Token Standard basic implementation
  15. * @dev see https://eips.ethereum.org/EIPS/eip-721
  16. */
  17. contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
  18. using SafeMath for uint256;
  19. using Address for address;
  20. using EnumerableSet for EnumerableSet.UintSet;
  21. using EnumerableMap for EnumerableMap.UintToAddressMap;
  22. // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
  23. // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
  24. bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
  25. // Mapping from holder address to their (enumerable) set of owned tokens
  26. mapping (address => EnumerableSet.UintSet) private _holderTokens;
  27. // Enumerable mapping from token ids to their owners
  28. EnumerableMap.UintToAddressMap private _tokenOwners;
  29. // Mapping from token ID to approved address
  30. mapping (uint256 => address) private _tokenApprovals;
  31. // Mapping from owner to operator approvals
  32. mapping (address => mapping (address => bool)) private _operatorApprovals;
  33. // Token name
  34. string private _name;
  35. // Token symbol
  36. string private _symbol;
  37. // Optional mapping for token URIs
  38. mapping(uint256 => string) private _tokenURIs;
  39. // Base URI
  40. string private _baseURI;
  41. /*
  42. * bytes4(keccak256('balanceOf(address)')) == 0x70a08231
  43. * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
  44. * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
  45. * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
  46. * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
  47. * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
  48. * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
  49. * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
  50. * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
  51. *
  52. * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
  53. * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
  54. */
  55. bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
  56. /*
  57. * bytes4(keccak256('name()')) == 0x06fdde03
  58. * bytes4(keccak256('symbol()')) == 0x95d89b41
  59. * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
  60. *
  61. * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
  62. */
  63. bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
  64. /*
  65. * bytes4(keccak256('totalSupply()')) == 0x18160ddd
  66. * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
  67. * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
  68. *
  69. * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
  70. */
  71. bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
  72. constructor (string memory name, string memory symbol) public {
  73. _name = name;
  74. _symbol = symbol;
  75. // register the supported interfaces to conform to ERC721 via ERC165
  76. _registerInterface(_INTERFACE_ID_ERC721);
  77. _registerInterface(_INTERFACE_ID_ERC721_METADATA);
  78. _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
  79. }
  80. /**
  81. * @dev Gets the balance of the specified address.
  82. * @param owner address to query the balance of
  83. * @return uint256 representing the amount owned by the passed address
  84. */
  85. function balanceOf(address owner) public view override returns (uint256) {
  86. require(owner != address(0), "ERC721: balance query for the zero address");
  87. return _holderTokens[owner].length();
  88. }
  89. /**
  90. * @dev Gets the owner of the specified token ID.
  91. * @param tokenId uint256 ID of the token to query the owner of
  92. * @return address currently marked as the owner of the given token ID
  93. */
  94. function ownerOf(uint256 tokenId) public view override returns (address) {
  95. return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
  96. }
  97. /**
  98. * @dev Gets the token name.
  99. * @return string representing the token name
  100. */
  101. function name() public view override returns (string memory) {
  102. return _name;
  103. }
  104. /**
  105. * @dev Gets the token symbol.
  106. * @return string representing the token symbol
  107. */
  108. function symbol() public view override returns (string memory) {
  109. return _symbol;
  110. }
  111. /**
  112. * @dev Returns the URI for a given token ID. May return an empty string.
  113. *
  114. * If no base URI was set (via {_setBaseURI}), return the token ID's URI.
  115. * If a base URI was set, it will be added as a prefix to the token ID's URI,
  116. * or to the token ID itself, if no URI is set for that token ID.
  117. *
  118. * Reverts if the token ID does not exist.
  119. */
  120. function tokenURI(uint256 tokenId) public view override returns (string memory) {
  121. require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
  122. string memory _tokenURI = _tokenURIs[tokenId];
  123. // If there is no base URI, return the token URI.
  124. if (bytes(_baseURI).length == 0) {
  125. return _tokenURI;
  126. }
  127. // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
  128. if (bytes(_tokenURI).length > 0) {
  129. return string(abi.encodePacked(_baseURI, _tokenURI));
  130. }
  131. // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
  132. return string(abi.encodePacked(_baseURI, Strings.fromUint256(tokenId)));
  133. }
  134. /**
  135. * @dev Returns the base URI set via {_setBaseURI}. This will be
  136. * automatically added as a prefix in {tokenURI} to each token's URI, or
  137. * to the token ID if no specific URI is set for that token ID.
  138. */
  139. function baseURI() public view returns (string memory) {
  140. return _baseURI;
  141. }
  142. /**
  143. * @dev Gets the token ID at a given index of the tokens list of the requested owner.
  144. * @param owner address owning the tokens list to be accessed
  145. * @param index uint256 representing the index to be accessed of the requested tokens list
  146. * @return uint256 token ID at the given index of the tokens list owned by the requested address
  147. */
  148. function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
  149. return _holderTokens[owner].at(index);
  150. }
  151. /**
  152. * @dev Gets the total amount of tokens stored by the contract.
  153. * @return uint256 representing the total amount of tokens
  154. */
  155. function totalSupply() public view override returns (uint256) {
  156. // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
  157. return _tokenOwners.length();
  158. }
  159. /**
  160. * @dev Gets the token ID at a given index of all the tokens in this contract
  161. * Reverts if the index is greater or equal to the total number of tokens.
  162. * @param index uint256 representing the index to be accessed of the tokens list
  163. * @return uint256 token ID at the given index of the tokens list
  164. */
  165. function tokenByIndex(uint256 index) public view override returns (uint256) {
  166. (uint256 tokenId, ) = _tokenOwners.at(index);
  167. return tokenId;
  168. }
  169. /**
  170. * @dev Approves another address to transfer the given token ID
  171. * The zero address indicates there is no approved address.
  172. * There can only be one approved address per token at a given time.
  173. * Can only be called by the token owner or an approved operator.
  174. * @param to address to be approved for the given token ID
  175. * @param tokenId uint256 ID of the token to be approved
  176. */
  177. function approve(address to, uint256 tokenId) public virtual override {
  178. address owner = ownerOf(tokenId);
  179. require(to != owner, "ERC721: approval to current owner");
  180. require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
  181. "ERC721: approve caller is not owner nor approved for all"
  182. );
  183. _approve(to, tokenId);
  184. }
  185. /**
  186. * @dev Gets the approved address for a token ID, or zero if no address set
  187. * Reverts if the token ID does not exist.
  188. * @param tokenId uint256 ID of the token to query the approval of
  189. * @return address currently approved for the given token ID
  190. */
  191. function getApproved(uint256 tokenId) public view override returns (address) {
  192. require(_exists(tokenId), "ERC721: approved query for nonexistent token");
  193. return _tokenApprovals[tokenId];
  194. }
  195. /**
  196. * @dev Sets or unsets the approval of a given operator
  197. * An operator is allowed to transfer all tokens of the sender on their behalf.
  198. * @param operator operator address to set the approval
  199. * @param approved representing the status of the approval to be set
  200. */
  201. function setApprovalForAll(address operator, bool approved) public virtual override {
  202. require(operator != _msgSender(), "ERC721: approve to caller");
  203. _operatorApprovals[_msgSender()][operator] = approved;
  204. emit ApprovalForAll(_msgSender(), operator, approved);
  205. }
  206. /**
  207. * @dev Tells whether an operator is approved by a given owner.
  208. * @param owner owner address which you want to query the approval of
  209. * @param operator operator address which you want to query the approval of
  210. * @return bool whether the given operator is approved by the given owner
  211. */
  212. function isApprovedForAll(address owner, address operator) public view override returns (bool) {
  213. return _operatorApprovals[owner][operator];
  214. }
  215. /**
  216. * @dev Transfers the ownership of a given token ID to another address.
  217. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
  218. * Requires the msg.sender to be the owner, approved, or operator.
  219. * @param from current owner of the token
  220. * @param to address to receive the ownership of the given token ID
  221. * @param tokenId uint256 ID of the token to be transferred
  222. */
  223. function transferFrom(address from, address to, uint256 tokenId) public virtual override {
  224. //solhint-disable-next-line max-line-length
  225. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
  226. _transfer(from, to, tokenId);
  227. }
  228. /**
  229. * @dev Safely transfers the ownership of a given token ID to another address
  230. * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
  231. * which is called upon a safe transfer, and return the magic value
  232. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  233. * the transfer is reverted.
  234. * Requires the msg.sender to be the owner, approved, or operator
  235. * @param from current owner of the token
  236. * @param to address to receive the ownership of the given token ID
  237. * @param tokenId uint256 ID of the token to be transferred
  238. */
  239. function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
  240. safeTransferFrom(from, to, tokenId, "");
  241. }
  242. /**
  243. * @dev Safely transfers the ownership of a given token ID to another address
  244. * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
  245. * which is called upon a safe transfer, and return the magic value
  246. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  247. * the transfer is reverted.
  248. * Requires the _msgSender() to be the owner, approved, or operator
  249. * @param from current owner of the token
  250. * @param to address to receive the ownership of the given token ID
  251. * @param tokenId uint256 ID of the token to be transferred
  252. * @param _data bytes data to send along with a safe transfer check
  253. */
  254. function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
  255. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
  256. _safeTransfer(from, to, tokenId, _data);
  257. }
  258. /**
  259. * @dev Safely transfers the ownership of a given token ID to another address
  260. * If the target address is a contract, it must implement `onERC721Received`,
  261. * which is called upon a safe transfer, and return the magic value
  262. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  263. * the transfer is reverted.
  264. * Requires the msg.sender to be the owner, approved, or operator
  265. * @param from current owner of the token
  266. * @param to address to receive the ownership of the given token ID
  267. * @param tokenId uint256 ID of the token to be transferred
  268. * @param _data bytes data to send along with a safe transfer check
  269. */
  270. function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
  271. _transfer(from, to, tokenId);
  272. require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
  273. }
  274. /**
  275. * @dev Returns whether the specified token exists.
  276. * @param tokenId uint256 ID of the token to query the existence of
  277. * @return bool whether the token exists
  278. */
  279. function _exists(uint256 tokenId) internal view returns (bool) {
  280. return _tokenOwners.contains(tokenId);
  281. }
  282. /**
  283. * @dev Returns whether the given spender can transfer a given token ID.
  284. * @param spender address of the spender to query
  285. * @param tokenId uint256 ID of the token to be transferred
  286. * @return bool whether the msg.sender is approved for the given token ID,
  287. * is an operator of the owner, or is the owner of the token
  288. */
  289. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
  290. require(_exists(tokenId), "ERC721: operator query for nonexistent token");
  291. address owner = ownerOf(tokenId);
  292. return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
  293. }
  294. /**
  295. * @dev Internal function to safely mint a new token.
  296. * Reverts if the given token ID already exists.
  297. * If the target address is a contract, it must implement `onERC721Received`,
  298. * which is called upon a safe transfer, and return the magic value
  299. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  300. * the transfer is reverted.
  301. * @param to The address that will own the minted token
  302. * @param tokenId uint256 ID of the token to be minted
  303. */
  304. function _safeMint(address to, uint256 tokenId) internal virtual {
  305. _safeMint(to, tokenId, "");
  306. }
  307. /**
  308. * @dev Internal function to safely mint a new token.
  309. * Reverts if the given token ID already exists.
  310. * If the target address is a contract, it must implement `onERC721Received`,
  311. * which is called upon a safe transfer, and return the magic value
  312. * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
  313. * the transfer is reverted.
  314. * @param to The address that will own the minted token
  315. * @param tokenId uint256 ID of the token to be minted
  316. * @param _data bytes data to send along with a safe transfer check
  317. */
  318. function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
  319. _mint(to, tokenId);
  320. require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
  321. }
  322. /**
  323. * @dev Internal function to mint a new token.
  324. * Reverts if the given token ID already exists.
  325. * @param to The address that will own the minted token
  326. * @param tokenId uint256 ID of the token to be minted
  327. */
  328. function _mint(address to, uint256 tokenId) internal virtual {
  329. require(to != address(0), "ERC721: mint to the zero address");
  330. require(!_exists(tokenId), "ERC721: token already minted");
  331. _beforeTokenTransfer(address(0), to, tokenId);
  332. _holderTokens[to].add(tokenId);
  333. _tokenOwners.set(tokenId, to);
  334. emit Transfer(address(0), to, tokenId);
  335. }
  336. /**
  337. * @dev Internal function to burn a specific token.
  338. * Reverts if the token does not exist.
  339. * @param tokenId uint256 ID of the token being burned
  340. */
  341. function _burn(uint256 tokenId) internal virtual {
  342. address owner = ownerOf(tokenId);
  343. _beforeTokenTransfer(owner, address(0), tokenId);
  344. // Clear approvals
  345. _approve(address(0), tokenId);
  346. // Clear metadata (if any)
  347. if (bytes(_tokenURIs[tokenId]).length != 0) {
  348. delete _tokenURIs[tokenId];
  349. }
  350. _holderTokens[owner].remove(tokenId);
  351. _tokenOwners.remove(tokenId);
  352. emit Transfer(owner, address(0), tokenId);
  353. }
  354. /**
  355. * @dev Internal function to transfer ownership of a given token ID to another address.
  356. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
  357. * @param from current owner of the token
  358. * @param to address to receive the ownership of the given token ID
  359. * @param tokenId uint256 ID of the token to be transferred
  360. */
  361. function _transfer(address from, address to, uint256 tokenId) internal virtual {
  362. require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
  363. require(to != address(0), "ERC721: transfer to the zero address");
  364. _beforeTokenTransfer(from, to, tokenId);
  365. // Clear approvals from the previous owner
  366. _approve(address(0), tokenId);
  367. _holderTokens[from].remove(tokenId);
  368. _holderTokens[to].add(tokenId);
  369. _tokenOwners.set(tokenId, to);
  370. emit Transfer(from, to, tokenId);
  371. }
  372. /**
  373. * @dev Internal function to set the token URI for a given token.
  374. *
  375. * Reverts if the token ID does not exist.
  376. *
  377. * TIP: If all token IDs share a prefix (for example, if your URIs look like
  378. * `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
  379. * it and save gas.
  380. */
  381. function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
  382. require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
  383. _tokenURIs[tokenId] = _tokenURI;
  384. }
  385. /**
  386. * @dev Internal function to set the base URI for all token IDs. It is
  387. * automatically added as a prefix to the value returned in {tokenURI},
  388. * or to the token ID if {tokenURI} is empty.
  389. */
  390. function _setBaseURI(string memory baseURI_) internal virtual {
  391. _baseURI = baseURI_;
  392. }
  393. /**
  394. * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
  395. * The call is not executed if the target address is not a contract.
  396. *
  397. * @param from address representing the previous owner of the given token ID
  398. * @param to target address that will receive the tokens
  399. * @param tokenId uint256 ID of the token to be transferred
  400. * @param _data bytes optional data to send along with the call
  401. * @return bool whether the call correctly returned the expected magic value
  402. */
  403. function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
  404. private returns (bool)
  405. {
  406. if (!to.isContract()) {
  407. return true;
  408. }
  409. // solhint-disable-next-line avoid-low-level-calls
  410. (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
  411. IERC721Receiver(to).onERC721Received.selector,
  412. _msgSender(),
  413. from,
  414. tokenId,
  415. _data
  416. ));
  417. if (!success) {
  418. if (returndata.length > 0) {
  419. // solhint-disable-next-line no-inline-assembly
  420. assembly {
  421. let returndata_size := mload(returndata)
  422. revert(add(32, returndata), returndata_size)
  423. }
  424. } else {
  425. revert("ERC721: transfer to non ERC721Receiver implementer");
  426. }
  427. } else {
  428. bytes4 retval = abi.decode(returndata, (bytes4));
  429. return (retval == _ERC721_RECEIVED);
  430. }
  431. }
  432. function _approve(address to, uint256 tokenId) private {
  433. _tokenApprovals[tokenId] = to;
  434. emit Approval(ownerOf(tokenId), to, tokenId);
  435. }
  436. /**
  437. * @dev Hook that is called before any token transfer. This includes minting
  438. * and burning.
  439. *
  440. * Calling conditions:
  441. *
  442. * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be
  443. * transferred to `to`.
  444. * - when `from` is zero, `tokenId` will be minted for `to`.
  445. * - when `to` is zero, ``from``'s `tokenId` will be burned.
  446. * - `from` and `to` are never both zero.
  447. *
  448. * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks].
  449. */
  450. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
  451. }