ERC721.sol 15 KB

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