ERC721.sol 22 KB

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