ERC721.sol 22 KB

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