|
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\nerror ERC721__ApprovalCallerNotOwnerNorApproved(address caller);\nerror ERC721__ApproveToCaller();\nerror ERC721__ApprovalToCurrentOwner();\nerror ERC721__BalanceQueryForZeroAddress();\nerror ERC721__MintToZeroAddress();\nerror ERC721__MintZeroQuantity();\nerror ERC721__OwnerQueryForNonexistentToken(uint256 tokenId);\nerror ERC721__TransferCallerNotOwnerNorApproved(address caller);\nerror ERC721__TransferFromIncorrectOwner(address from, address owner);\nerror ERC721__TransferToNonERC721ReceiverImplementer(address receiver);\nerror ERC721__TransferToZeroAddress();\n\n/**\n * @notice Maximally optimized, minimalist ERC-721 implementation.\n *\n * @dev Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3..),\n * and that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.\n * \n * @author https://github.com/kadenzipfel - fork of https://github.com/chiru-labs/ERC721A, \n * inspired by https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol.\n */\nabstract contract ERC721K {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE/LOGIC\n //////////////////////////////////////////////////////////////*/\n\n // Token name\n string public name;\n\n // Token symbol\n string public symbol;\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) public view virtual returns (string memory);\n\n /*//////////////////////////////////////////////////////////////\n ERC721 STORAGE\n //////////////////////////////////////////////////////////////*/ \n\n // Compiler will pack this into a single 256bit word.\n struct TokenOwnership {\n // The address of the owner.\n address addr;\n // Keeps track of the start time of ownership with minimal overhead for tokenomics.\n uint64 startTimestamp;\n // Whether the token has been burned.\n bool burned;\n }\n\n // Compiler will pack this into a single 256bit word.\n struct AddressData {\n // Realistically, 2**64-1 is more than enough.\n uint64 balance;\n // Keeps track of mint count with minimal overhead for tokenomics.\n uint64 numberMinted;\n // Keeps track of burn count with minimal overhead for tokenomics.\n uint64 numberBurned;\n // For miscellaneous variable(s) pertaining to the address\n // (e.g. number of whitelist mint slots used).\n // If there are multiple variables, please pack them into a uint64.\n uint64 aux;\n }\n\n // The tokenId of the next token to be minted.\n uint256 internal _currentIndex = 1;\n\n // The number of tokens burned.\n uint256 internal _burnCounter;\n\n // Mapping from token ID to ownership details\n // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.\n mapping(uint256 => TokenOwnership) internal _ownerships;\n\n // Mapping owner address to address data\n mapping(address => AddressData) private _addressData;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) public getApproved;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) public isApprovedForAll;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(string memory _name, string memory _symbol) {\n name = _name;\n symbol = _symbol;\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC721 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.\n */\n function totalSupply() public view returns (uint256) {\n // Counter underflow is impossible as _burnCounter cannot be incremented\n // more than _currentIndex - 1 times\n unchecked {\n return _currentIndex - _burnCounter - 1;\n }\n }\n\n /**\n * @dev Returns the number of tokens in `owner`'s account.\n */\n function balanceOf(address owner) public view returns (uint256) {\n if (owner == address(0)) revert ERC721__BalanceQueryForZeroAddress();\n return uint256(_addressData[owner].balance);\n }\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n */\n function ownerOf(uint256 tokenId) public view returns (address) {\n return _ownershipOf(tokenId).addr;\n }\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) public {\n address owner = ERC721K.ownerOf(tokenId);\n if (to == owner) revert ERC721__ApprovalToCurrentOwner();\n\n if (msg.sender != owner && !isApprovedForAll[owner][msg.sender]) {\n revert ERC721__ApprovalCallerNotOwnerNorApproved(msg.sender);\n }\n\n _approve(to, tokenId, owner);\n }\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) public virtual {\n if (operator == msg.sender) revert ERC721__ApproveToCaller();\n\n isApprovedForAll[msg.sender][operator] = approved;\n emit ApprovalForAll(msg.sender, operator, approved);\n }\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual {\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual {\n safeTransferFrom(from, to, tokenId, '');\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) public virtual {\n _transfer(from, to, tokenId);\n if (to.code.length != 0 && ERC721TokenReceiver(to).onERC721Received(msg.sender, from, tokenId, _data) !=\n ERC721TokenReceiver.onERC721Received.selector) {\n revert ERC721__TransferToNonERC721ReceiverImplementer(to);\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC165 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n return \n interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165\n interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721\n interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /**\n * Returns the total amount of tokens minted in the contract.\n */\n function _totalMinted() internal view returns (uint256) {\n // Counter underflow is impossible as _currentIndex does not decrement,\n // and it is initialized to 1\n unchecked {\n return _currentIndex - 1;\n }\n }\n\n /**\n * Gas spent here starts off proportional to the maximum mint batch size.\n * It gradually moves to O(1) as tokens get transferred around in the collection over time.\n */\n function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {\n uint256 curr = tokenId;\n\n unchecked {\n if (curr != 0 && curr < _currentIndex) {\n TokenOwnership memory ownership = _ownerships[curr];\n if (!ownership.burned) {\n if (ownership.addr != address(0)) {\n return ownership;\n }\n // Invariant:\n // There will always be an ownership that has an address and is not burned\n // before an ownership that does not have an address and is not burned.\n // Hence, curr will not underflow.\n while (true) {\n curr--;\n ownership = _ownerships[curr];\n if (ownership.addr != address(0)) {\n return ownership;\n }\n }\n }\n }\n }\n revert ERC721__OwnerQueryForNonexistentToken(tokenId);\n }\n\n function _safeMint(address to, uint256 quantity) internal {\n _safeMint(to, quantity, '');\n }\n\n /**\n * @dev Safely mints `quantity` tokens and transfers them to `to`.\n *\n * Requirements:\n *\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.\n * - `quantity` must be greater than 0.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(\n address to,\n uint256 quantity,\n bytes memory _data\n ) internal {\n _mint(to, quantity, _data, true);\n }\n\n /**\n * @dev Mints `quantity` tokens and transfers them to `to`.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `quantity` must be greater than 0.\n *\n * Emits a {Transfer} event.\n */\n function _mint(\n address to,\n uint256 quantity,\n bytes memory _data,\n bool safe\n ) internal {\n uint256 startTokenId = _currentIndex;\n if (to == address(0)) revert ERC721__MintToZeroAddress();\n if (quantity == 0) revert ERC721__MintZeroQuantity();\n\n // Overflows are incredibly unrealistic.\n // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1\n // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1\n unchecked {\n _addressData[to].balance += uint64(quantity);\n _addressData[to].numberMinted += uint64(quantity);\n\n _ownerships[startTokenId].addr = to;\n _ownerships[startTokenId].startTimestamp = uint64(block.timestamp);\n\n uint256 updatedIndex = startTokenId;\n uint256 end = updatedIndex + quantity;\n\n if (safe && to.code.length != 0) {\n do {\n emit Transfer(address(0), to, updatedIndex++);\n } while (updatedIndex != end);\n if (ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), end - 1, _data) !=\n ERC721TokenReceiver.onERC721Received.selector) {\n revert ERC721__TransferToNonERC721ReceiverImplementer(to);\n }\n // Reentrancy protection\n if (_currentIndex != startTokenId) revert();\n } else {\n do {\n emit Transfer(address(0), to, updatedIndex++);\n } while (updatedIndex != end);\n }\n _currentIndex = updatedIndex;\n }\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) private {\n TokenOwnership memory prevOwnership = _ownershipOf(tokenId);\n\n if (prevOwnership.addr != from) revert ERC721__TransferFromIncorrectOwner(from, prevOwnership.addr);\n\n bool isApprovedOrOwner = (msg.sender == from ||\n getApproved[tokenId] == msg.sender) ||\n isApprovedForAll[from][msg.sender];\n\n if (!isApprovedOrOwner) revert ERC721__TransferCallerNotOwnerNorApproved(msg.sender);\n if (to == address(0)) revert ERC721__TransferToZeroAddress();\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId, from);\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.\n unchecked {\n _addressData[from].balance -= 1;\n _addressData[to].balance += 1;\n\n TokenOwnership storage currSlot = _ownerships[tokenId];\n currSlot.addr = to;\n currSlot.startTimestamp = uint64(block.timestamp);\n\n // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.\n // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.\n uint256 nextTokenId = tokenId + 1;\n TokenOwnership storage nextSlot = _ownerships[nextTokenId];\n if (nextSlot.addr == address(0)) {\n if (nextTokenId != _currentIndex) {\n nextSlot.addr = from;\n nextSlot.startTimestamp = prevOwnership.startTimestamp;\n }\n }\n }\n\n delete getApproved[tokenId];\n\n emit Transfer(from, to, tokenId);\n }\n\n /**\n * @dev This is equivalent to _burn(tokenId, false)\n */\n function _burn(uint256 tokenId) internal virtual {\n _burn(tokenId, false);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId, bool approvalCheck) internal virtual {\n TokenOwnership memory prevOwnership = _ownershipOf(tokenId);\n\n address from = prevOwnership.addr;\n\n if (approvalCheck) {\n bool isApprovedOrOwner = (msg.sender == from ||\n getApproved[tokenId] == msg.sender) ||\n isApprovedForAll[from][msg.sender];\n\n if (!isApprovedOrOwner) revert ERC721__TransferCallerNotOwnerNorApproved(msg.sender);\n }\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId, from);\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.\n unchecked {\n AddressData storage addressData = _addressData[from];\n addressData.balance -= 1;\n addressData.numberBurned += 1;\n\n // Keep track of who burned the token, and the timestamp of burning.\n TokenOwnership storage currSlot = _ownerships[tokenId];\n currSlot.addr = from;\n currSlot.startTimestamp = uint64(block.timestamp);\n currSlot.burned = true;\n\n // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.\n // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.\n uint256 nextTokenId = tokenId + 1;\n TokenOwnership storage nextSlot = _ownerships[nextTokenId];\n if (nextSlot.addr == address(0)) {\n if (nextTokenId != _currentIndex) {\n nextSlot.addr = from;\n nextSlot.startTimestamp = prevOwnership.startTimestamp;\n }\n }\n }\n\n delete getApproved[tokenId];\n\n emit Transfer(from, address(0), tokenId);\n\n // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.\n unchecked {\n _burnCounter++;\n }\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits a {Approval} event.\n */\n function _approve(\n address to,\n uint256 tokenId,\n address owner\n ) private {\n getApproved[tokenId] = to;\n emit Approval(owner, to, tokenId);\n }\n}\n\n/// @notice A generic interface for a contract which properly accepts ERC721 tokens.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)\ninterface ERC721TokenReceiver {\n function onERC721Received(\n address operator,\n address from,\n uint256 id,\n bytes calldata data\n ) external returns (bytes4);\n}"
|