ERC721.sol 17 KB

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