ERC721.sol 17 KB

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