ERC721.sol 13 KB

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