ERC721.sol 17 KB

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