ERC721.sol 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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(
  125. address from,
  126. address to,
  127. uint256 tokenId
  128. ) public virtual override {
  129. //solhint-disable-next-line max-line-length
  130. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
  131. _transfer(from, to, tokenId);
  132. }
  133. /**
  134. * @dev See {IERC721-safeTransferFrom}.
  135. */
  136. function safeTransferFrom(
  137. address from,
  138. address to,
  139. uint256 tokenId
  140. ) public virtual override {
  141. safeTransferFrom(from, to, tokenId, "");
  142. }
  143. /**
  144. * @dev See {IERC721-safeTransferFrom}.
  145. */
  146. function safeTransferFrom(
  147. address from,
  148. address to,
  149. uint256 tokenId,
  150. bytes memory data
  151. ) public virtual override {
  152. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
  153. _safeTransfer(from, to, tokenId, data);
  154. }
  155. /**
  156. * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
  157. * are aware of the ERC721 protocol to prevent tokens from being forever locked.
  158. *
  159. * `data` is additional data, it has no specified format and it is sent in call to `to`.
  160. *
  161. * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
  162. * implement alternative mechanisms to perform token transfer, such as signature-based.
  163. *
  164. * Requirements:
  165. *
  166. * - `from` cannot be the zero address.
  167. * - `to` cannot be the zero address.
  168. * - `tokenId` token must exist and be owned by `from`.
  169. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  170. *
  171. * Emits a {Transfer} event.
  172. */
  173. function _safeTransfer(
  174. address from,
  175. address to,
  176. uint256 tokenId,
  177. bytes memory data
  178. ) internal virtual {
  179. _transfer(from, to, tokenId);
  180. require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
  181. }
  182. /**
  183. * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
  184. */
  185. function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
  186. return _owners[tokenId];
  187. }
  188. /**
  189. * @dev Returns whether `tokenId` exists.
  190. *
  191. * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
  192. *
  193. * Tokens start existing when they are minted (`_mint`),
  194. * and stop existing when they are burned (`_burn`).
  195. */
  196. function _exists(uint256 tokenId) internal view virtual returns (bool) {
  197. return _ownerOf(tokenId) != address(0);
  198. }
  199. /**
  200. * @dev Returns whether `spender` is allowed to manage `tokenId`.
  201. *
  202. * Requirements:
  203. *
  204. * - `tokenId` must exist.
  205. */
  206. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
  207. address owner = ERC721.ownerOf(tokenId);
  208. return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
  209. }
  210. /**
  211. * @dev Safely mints `tokenId` and transfers it to `to`.
  212. *
  213. * Requirements:
  214. *
  215. * - `tokenId` must not exist.
  216. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  217. *
  218. * Emits a {Transfer} event.
  219. */
  220. function _safeMint(address to, uint256 tokenId) internal virtual {
  221. _safeMint(to, tokenId, "");
  222. }
  223. /**
  224. * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
  225. * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
  226. */
  227. function _safeMint(
  228. address to,
  229. uint256 tokenId,
  230. bytes memory data
  231. ) internal virtual {
  232. _mint(to, tokenId);
  233. require(
  234. _checkOnERC721Received(address(0), to, tokenId, data),
  235. "ERC721: transfer to non ERC721Receiver implementer"
  236. );
  237. }
  238. /**
  239. * @dev Mints `tokenId` and transfers it to `to`.
  240. *
  241. * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
  242. *
  243. * Requirements:
  244. *
  245. * - `tokenId` must not exist.
  246. * - `to` cannot be the zero address.
  247. *
  248. * Emits a {Transfer} event.
  249. */
  250. function _mint(address to, uint256 tokenId) internal virtual {
  251. require(to != address(0), "ERC721: mint to the zero address");
  252. require(!_exists(tokenId), "ERC721: token already minted");
  253. _beforeTokenTransfer(address(0), to, tokenId, 1);
  254. // Check that tokenId was not minted by `_beforeTokenTransfer` hook
  255. require(!_exists(tokenId), "ERC721: token already minted");
  256. unchecked {
  257. // Will not overflow unless all 2**256 token ids are minted to the same owner.
  258. // Given that tokens are minted one by one, it is impossible in practice that
  259. // this ever happens. Might change if we allow batch minting.
  260. // The ERC fails to describe this case.
  261. _balances[to] += 1;
  262. }
  263. _owners[tokenId] = to;
  264. emit Transfer(address(0), to, tokenId);
  265. _afterTokenTransfer(address(0), to, tokenId, 1);
  266. }
  267. /**
  268. * @dev Destroys `tokenId`.
  269. * The approval is cleared when the token is burned.
  270. * This is an internal function that does not check if the sender is authorized to operate on the token.
  271. *
  272. * Requirements:
  273. *
  274. * - `tokenId` must exist.
  275. *
  276. * Emits a {Transfer} event.
  277. */
  278. function _burn(uint256 tokenId) internal virtual {
  279. address owner = ERC721.ownerOf(tokenId);
  280. _beforeTokenTransfer(owner, address(0), tokenId, 1);
  281. // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
  282. owner = ERC721.ownerOf(tokenId);
  283. // Clear approvals
  284. delete _tokenApprovals[tokenId];
  285. unchecked {
  286. // Cannot overflow, as that would require more tokens to be burned/transferred
  287. // out than the owner initially received through minting and transferring in.
  288. _balances[owner] -= 1;
  289. }
  290. delete _owners[tokenId];
  291. emit Transfer(owner, address(0), tokenId);
  292. _afterTokenTransfer(owner, address(0), tokenId, 1);
  293. }
  294. /**
  295. * @dev Transfers `tokenId` from `from` to `to`.
  296. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
  297. *
  298. * Requirements:
  299. *
  300. * - `to` cannot be the zero address.
  301. * - `tokenId` token must be owned by `from`.
  302. *
  303. * Emits a {Transfer} event.
  304. */
  305. function _transfer(
  306. address from,
  307. address to,
  308. uint256 tokenId
  309. ) internal virtual {
  310. require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
  311. require(to != address(0), "ERC721: transfer to the zero address");
  312. _beforeTokenTransfer(from, to, tokenId, 1);
  313. // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
  314. require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
  315. // Clear approvals from the previous owner
  316. delete _tokenApprovals[tokenId];
  317. unchecked {
  318. // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
  319. // `from`'s balance is the number of token held, which is at least one before the current
  320. // transfer.
  321. // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
  322. // all 2**256 token ids to be minted, which in practice is impossible.
  323. _balances[from] -= 1;
  324. _balances[to] += 1;
  325. }
  326. _owners[tokenId] = to;
  327. emit Transfer(from, to, tokenId);
  328. _afterTokenTransfer(from, to, tokenId, 1);
  329. }
  330. /**
  331. * @dev Approve `to` to operate on `tokenId`
  332. *
  333. * Emits an {Approval} event.
  334. */
  335. function _approve(address to, uint256 tokenId) internal virtual {
  336. _tokenApprovals[tokenId] = to;
  337. emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
  338. }
  339. /**
  340. * @dev Approve `operator` to operate on all of `owner` tokens
  341. *
  342. * Emits an {ApprovalForAll} event.
  343. */
  344. function _setApprovalForAll(
  345. address owner,
  346. address operator,
  347. bool approved
  348. ) internal virtual {
  349. require(owner != operator, "ERC721: approve to caller");
  350. _operatorApprovals[owner][operator] = approved;
  351. emit ApprovalForAll(owner, operator, approved);
  352. }
  353. /**
  354. * @dev Reverts if the `tokenId` has not been minted yet.
  355. */
  356. function _requireMinted(uint256 tokenId) internal view virtual {
  357. require(_exists(tokenId), "ERC721: invalid token ID");
  358. }
  359. /**
  360. * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
  361. * The call is not executed if the target address is not a contract.
  362. *
  363. * @param from address representing the previous owner of the given token ID
  364. * @param to target address that will receive the tokens
  365. * @param tokenId uint256 ID of the token to be transferred
  366. * @param data bytes optional data to send along with the call
  367. * @return bool whether the call correctly returned the expected magic value
  368. */
  369. function _checkOnERC721Received(
  370. address from,
  371. address to,
  372. uint256 tokenId,
  373. bytes memory data
  374. ) private returns (bool) {
  375. if (to.isContract()) {
  376. try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
  377. return retval == IERC721Receiver.onERC721Received.selector;
  378. } catch (bytes memory reason) {
  379. if (reason.length == 0) {
  380. revert("ERC721: transfer to non ERC721Receiver implementer");
  381. } else {
  382. /// @solidity memory-safe-assembly
  383. assembly {
  384. revert(add(32, reason), mload(reason))
  385. }
  386. }
  387. }
  388. } else {
  389. return true;
  390. }
  391. }
  392. /**
  393. * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
  394. * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
  395. *
  396. * Calling conditions:
  397. *
  398. * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
  399. * - When `from` is zero, the tokens will be minted for `to`.
  400. * - When `to` is zero, ``from``'s tokens will be burned.
  401. * - `from` and `to` are never both zero.
  402. * - `batchSize` is non-zero.
  403. *
  404. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  405. */
  406. function _beforeTokenTransfer(
  407. address from,
  408. address to,
  409. uint256, /* firstTokenId */
  410. uint256 batchSize
  411. ) internal virtual {
  412. if (batchSize > 1) {
  413. if (from != address(0)) {
  414. _balances[from] -= batchSize;
  415. }
  416. if (to != address(0)) {
  417. _balances[to] += batchSize;
  418. }
  419. }
  420. }
  421. /**
  422. * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
  423. * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
  424. *
  425. * Calling conditions:
  426. *
  427. * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
  428. * - When `from` is zero, the tokens were minted for `to`.
  429. * - When `to` is zero, ``from``'s tokens were burned.
  430. * - `from` and `to` are never both zero.
  431. * - `batchSize` is non-zero.
  432. *
  433. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  434. */
  435. function _afterTokenTransfer(
  436. address from,
  437. address to,
  438. uint256 firstTokenId,
  439. uint256 batchSize
  440. ) internal virtual {}
  441. }