ERC721.sol 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 ^ 0xe985e9c5 ^ 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. /**
  75. * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
  76. */
  77. constructor (string memory name, string memory symbol) public {
  78. _name = name;
  79. _symbol = symbol;
  80. // register the supported interfaces to conform to ERC721 via ERC165
  81. _registerInterface(_INTERFACE_ID_ERC721);
  82. _registerInterface(_INTERFACE_ID_ERC721_METADATA);
  83. _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
  84. }
  85. /**
  86. * @dev See {IERC721-balanceOf}.
  87. */
  88. function balanceOf(address owner) public view override returns (uint256) {
  89. require(owner != address(0), "ERC721: balance query for the zero address");
  90. return _holderTokens[owner].length();
  91. }
  92. /**
  93. * @dev See {IERC721-ownerOf}.
  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 See {IERC721Metadata-name}.
  100. */
  101. function name() public view override returns (string memory) {
  102. return _name;
  103. }
  104. /**
  105. * @dev See {IERC721Metadata-symbol}.
  106. */
  107. function symbol() public view override returns (string memory) {
  108. return _symbol;
  109. }
  110. /**
  111. * @dev See {IERC721Metadata-tokenURI}.
  112. */
  113. function tokenURI(uint256 tokenId) public view override returns (string memory) {
  114. require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
  115. string memory _tokenURI = _tokenURIs[tokenId];
  116. // If there is no base URI, return the token URI.
  117. if (bytes(_baseURI).length == 0) {
  118. return _tokenURI;
  119. }
  120. // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
  121. if (bytes(_tokenURI).length > 0) {
  122. return string(abi.encodePacked(_baseURI, _tokenURI));
  123. }
  124. // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
  125. return string(abi.encodePacked(_baseURI, tokenId.toString()));
  126. }
  127. /**
  128. * @dev Returns the base URI set via {_setBaseURI}. This will be
  129. * automatically added as a prefix in {tokenURI} to each token's URI, or
  130. * to the token ID if no specific URI is set for that token ID.
  131. */
  132. function baseURI() public view returns (string memory) {
  133. return _baseURI;
  134. }
  135. /**
  136. * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
  137. */
  138. function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
  139. return _holderTokens[owner].at(index);
  140. }
  141. /**
  142. * @dev See {IERC721Enumerable-totalSupply}.
  143. */
  144. function totalSupply() public view override returns (uint256) {
  145. // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
  146. return _tokenOwners.length();
  147. }
  148. /**
  149. * @dev See {IERC721Enumerable-tokenByIndex}.
  150. */
  151. function tokenByIndex(uint256 index) public view override returns (uint256) {
  152. (uint256 tokenId, ) = _tokenOwners.at(index);
  153. return tokenId;
  154. }
  155. /**
  156. * @dev See {IERC721-approve}.
  157. */
  158. function approve(address to, uint256 tokenId) public virtual override {
  159. address owner = ownerOf(tokenId);
  160. require(to != owner, "ERC721: approval to current owner");
  161. require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
  162. "ERC721: approve caller is not owner nor approved for all"
  163. );
  164. _approve(to, tokenId);
  165. }
  166. /**
  167. * @dev See {IERC721-getApproved}.
  168. */
  169. function getApproved(uint256 tokenId) public view override returns (address) {
  170. require(_exists(tokenId), "ERC721: approved query for nonexistent token");
  171. return _tokenApprovals[tokenId];
  172. }
  173. /**
  174. * @dev See {IERC721-setApprovalForAll}.
  175. */
  176. function setApprovalForAll(address operator, bool approved) public virtual override {
  177. require(operator != _msgSender(), "ERC721: approve to caller");
  178. _operatorApprovals[_msgSender()][operator] = approved;
  179. emit ApprovalForAll(_msgSender(), operator, approved);
  180. }
  181. /**
  182. * @dev See {IERC721-isApprovedForAll}.
  183. */
  184. function isApprovedForAll(address owner, address operator) public view override returns (bool) {
  185. return _operatorApprovals[owner][operator];
  186. }
  187. /**
  188. * @dev See {IERC721-transferFrom}.
  189. */
  190. function transferFrom(address from, address to, uint256 tokenId) public virtual override {
  191. //solhint-disable-next-line max-line-length
  192. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
  193. _transfer(from, to, tokenId);
  194. }
  195. /**
  196. * @dev See {IERC721-safeTransferFrom}.
  197. */
  198. function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
  199. safeTransferFrom(from, to, tokenId, "");
  200. }
  201. /**
  202. * @dev See {IERC721-safeTransferFrom}.
  203. */
  204. function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
  205. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
  206. _safeTransfer(from, to, tokenId, _data);
  207. }
  208. /**
  209. * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
  210. * are aware of the ERC721 protocol to prevent tokens from being forever locked.
  211. *
  212. * `_data` is additional data, it has no specified format and it is sent in call to `to`.
  213. *
  214. * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
  215. * implement alternative mechanisms to perform token transfer, such as signature-based.
  216. *
  217. * Requirements:
  218. *
  219. * - `from` cannot be the zero address.
  220. * - `to` cannot be the zero address.
  221. * - `tokenId` token must exist and be owned by `from`.
  222. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  223. *
  224. * Emits a {Transfer} event.
  225. */
  226. function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
  227. _transfer(from, to, tokenId);
  228. require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
  229. }
  230. /**
  231. * @dev Returns whether `tokenId` exists.
  232. *
  233. * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
  234. *
  235. * Tokens start existing when they are minted (`_mint`),
  236. * and stop existing when they are burned (`_burn`).
  237. */
  238. function _exists(uint256 tokenId) internal view returns (bool) {
  239. return _tokenOwners.contains(tokenId);
  240. }
  241. /**
  242. * @dev Returns whether `spender` is allowed to manage `tokenId`.
  243. *
  244. * Requirements:
  245. *
  246. * - `tokenId` must exist.
  247. */
  248. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
  249. require(_exists(tokenId), "ERC721: operator query for nonexistent token");
  250. address owner = ownerOf(tokenId);
  251. return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
  252. }
  253. /**
  254. * @dev Safely mints `tokenId` and transfers it to `to`.
  255. *
  256. * Requirements:
  257. d*
  258. * - `tokenId` must not exist.
  259. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  260. *
  261. * Emits a {Transfer} event.
  262. */
  263. function _safeMint(address to, uint256 tokenId) internal virtual {
  264. _safeMint(to, tokenId, "");
  265. }
  266. /**
  267. * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
  268. * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
  269. */
  270. function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
  271. _mint(to, tokenId);
  272. require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
  273. }
  274. /**
  275. * @dev Mints `tokenId` and transfers it to `to`.
  276. *
  277. * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
  278. *
  279. * Requirements:
  280. *
  281. * - `tokenId` must not exist.
  282. * - `to` cannot be the zero address.
  283. *
  284. * Emits a {Transfer} event.
  285. */
  286. function _mint(address to, uint256 tokenId) internal virtual {
  287. require(to != address(0), "ERC721: mint to the zero address");
  288. require(!_exists(tokenId), "ERC721: token already minted");
  289. _beforeTokenTransfer(address(0), to, tokenId);
  290. _holderTokens[to].add(tokenId);
  291. _tokenOwners.set(tokenId, to);
  292. emit Transfer(address(0), to, tokenId);
  293. }
  294. /**
  295. * @dev Destroys `tokenId`.
  296. * The approval is cleared when the token is burned.
  297. *
  298. * Requirements:
  299. *
  300. * - `tokenId` must exist.
  301. *
  302. * Emits a {Transfer} event.
  303. */
  304. function _burn(uint256 tokenId) internal virtual {
  305. address owner = ownerOf(tokenId);
  306. _beforeTokenTransfer(owner, address(0), tokenId);
  307. // Clear approvals
  308. _approve(address(0), tokenId);
  309. // Clear metadata (if any)
  310. if (bytes(_tokenURIs[tokenId]).length != 0) {
  311. delete _tokenURIs[tokenId];
  312. }
  313. _holderTokens[owner].remove(tokenId);
  314. _tokenOwners.remove(tokenId);
  315. emit Transfer(owner, address(0), tokenId);
  316. }
  317. /**
  318. * @dev Transfers `tokenId` from `from` to `to`.
  319. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
  320. *
  321. * Requirements:
  322. *
  323. * - `to` cannot be the zero address.
  324. * - `tokenId` token must be owned by `from`.
  325. *
  326. * Emits a {Transfer} event.
  327. */
  328. function _transfer(address from, address to, uint256 tokenId) internal virtual {
  329. require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
  330. require(to != address(0), "ERC721: transfer to the zero address");
  331. _beforeTokenTransfer(from, to, tokenId);
  332. // Clear approvals from the previous owner
  333. _approve(address(0), tokenId);
  334. _holderTokens[from].remove(tokenId);
  335. _holderTokens[to].add(tokenId);
  336. _tokenOwners.set(tokenId, to);
  337. emit Transfer(from, to, tokenId);
  338. }
  339. /**
  340. * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
  341. *
  342. * Requirements:
  343. *
  344. * - `tokenId` must exist.
  345. */
  346. function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
  347. require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
  348. _tokenURIs[tokenId] = _tokenURI;
  349. }
  350. /**
  351. * @dev Internal function to set the base URI for all token IDs. It is
  352. * automatically added as a prefix to the value returned in {tokenURI},
  353. * or to the token ID if {tokenURI} is empty.
  354. */
  355. function _setBaseURI(string memory baseURI_) internal virtual {
  356. _baseURI = baseURI_;
  357. }
  358. /**
  359. * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
  360. * The call is not executed if the target address is not a contract.
  361. *
  362. * @param from address representing the previous owner of the given token ID
  363. * @param to target address that will receive the tokens
  364. * @param tokenId uint256 ID of the token to be transferred
  365. * @param _data bytes optional data to send along with the call
  366. * @return bool whether the call correctly returned the expected magic value
  367. */
  368. function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
  369. private returns (bool)
  370. {
  371. if (!to.isContract()) {
  372. return true;
  373. }
  374. bytes memory returndata = to.functionCall(abi.encodeWithSelector(
  375. IERC721Receiver(to).onERC721Received.selector,
  376. _msgSender(),
  377. from,
  378. tokenId,
  379. _data
  380. ), "ERC721: transfer to non ERC721Receiver implementer");
  381. bytes4 retval = abi.decode(returndata, (bytes4));
  382. return (retval == _ERC721_RECEIVED);
  383. }
  384. function _approve(address to, uint256 tokenId) private {
  385. _tokenApprovals[tokenId] = to;
  386. emit Approval(ownerOf(tokenId), to, tokenId);
  387. }
  388. /**
  389. * @dev Hook that is called before any token transfer. This includes minting
  390. * and burning.
  391. *
  392. * Calling conditions:
  393. *
  394. * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
  395. * transferred to `to`.
  396. * - When `from` is zero, `tokenId` will be minted for `to`.
  397. * - When `to` is zero, ``from``'s `tokenId` will be burned.
  398. * - `from` cannot be the zero address.
  399. * - `to` cannot be the zero address.
  400. *
  401. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  402. */
  403. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
  404. }