ERC721.sol 16 KB

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