ERC721.sol 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/ERC721.sol)
  3. pragma solidity ^0.8.20;
  4. import {IERC721} from "./IERC721.sol";
  5. import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
  6. import {ERC721Utils} from "./utils/ERC721Utils.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[ERC-721] 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(uint256 tokenId => address) private _owners;
  23. mapping(address owner => uint256) private _balances;
  24. mapping(uint256 tokenId => address) private _tokenApprovals;
  25. mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;
  26. /**
  27. * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
  28. */
  29. constructor(string memory name_, string memory symbol_) {
  30. _name = name_;
  31. _symbol = symbol_;
  32. }
  33. /// @inheritdoc IERC165
  34. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
  35. return
  36. interfaceId == type(IERC721).interfaceId ||
  37. interfaceId == type(IERC721Metadata).interfaceId ||
  38. super.supportsInterface(interfaceId);
  39. }
  40. /// @inheritdoc IERC721
  41. function balanceOf(address owner) public view virtual returns (uint256) {
  42. if (owner == address(0)) {
  43. revert ERC721InvalidOwner(address(0));
  44. }
  45. return _balances[owner];
  46. }
  47. /// @inheritdoc IERC721
  48. function ownerOf(uint256 tokenId) public view virtual returns (address) {
  49. return _requireOwned(tokenId);
  50. }
  51. /// @inheritdoc IERC721Metadata
  52. function name() public view virtual returns (string memory) {
  53. return _name;
  54. }
  55. /// @inheritdoc IERC721Metadata
  56. function symbol() public view virtual returns (string memory) {
  57. return _symbol;
  58. }
  59. /// @inheritdoc IERC721Metadata
  60. function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
  61. _requireOwned(tokenId);
  62. string memory baseURI = _baseURI();
  63. return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
  64. }
  65. /**
  66. * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
  67. * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
  68. * by default, can be overridden in child contracts.
  69. */
  70. function _baseURI() internal view virtual returns (string memory) {
  71. return "";
  72. }
  73. /// @inheritdoc IERC721
  74. function approve(address to, uint256 tokenId) public virtual {
  75. _approve(to, tokenId, _msgSender());
  76. }
  77. /// @inheritdoc IERC721
  78. function getApproved(uint256 tokenId) public view virtual returns (address) {
  79. _requireOwned(tokenId);
  80. return _getApproved(tokenId);
  81. }
  82. /// @inheritdoc IERC721
  83. function setApprovalForAll(address operator, bool approved) public virtual {
  84. _setApprovalForAll(_msgSender(), operator, approved);
  85. }
  86. /// @inheritdoc IERC721
  87. function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
  88. return _operatorApprovals[owner][operator];
  89. }
  90. /// @inheritdoc IERC721
  91. function transferFrom(address from, address to, uint256 tokenId) public virtual {
  92. if (to == address(0)) {
  93. revert ERC721InvalidReceiver(address(0));
  94. }
  95. // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
  96. // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
  97. address previousOwner = _update(to, tokenId, _msgSender());
  98. if (previousOwner != from) {
  99. revert ERC721IncorrectOwner(from, tokenId, previousOwner);
  100. }
  101. }
  102. /// @inheritdoc IERC721
  103. function safeTransferFrom(address from, address to, uint256 tokenId) public {
  104. safeTransferFrom(from, to, tokenId, "");
  105. }
  106. /// @inheritdoc IERC721
  107. function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
  108. transferFrom(from, to, tokenId);
  109. ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
  110. }
  111. /**
  112. * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
  113. *
  114. * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
  115. * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
  116. * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
  117. * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
  118. */
  119. function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
  120. return _owners[tokenId];
  121. }
  122. /**
  123. * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
  124. */
  125. function _getApproved(uint256 tokenId) internal view virtual returns (address) {
  126. return _tokenApprovals[tokenId];
  127. }
  128. /**
  129. * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
  130. * particular (ignoring whether it is owned by `owner`).
  131. *
  132. * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
  133. * assumption.
  134. */
  135. function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
  136. return
  137. spender != address(0) &&
  138. (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
  139. }
  140. /**
  141. * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
  142. * Reverts if:
  143. * - `spender` does not have approval from `owner` for `tokenId`.
  144. * - `spender` does not have approval to manage all of `owner`'s assets.
  145. *
  146. * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
  147. * assumption.
  148. */
  149. function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
  150. if (!_isAuthorized(owner, spender, tokenId)) {
  151. if (owner == address(0)) {
  152. revert ERC721NonexistentToken(tokenId);
  153. } else {
  154. revert ERC721InsufficientApproval(spender, tokenId);
  155. }
  156. }
  157. }
  158. /**
  159. * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
  160. *
  161. * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
  162. * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
  163. *
  164. * WARNING: Increasing an account's balance using this function tends to be paired with an override of the
  165. * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
  166. * remain consistent with one another.
  167. */
  168. function _increaseBalance(address account, uint128 value) internal virtual {
  169. unchecked {
  170. _balances[account] += value;
  171. }
  172. }
  173. /**
  174. * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
  175. * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
  176. *
  177. * The `auth` argument is optional. If the value passed is non 0, then this function will check that
  178. * `auth` is either the owner of the token, or approved to operate on the token (by the owner).
  179. *
  180. * Emits a {Transfer} event.
  181. *
  182. * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
  183. */
  184. function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
  185. address from = _ownerOf(tokenId);
  186. // Perform (optional) operator check
  187. if (auth != address(0)) {
  188. _checkAuthorized(from, auth, tokenId);
  189. }
  190. // Execute the update
  191. if (from != address(0)) {
  192. // Clear approval. No need to re-authorize or emit the Approval event
  193. _approve(address(0), tokenId, address(0), false);
  194. unchecked {
  195. _balances[from] -= 1;
  196. }
  197. }
  198. if (to != address(0)) {
  199. unchecked {
  200. _balances[to] += 1;
  201. }
  202. }
  203. _owners[tokenId] = to;
  204. emit Transfer(from, to, tokenId);
  205. return from;
  206. }
  207. /**
  208. * @dev Mints `tokenId` and transfers it to `to`.
  209. *
  210. * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
  211. *
  212. * Requirements:
  213. *
  214. * - `tokenId` must not exist.
  215. * - `to` cannot be the zero address.
  216. *
  217. * Emits a {Transfer} event.
  218. */
  219. function _mint(address to, uint256 tokenId) internal {
  220. if (to == address(0)) {
  221. revert ERC721InvalidReceiver(address(0));
  222. }
  223. address previousOwner = _update(to, tokenId, address(0));
  224. if (previousOwner != address(0)) {
  225. revert ERC721InvalidSender(address(0));
  226. }
  227. }
  228. /**
  229. * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
  230. *
  231. * Requirements:
  232. *
  233. * - `tokenId` must not exist.
  234. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  235. *
  236. * Emits a {Transfer} event.
  237. */
  238. function _safeMint(address to, uint256 tokenId) internal {
  239. _safeMint(to, tokenId, "");
  240. }
  241. /**
  242. * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
  243. * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
  244. */
  245. function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
  246. _mint(to, tokenId);
  247. ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
  248. }
  249. /**
  250. * @dev Destroys `tokenId`.
  251. * The approval is cleared when the token is burned.
  252. * This is an internal function that does not check if the sender is authorized to operate on the token.
  253. *
  254. * Requirements:
  255. *
  256. * - `tokenId` must exist.
  257. *
  258. * Emits a {Transfer} event.
  259. */
  260. function _burn(uint256 tokenId) internal {
  261. address previousOwner = _update(address(0), tokenId, address(0));
  262. if (previousOwner == address(0)) {
  263. revert ERC721NonexistentToken(tokenId);
  264. }
  265. }
  266. /**
  267. * @dev Transfers `tokenId` from `from` to `to`.
  268. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
  269. *
  270. * Requirements:
  271. *
  272. * - `to` cannot be the zero address.
  273. * - `tokenId` token must be owned by `from`.
  274. *
  275. * Emits a {Transfer} event.
  276. */
  277. function _transfer(address from, address to, uint256 tokenId) internal {
  278. if (to == address(0)) {
  279. revert ERC721InvalidReceiver(address(0));
  280. }
  281. address previousOwner = _update(to, tokenId, address(0));
  282. if (previousOwner == address(0)) {
  283. revert ERC721NonexistentToken(tokenId);
  284. } else if (previousOwner != from) {
  285. revert ERC721IncorrectOwner(from, tokenId, previousOwner);
  286. }
  287. }
  288. /**
  289. * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
  290. * are aware of the ERC-721 standard to prevent tokens from being forever locked.
  291. *
  292. * `data` is additional data, it has no specified format and it is sent in call to `to`.
  293. *
  294. * This internal function is like {safeTransferFrom} in the sense that it invokes
  295. * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
  296. * implement alternative mechanisms to perform token transfer, such as signature-based.
  297. *
  298. * Requirements:
  299. *
  300. * - `tokenId` token must exist and be owned by `from`.
  301. * - `to` cannot be the zero address.
  302. * - `from` cannot be the zero address.
  303. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  304. *
  305. * Emits a {Transfer} event.
  306. */
  307. function _safeTransfer(address from, address to, uint256 tokenId) internal {
  308. _safeTransfer(from, to, tokenId, "");
  309. }
  310. /**
  311. * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
  312. * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
  313. */
  314. function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
  315. _transfer(from, to, tokenId);
  316. ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
  317. }
  318. /**
  319. * @dev Approve `to` to operate on `tokenId`
  320. *
  321. * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
  322. * either the owner of the token, or approved to operate on all tokens held by this owner.
  323. *
  324. * Emits an {Approval} event.
  325. *
  326. * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
  327. */
  328. function _approve(address to, uint256 tokenId, address auth) internal {
  329. _approve(to, tokenId, auth, true);
  330. }
  331. /**
  332. * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
  333. * emitted in the context of transfers.
  334. */
  335. function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
  336. // Avoid reading the owner unless necessary
  337. if (emitEvent || auth != address(0)) {
  338. address owner = _requireOwned(tokenId);
  339. // We do not use _isAuthorized because single-token approvals should not be able to call approve
  340. if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
  341. revert ERC721InvalidApprover(auth);
  342. }
  343. if (emitEvent) {
  344. emit Approval(owner, to, tokenId);
  345. }
  346. }
  347. _tokenApprovals[tokenId] = to;
  348. }
  349. /**
  350. * @dev Approve `operator` to operate on all of `owner` tokens
  351. *
  352. * Requirements:
  353. * - operator can't be the address zero.
  354. *
  355. * Emits an {ApprovalForAll} event.
  356. */
  357. function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
  358. if (operator == address(0)) {
  359. revert ERC721InvalidOperator(operator);
  360. }
  361. _operatorApprovals[owner][operator] = approved;
  362. emit ApprovalForAll(owner, operator, approved);
  363. }
  364. /**
  365. * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
  366. * Returns the owner.
  367. *
  368. * Overrides to ownership logic should be done to {_ownerOf}.
  369. */
  370. function _requireOwned(uint256 tokenId) internal view returns (address) {
  371. address owner = _ownerOf(tokenId);
  372. if (owner == address(0)) {
  373. revert ERC721NonexistentToken(tokenId);
  374. }
  375. return owner;
  376. }
  377. }