ERC721.sol 16 KB

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