123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492 |
- // SPDX-License-Identifier: MIT
- // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)
- pragma solidity ^0.8.19;
- import {IERC721} from "./IERC721.sol";
- import {IERC721Receiver} from "./IERC721Receiver.sol";
- import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
- import {Context} from "../../utils/Context.sol";
- import {Strings} from "../../utils/Strings.sol";
- import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
- import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";
- /**
- * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
- * the Metadata extension, but not including the Enumerable extension, which is available separately as
- * {ERC721Enumerable}.
- */
- abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
- using Strings for uint256;
- // Token name
- string private _name;
- // Token symbol
- string private _symbol;
- // Mapping from token ID to owner address
- mapping(uint256 => address) private _owners;
- // Mapping owner address to token count
- mapping(address => uint256) private _balances;
- // Mapping from token ID to approved address
- mapping(uint256 => address) private _tokenApprovals;
- // Mapping from owner to operator approvals
- mapping(address => mapping(address => bool)) private _operatorApprovals;
- /**
- * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
- */
- constructor(string memory name_, string memory symbol_) {
- _name = name_;
- _symbol = symbol_;
- }
- /**
- * @dev See {IERC165-supportsInterface}.
- */
- function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
- return
- interfaceId == type(IERC721).interfaceId ||
- interfaceId == type(IERC721Metadata).interfaceId ||
- super.supportsInterface(interfaceId);
- }
- /**
- * @dev See {IERC721-balanceOf}.
- */
- function balanceOf(address owner) public view virtual returns (uint256) {
- if (owner == address(0)) {
- revert ERC721InvalidOwner(address(0));
- }
- return _balances[owner];
- }
- /**
- * @dev See {IERC721-ownerOf}.
- */
- function ownerOf(uint256 tokenId) public view virtual returns (address) {
- address owner = _ownerOf(tokenId);
- if (owner == address(0)) {
- revert ERC721NonexistentToken(tokenId);
- }
- return owner;
- }
- /**
- * @dev See {IERC721Metadata-name}.
- */
- function name() public view virtual returns (string memory) {
- return _name;
- }
- /**
- * @dev See {IERC721Metadata-symbol}.
- */
- function symbol() public view virtual returns (string memory) {
- return _symbol;
- }
- /**
- * @dev See {IERC721Metadata-tokenURI}.
- */
- function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
- _requireMinted(tokenId);
- string memory baseURI = _baseURI();
- return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
- }
- /**
- * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
- * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
- * by default, can be overridden in child contracts.
- */
- function _baseURI() internal view virtual returns (string memory) {
- return "";
- }
- /**
- * @dev See {IERC721-approve}.
- */
- function approve(address to, uint256 tokenId) public virtual {
- address owner = ownerOf(tokenId);
- if (to == owner) {
- revert ERC721InvalidOperator(owner);
- }
- if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
- revert ERC721InvalidApprover(_msgSender());
- }
- _approve(to, tokenId);
- }
- /**
- * @dev See {IERC721-getApproved}.
- */
- function getApproved(uint256 tokenId) public view virtual returns (address) {
- _requireMinted(tokenId);
- return _tokenApprovals[tokenId];
- }
- /**
- * @dev See {IERC721-setApprovalForAll}.
- */
- function setApprovalForAll(address operator, bool approved) public virtual {
- _setApprovalForAll(_msgSender(), operator, approved);
- }
- /**
- * @dev See {IERC721-isApprovedForAll}.
- */
- function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
- return _operatorApprovals[owner][operator];
- }
- /**
- * @dev See {IERC721-transferFrom}.
- */
- function transferFrom(address from, address to, uint256 tokenId) public virtual {
- if (!_isApprovedOrOwner(_msgSender(), tokenId)) {
- revert ERC721InsufficientApproval(_msgSender(), tokenId);
- }
- _transfer(from, to, tokenId);
- }
- /**
- * @dev See {IERC721-safeTransferFrom}.
- */
- function safeTransferFrom(address from, address to, uint256 tokenId) public virtual {
- safeTransferFrom(from, to, tokenId, "");
- }
- /**
- * @dev See {IERC721-safeTransferFrom}.
- */
- function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
- if (!_isApprovedOrOwner(_msgSender(), tokenId)) {
- revert ERC721InsufficientApproval(_msgSender(), tokenId);
- }
- _safeTransfer(from, to, tokenId, data);
- }
- /**
- * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
- * are aware of the ERC721 protocol to prevent tokens from being forever locked.
- *
- * `data` is additional data, it has no specified format and it is sent in call to `to`.
- *
- * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
- * implement alternative mechanisms to perform token transfer, such as signature-based.
- *
- * Requirements:
- *
- * - `from` cannot be the zero address.
- * - `to` cannot be the zero address.
- * - `tokenId` token must exist and be owned by `from`.
- * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
- *
- * Emits a {Transfer} event.
- */
- function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
- _transfer(from, to, tokenId);
- if (!_checkOnERC721Received(from, to, tokenId, data)) {
- revert ERC721InvalidReceiver(to);
- }
- }
- /**
- * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
- */
- function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
- return _owners[tokenId];
- }
- /**
- * @dev Returns whether `tokenId` exists.
- *
- * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
- *
- * Tokens start existing when they are minted (`_mint`),
- * and stop existing when they are burned (`_burn`).
- */
- function _exists(uint256 tokenId) internal view virtual returns (bool) {
- return _ownerOf(tokenId) != address(0);
- }
- /**
- * @dev Returns whether `spender` is allowed to manage `tokenId`.
- *
- * Requirements:
- *
- * - `tokenId` must exist.
- */
- function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
- address owner = ownerOf(tokenId);
- return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
- }
- /**
- * @dev Safely mints `tokenId` and transfers it to `to`.
- *
- * Requirements:
- *
- * - `tokenId` must not exist.
- * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
- *
- * Emits a {Transfer} event.
- */
- function _safeMint(address to, uint256 tokenId) internal virtual {
- _safeMint(to, tokenId, "");
- }
- /**
- * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
- * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
- */
- function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
- _mint(to, tokenId);
- if (!_checkOnERC721Received(address(0), to, tokenId, data)) {
- revert ERC721InvalidReceiver(to);
- }
- }
- /**
- * @dev Mints `tokenId` and transfers it to `to`.
- *
- * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
- *
- * Requirements:
- *
- * - `tokenId` must not exist.
- * - `to` cannot be the zero address.
- *
- * Emits a {Transfer} event.
- */
- function _mint(address to, uint256 tokenId) internal virtual {
- if (to == address(0)) {
- revert ERC721InvalidReceiver(address(0));
- }
- if (_exists(tokenId)) {
- revert ERC721InvalidSender(address(0));
- }
- _beforeTokenTransfer(address(0), to, tokenId, 1);
- // Check that tokenId was not minted by `_beforeTokenTransfer` hook
- if (_exists(tokenId)) {
- revert ERC721InvalidSender(address(0));
- }
- unchecked {
- // Will not overflow unless all 2**256 token ids are minted to the same owner.
- // Given that tokens are minted one by one, it is impossible in practice that
- // this ever happens. Might change if we allow batch minting.
- // The ERC fails to describe this case.
- _balances[to] += 1;
- }
- _owners[tokenId] = to;
- emit Transfer(address(0), to, tokenId);
- _afterTokenTransfer(address(0), to, tokenId, 1);
- }
- /**
- * @dev Destroys `tokenId`.
- * The approval is cleared when the token is burned.
- * This is an internal function that does not check if the sender is authorized to operate on the token.
- *
- * Requirements:
- *
- * - `tokenId` must exist.
- *
- * Emits a {Transfer} event.
- */
- function _burn(uint256 tokenId) internal virtual {
- address owner = ownerOf(tokenId);
- _beforeTokenTransfer(owner, address(0), tokenId, 1);
- // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
- owner = ownerOf(tokenId);
- // Clear approvals
- delete _tokenApprovals[tokenId];
- // Decrease balance with checked arithmetic, because an `ownerOf` override may
- // invalidate the assumption that `_balances[from] >= 1`.
- _balances[owner] -= 1;
- delete _owners[tokenId];
- emit Transfer(owner, address(0), tokenId);
- _afterTokenTransfer(owner, address(0), tokenId, 1);
- }
- /**
- * @dev Transfers `tokenId` from `from` to `to`.
- * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
- *
- * Requirements:
- *
- * - `to` cannot be the zero address.
- * - `tokenId` token must be owned by `from`.
- *
- * Emits a {Transfer} event.
- */
- function _transfer(address from, address to, uint256 tokenId) internal virtual {
- address owner = ownerOf(tokenId);
- if (owner != from) {
- revert ERC721IncorrectOwner(from, tokenId, owner);
- }
- if (to == address(0)) {
- revert ERC721InvalidReceiver(address(0));
- }
- _beforeTokenTransfer(from, to, tokenId, 1);
- // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
- owner = ownerOf(tokenId);
- if (owner != from) {
- revert ERC721IncorrectOwner(from, tokenId, owner);
- }
- // Clear approvals from the previous owner
- delete _tokenApprovals[tokenId];
- // Decrease balance with checked arithmetic, because an `ownerOf` override may
- // invalidate the assumption that `_balances[from] >= 1`.
- _balances[from] -= 1;
- unchecked {
- // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
- // all 2**256 token ids to be minted, which in practice is impossible.
- _balances[to] += 1;
- }
- _owners[tokenId] = to;
- emit Transfer(from, to, tokenId);
- _afterTokenTransfer(from, to, tokenId, 1);
- }
- /**
- * @dev Approve `to` to operate on `tokenId`
- *
- * Emits an {Approval} event.
- */
- function _approve(address to, uint256 tokenId) internal virtual {
- _tokenApprovals[tokenId] = to;
- emit Approval(ownerOf(tokenId), to, tokenId);
- }
- /**
- * @dev Approve `operator` to operate on all of `owner` tokens
- *
- * Emits an {ApprovalForAll} event.
- */
- function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
- if (owner == operator) {
- revert ERC721InvalidOperator(owner);
- }
- _operatorApprovals[owner][operator] = approved;
- emit ApprovalForAll(owner, operator, approved);
- }
- /**
- * @dev Reverts if the `tokenId` has not been minted yet.
- */
- function _requireMinted(uint256 tokenId) internal view virtual {
- if (!_exists(tokenId)) {
- revert ERC721NonexistentToken(tokenId);
- }
- }
- /**
- * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address.
- * The call is not executed if the target address is not a contract.
- *
- * @param from address representing the previous owner of the given token ID
- * @param to target address that will receive the tokens
- * @param tokenId uint256 ID of the token to be transferred
- * @param data bytes optional data to send along with the call
- * @return bool whether the call correctly returned the expected magic value
- */
- function _checkOnERC721Received(
- address from,
- address to,
- uint256 tokenId,
- bytes memory data
- ) private returns (bool) {
- if (to.code.length > 0) {
- try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
- return retval == IERC721Receiver.onERC721Received.selector;
- } catch (bytes memory reason) {
- if (reason.length == 0) {
- revert ERC721InvalidReceiver(to);
- } else {
- /// @solidity memory-safe-assembly
- assembly {
- revert(add(32, reason), mload(reason))
- }
- }
- }
- } else {
- return true;
- }
- }
- /**
- * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
- * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
- *
- * Calling conditions:
- *
- * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
- * - When `from` is zero, the tokens will be minted for `to`.
- * - When `to` is zero, ``from``'s tokens will be burned.
- * - `from` and `to` are never both zero.
- * - `batchSize` is non-zero.
- *
- * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
- */
- function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
- /**
- * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
- * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
- *
- * Calling conditions:
- *
- * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
- * - When `from` is zero, the tokens were minted for `to`.
- * - When `to` is zero, ``from``'s tokens were burned.
- * - `from` and `to` are never both zero.
- * - `batchSize` is non-zero.
- *
- * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
- */
- function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
- /**
- * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
- *
- * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
- * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
- * that `ownerOf(tokenId)` is `a`.
- */
- // solhint-disable-next-line func-name-mixedcase
- function __unsafe_increaseBalance(address account, uint256 value) internal {
- _balances[account] += value;
- }
- }
|