// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.16; // ========== External imports ========== import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@erc721/ERC721R/ERC721R.sol"; // ========== Internal imports ========== import "./lib/CurrencyTransferLib.sol"; // ========== Features ========== import "./extension/interface/IERC721Enumerable.sol"; import "./extension/RoyaltySplitter.sol"; import "./extension/PrimarySale.sol"; import "./extension/DelayedReveal.sol"; import "./extension/LazyMint.sol"; import "./extension/Drop.sol"; import "./extension/WalletClaimCounter.sol"; import "./extension/Oneshot.sol"; import "./extension/ThirdPartyMint721.sol"; import "./lib/Crypto.sol"; contract KanjiDropERC721REnumerable is IERC721Enumerable, WalletClaimCounter, RoyaltySplitter, PrimarySale, Ownable, DelayedReveal, LazyMint, Drop, ThirdPartyMint721, ReentrancyGuard, Pausable, Oneshot, ERC721r { using Strings for uint256; /*/////////////////////////////////////////////////////////////// Errors //////////////////////////////////////////////////////////////*/ error NotEnoughMintedTokensError(uint256 quantity, uint256 nextTokenIdToClaim, uint256 nextTokenIdToMint); error ExceedMaxSupplyError(uint256 quantity, uint256 maxSupply, uint256 nextTokenIdToClaim); error ExceedClaimLimitForWalletError( uint256 quantity, uint256 walletClaimCountClaimer, address claimer, uint256 maxWalletClaimCount ); error PausedError(); error IncorrectMsgValue(uint256 expected); /*/////////////////////////////////////////////////////////////// Events //////////////////////////////////////////////////////////////*/ event MaxSupplyUpdated(uint256 maxSupply); /*/////////////////////////////////////////////////////////////// State variables //////////////////////////////////////////////////////////////*/ /// @dev Max bps in the thirdweb system. uint256 private constant MAX_BPS = 10_000; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /*/////////////////////////////////////////////////////////////// Constructor + initializer logic //////////////////////////////////////////////////////////////*/ /// @notice Creates a new `KanjiDropERC721A` contract. /// @param _name The name of the NFT. /// @param _symbol The symbol of the NFT. /// @param _metadata Contract-level metadata /// @param _saleRecipients Recipients of the sale /// @param _royaltyBps The ERC2981 royalty cut /// @param _royaltyRecipients The ERC2981 royalty recipients constructor( string memory _name, string memory _symbol, uint256 _maxSupply, Metadata memory _metadata, PrimarySaleRecipient[] memory _saleRecipients, uint16 _royaltyBps, RoyaltyRecipient[] memory _royaltyRecipients, IAccessControl _thirdParty ) PrimarySale(_saleRecipients) RoyaltySplitter(_royaltyRecipients, _metadata, _royaltyBps) ERC721r(_name, _symbol, _maxSupply) ReentrancyGuard() Ownable() Pausable() ThirdPartyMint721(_thirdParty) {} /*/////////////////////////////////////////////////////////////// ERC 165 / 721 / 2981 logic //////////////////////////////////////////////////////////////*/ /// @dev Returns the URI for a given tokenId. function tokenURI(uint256 _tokenId) public view override returns (string memory) { if (isEncrypted) { return flaskURI; } else { return string(abi.encodePacked(baseURI, _tokenId.toString(), ".json")); } } /// @dev See ERC 165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721r, IERC165) returns (bool) { return super.supportsInterface(interfaceId) || type(IERC2981).interfaceId == interfaceId || type(IERC721Enumerable).interfaceId == interfaceId; } function totalSupply() public view virtual override(IERC721Enumerable, ERC721r) returns (uint256) { return ERC721r.totalSupply(); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721r.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /*/////////////////////////////////////////////////////////////// Lazy minting + delayed-reveal logic //////////////////////////////////////////////////////////////*/ function lazyMint(uint256 _amount, bytes calldata _baseURI, string calldata _flaskURI) public onlyOwner oneShot { if (_amount == 0) revert AmountCantBeZeroError(); if (_baseURI.length == 0) { revert BaseURIRequiredError(); } baseURI = string(_baseURI); if (bytes(_flaskURI).length != 0) { isEncrypted = true; flaskURI = _flaskURI; } super.lazyMint(_amount); } /// @dev Lets an owner reveal the URI for a batch of 'delayed-reveal' NFTs. function reveal(bytes calldata _key) external onlyOwner oneShot returns (string memory revealedURI) { if (!isEncrypted) revert NothingToReveal(); revealedURI = string(Crypto.encryptDecrypt(bytes(baseURI), _key)); baseURI = revealedURI; isEncrypted = false; emit URIRevealed(revealedURI); } /// @notice owner mint a reserve of tokens to specific address /// @param receiver receiver of mint /// @param quantity quantity gonna be mint function mintOwner(address receiver, uint256 quantity) external onlyOwner { if (totalSupply() + quantity > maxSupply()) revert ExceedMaxSupplyError(quantity, maxSupply(), totalSupply()); super.lazyMint(quantity); _mintRandom(receiver, quantity); } /// @notice owner mint a one token for every address in the list /// Be aware of the order, as the tokenID depends on it /// @param recipients receiver of mint function batchMintOwner(address[] memory recipients) external onlyOwner { if (totalSupply() + recipients.length > maxSupply()) { revert ExceedMaxSupplyError(recipients.length, maxSupply(), totalSupply()); } super.lazyMint(recipients.length); for (uint256 i = 0; i < recipients.length; i++) { _mintRandom(recipients[i], 1); } } /*/////////////////////////////////////////////////////////////// Internal functions //////////////////////////////////////////////////////////////*/ /// @dev Runs before every `claim` function call. function _beforeClaim(address _claimer, uint256 _quantity, bytes32[] calldata) internal view override { if (totalSupply() + _quantity > nextTokenIdToLazyMint) { revert NotEnoughMintedTokensError({ quantity: _quantity, nextTokenIdToClaim: totalSupply(), nextTokenIdToMint: nextTokenIdToLazyMint }); } if (maxSupply() != 0 && totalSupply() + _quantity > maxSupply()) { revert ExceedMaxSupplyError({quantity: _quantity, maxSupply: maxSupply(), nextTokenIdToClaim: totalSupply()}); } if (maxWalletClaimCount != 0 && walletClaimCount[_claimer] + _quantity > maxWalletClaimCount) { revert ExceedClaimLimitForWalletError({ quantity: _quantity, walletClaimCountClaimer: walletClaimCount[_claimer], claimer: _claimer, maxWalletClaimCount: maxWalletClaimCount }); } } /// @dev Collects and distributes the primary sale value of NFTs being claimed. function collectPriceOnClaim(uint256 _quantityToClaim, uint256 _pricePerToken) internal override { if (_pricePerToken == 0) { return; } uint256 totalPrice = _quantityToClaim * _pricePerToken; if (msg.value != totalPrice) { revert IncorrectMsgValue({expected: totalPrice}); } address[] memory recipients = primarySaleRecipients(); for (uint256 i = 0; i < recipients.length; i++) { uint256 payout = ((totalPrice) * primarySaleRecipientBps(recipients[i])) / MAX_BPS; CurrencyTransferLib.transferCurrency(CurrencyTransferLib.NATIVE_TOKEN, _msgSender(), recipients[i], payout); } } /// @dev Transfers the NFTs being claimed. function transferTokensOnClaim(address _to, uint256 _quantityBeingClaimed) internal override returns (uint256 startTokenId) { startTokenId = totalSupply(); walletClaimCount[_msgSender()] += _quantityBeingClaimed; _mintRandom(_to, _quantityBeingClaimed); } function _beforeChangeThirdPartySetup(IAccessControl _thirdParty) internal override onlyOwner {} function _afterMintFromThirdParty(address _receiver, uint256 _quantity) internal override { _mintRandom(_receiver, _quantity); } /*/////////////////////////////////////////////////////////////// Miscellaneous //////////////////////////////////////////////////////////////*/ /** * Returns the total amount of tokens minted in the contract. */ function totalMinted() external view returns (uint256) { unchecked { return totalSupply(); } } /// @dev The tokenId of the next NFT that will be minted / lazy minted. function nextTokenIdToMint() external view returns (uint256) { return nextTokenIdToLazyMint; } /// @dev See {ERC721-_beforeTokenTransfer}. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { if (paused()) { revert PausedError(); } super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /// @notice Temporarily lock the contract function pause() external onlyOwner { if (paused()) _unpause(); else _pause(); } function setClaimConditions(ClaimCondition[] calldata _conditions, bool _resetClaimEligibility) public override onlyOwner { super.setClaimConditions(_conditions, _resetClaimEligibility); } function claim(address _receiver, uint256 _quantity, bytes32[] calldata _proof) public payable override nonReentrant { super.claim(_receiver, _quantity, _proof); } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721r.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721r.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } }