ERC721.sol 21 KB

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