ERC721.sol 15 KB

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