// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import"@openzeppelin/contracts/access/Ownable.sol";
import"@openzeppelin/contracts/utils/Strings.sol";
import"erc721a/contracts/extensions/ERC721AQueryable.sol";
import"erc721a/contracts/extensions/ERC721ABurnable.sol";
import {IBrawlerBearzDynamicItems} from"./interfaces/IBrawlerBearzDynamicItems.sol";
import"./tunnel/FxBaseRootTunnel.sol";
/*******************************************************************************
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|,|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&@@@@@@@@@@@|,*|&@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%,**%@@@@@@@@%|******%&@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&##*****|||**,(%%%%%**|%@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@***,#%%%%**#&@@@@@#**,|@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@*,(@@@@@@@@@@**,(&@@@@#**%@@@@@@||(%@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@%|,****&@((@&***&@@@@@@%||||||||#%&@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@&%#*****||||||**#%&@%%||||||||#@&%#(@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@&**,(&@@@@@%|||||*##&&&&##|||||(%@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@**,%@@@@@@@(|*|#%@@@@@@@@#||#%%@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@#||||#@@@@||*|%@@@@@@@@&|||%%&@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@#,,,,,,*|**||%|||||||###&@@@@@@@#|||#%@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@&#||*|||||%%%@%%%#|||%@@@@@@@@&(|(%&@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@&&%%(||||@@@@@@&|||||(%&((||(#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@%%(||||||||||#%#(|||||%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@&%#######%%@@**||(#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%##%%&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
********************************************************************************//**
* @title BrawlerBearzBattlePass
* @author @ScottMitchell18
* @dev Battle pass public mint and L2 sync on mint, non-transferable, or sellable
*/contractBrawlerBearzBattlePassisFxBaseRootTunnel,
ERC721AQueryable,
ERC721ABurnable,
Ownable{
usingStringsforuint256;
/// @dev Sync actionsbytes32publicconstant MINTED =keccak256("MINTED");
bytes32publicconstant REWARDS_CLAIM =keccak256("REWARDS_CLAIM");
/// @notice Vendor contract
IBrawlerBearzDynamicItems public vendorContract;
// @dev Base uri for the nftstringprivate baseURI ="ipfs://bafybeigbadgbqqmajhdiqgh354pqqaf32daqlcddrf4xccvbo4vo6e2zfm/";
// @dev The whitelist merkle rootbytes32public merkleRoot;
/// @notice Free battle pass tieruint256constant FREE_PASS =1;
/// @notice Pro battle pass tieruint256constant PRO_PASS =2;
/// @notice Pro+ battle pass tieruint256constant PRO_PLUS_PASS =3;
/// @notice Pro pass mint priceuint256public proPrice =0.01ether;
/// @notice Pro plus pass mint priceuint256public proPlusPrice =0.045ether;
// @dev Treasuryaddresspublic treasury =payable(0x39bfA2b4319581bc885A2d4b9F0C90C2e1c24B87);
/*
* @notice All mints live ~ December 5th, 12PM EST
* @dev Mints go live date
*/uint256public liveAt =1670259600;
/*
* @notice All mints expired ~ December 12th, 12PM EST
* @dev Mints expire at
*/uint256public expiresAt =1670864400;
/// @dev An address mapping for free pass mintedmapping(address=>bool) public addressToFreePassMinted;
/// @dev A token mapping to battle pass typemapping(uint256=>uint256) public passes;
/// @dev Thrown on approvalerrorCannotApproveAll();
/// @dev Thrown on transfererrorNontransferable();
modifierwhitelisted(bytes32[] calldata _proof) {
bytes32 leaf =keccak256(abi.encodePacked(_msgSender()));
require(MerkleProof.verify(_proof, merkleRoot, leaf), "Invalid proof.");
_;
}
modifiermintIsActive() {
require(
block.timestamp> liveAt &&block.timestamp< expiresAt,
"Minting is not active."
);
_;
}
constructor(address _checkpointManager,
address _fxRoot,
address _vendorContractAddress
)
FxBaseRootTunnel(_checkpointManager, _fxRoot)
ERC721A("Brawler Bearz Battle Pass", "BBBP")
{
vendorContract = IBrawlerBearzDynamicItems(_vendorContractAddress);
}
/**
* @notice Free battle pass mint
* @param _proof The bytes32 array proof to verify the merkle root
*/functionfreePassMint(bytes32[] calldata _proof)
externalmintIsActivewhitelisted(_proof)
{
require(!addressToFreePassMinted[_msgSender()], "Already free minted");
addressToFreePassMinted[_msgSender()] =true;
_mintSync(_msgSender(), FREE_PASS);
}
/// @notice Pro pass mintfunctionproPassMint() externalpayablemintIsActive{
require(msg.value>= proPrice, "Not enough funds.");
_mintSync(_msgSender(), PRO_PASS);
}
/// @notice Pro plus pass mintfunctionproPlusPassMint() externalpayablemintIsActive{
require(msg.value>= proPlusPrice, "Not enough funds.");
_mintSync(_msgSender(), PRO_PLUS_PASS);
}
/**
* @notice Returns the URI for a given token id
* @param _tokenId A tokenId
*/functiontokenURI(uint256 _tokenId)
publicviewoverridereturns (stringmemory)
{
if (!_exists(_tokenId)) revert OwnerQueryForNonexistentToken();
// 1, 2, 3returnstring(
abi.encodePacked(baseURI, Strings.toString(passes[_tokenId]))
);
}
// @dev Check if mint is livefunctionisLive() publicviewreturns (bool) {
returnblock.timestamp> liveAt &&block.timestamp< expiresAt;
}
/**
* @dev Check if wallet has minted
* @param _address mint address lookup
*/functionhasMintedFreePass(address _address) publicviewreturns (bool) {
return addressToFreePassMinted[_address];
}
// @dev Returns the starting token ID.function_startTokenId() internalviewvirtualoverridereturns (uint256) {
return1;
}
/**
* @notice Sets pro price
* @param _proPrice A base uri
*/functionsetProPrice(uint256 _proPrice) externalonlyOwner{
proPrice = _proPrice;
}
/**
* @notice Sets pro plus price
* @param _proPlusPrice A base uri
*/functionsetProPlusPrice(uint256 _proPlusPrice) externalonlyOwner{
proPlusPrice = _proPlusPrice;
}
/**
* @notice Sets the base URI of the NFT
* @param _baseURI A base uri
*/functionsetBaseURI(stringcalldata _baseURI) externalonlyOwner{
baseURI = _baseURI;
}
/**
* @notice Sets timestamps for live and expires timeframe
* @param _liveAt A unix timestamp for live date
* @param _expiresAt A unix timestamp for expiration date
*/functionsetMintWindow(uint256 _liveAt, uint256 _expiresAt)
externalonlyOwner{
liveAt = _liveAt;
expiresAt = _expiresAt;
}
/**
* @notice Sets the treasury recipient
* @param _treasury The treasury address
*/functionsetTreasury(address _treasury) publiconlyOwner{
treasury =payable(_treasury);
}
/**
* @notice Sets the Whitelist merkle root for the mint
* @param _merkleRoot The merkle root to set
*/functionsetMerkleRoot(bytes32 _merkleRoot) externalonlyOwner{
merkleRoot = _merkleRoot;
}
/**
* Set FxChildTunnel
* @param _fxChildTunnel - the fxChildTunnel address
*/functionsetFxChildTunnel(address _fxChildTunnel)
publicoverrideonlyOwner{
fxChildTunnel = _fxChildTunnel;
}
/**
* @notice Sets the bearz vendor item contract
* @dev only owner call this function
* @param _vendorContractAddress The new contract address
*/functionsetVendorContractAddress(address _vendorContractAddress)
externalonlyOwner{
vendorContract = IBrawlerBearzDynamicItems(_vendorContractAddress);
}
/// @notice Withdraws funds from contractfunctionwithdraw() publiconlyOwner{
(bool success, ) = treasury.call{value: address(this).balance}("");
require(success, "999");
}
/**
* @dev Internal helper function for minting and syncing to L2
* @param _address The amount of pro passes to mint
* @param _passType The pass type (1,2,3)
*/function_mintSync(address _address, uint256 _passType) internal{
uint256 tokenId = _nextTokenId();
_mint(_address, 1);
passes[tokenId] = _passType;
_sendMessageToChild(
abi.encode(MINTED, abi.encode(_address, tokenId, _passType))
);
}
/// @dev Prevent approvals of tokenfunctionsetApprovalForAll(address, bool) publicvirtualoverride{
revert CannotApproveAll();
}
/// @dev Prevent token transfer unless burningfunction_beforeTokenTransfers(addressfrom,
address to,
uint256 startTokenId,
uint256 quantity
) internaloverride(ERC721A) {
if (to !=address(0) &&from!=address(0)) {
revert Nontransferable();
}
super._beforeTokenTransfers(from, to, startTokenId, quantity);
}
function_processRewardsClaim(bytesmemory data) internal{
(address to, uint256[] memory itemIds) =abi.decode(
data,
(address, uint256[])
);
vendorContract.dropItems(to, itemIds);
}
/// @dev TEST// function _processMessageFromChildTest(bytes memory message)// external// onlyOwner// {// (bytes32 syncType, bytes memory syncData) = abi.decode(// message,// (bytes32, bytes)// );// if (syncType == REWARDS_CLAIM) {// _processRewardsClaim(syncData);// } else {// revert("INVALID_SYNC_TYPE");// }// }function_processMessageFromChild(bytesmemory message) internaloverride{
(bytes32 syncType, bytesmemory syncData) =abi.decode(
message,
(bytes32, bytes)
);
if (syncType == REWARDS_CLAIM) {
_processRewardsClaim(syncData);
} else {
revert("INVALID_SYNC_TYPE");
}
}
}
Contract Source Code
File 2 of 19: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 3 of 19: ERC721A.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.1.0// Creator: Chiru Labspragmasolidity ^0.8.4;import'./IERC721A.sol';
/**
* @dev ERC721 token receiver interface.
*/interfaceERC721A__IERC721Receiver{
functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard,
* including the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at `_startTokenId()`
* (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/contractERC721AisIERC721A{
// Mask of an entry in packed address data.uint256privateconstant BITMASK_ADDRESS_DATA_ENTRY = (1<<64) -1;
// The bit position of `numberMinted` in packed address data.uint256privateconstant BITPOS_NUMBER_MINTED =64;
// The bit position of `numberBurned` in packed address data.uint256privateconstant BITPOS_NUMBER_BURNED =128;
// The bit position of `aux` in packed address data.uint256privateconstant BITPOS_AUX =192;
// Mask of all 256 bits in packed address data except the 64 bits for `aux`.uint256privateconstant BITMASK_AUX_COMPLEMENT = (1<<192) -1;
// The bit position of `startTimestamp` in packed ownership.uint256privateconstant BITPOS_START_TIMESTAMP =160;
// The bit mask of the `burned` bit in packed ownership.uint256privateconstant BITMASK_BURNED =1<<224;
// The bit position of the `nextInitialized` bit in packed ownership.uint256privateconstant BITPOS_NEXT_INITIALIZED =225;
// The bit mask of the `nextInitialized` bit in packed ownership.uint256privateconstant BITMASK_NEXT_INITIALIZED =1<<225;
// The bit position of `extraData` in packed ownership.uint256privateconstant BITPOS_EXTRA_DATA =232;
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.uint256privateconstant BITMASK_EXTRA_DATA_COMPLEMENT = (1<<232) -1;
// The mask of the lower 160 bits for addresses.uint256privateconstant BITMASK_ADDRESS = (1<<160) -1;
// The maximum `quantity` that can be minted with `_mintERC2309`.// This limit is to prevent overflows on the address data entries.// For a limit of 5000, a total of 3.689e15 calls to `_mintERC2309`// is required to cause an overflow, which is unrealistic.uint256privateconstant MAX_MINT_ERC2309_QUANTITY_LIMIT =5000;
// The tokenId of the next token to be minted.uint256private _currentIndex;
// The number of tokens burned.uint256private _burnCounter;
// Token namestringprivate _name;
// Token symbolstringprivate _symbol;
// Mapping from token ID to ownership details// An empty struct value does not necessarily mean the token is unowned.// See `_packedOwnershipOf` implementation for details.//// Bits Layout:// - [0..159] `addr`// - [160..223] `startTimestamp`// - [224] `burned`// - [225] `nextInitialized`// - [232..255] `extraData`mapping(uint256=>uint256) private _packedOwnerships;
// Mapping owner address to address data.//// Bits Layout:// - [0..63] `balance`// - [64..127] `numberMinted`// - [128..191] `numberBurned`// - [192..255] `aux`mapping(address=>uint256) private _packedAddressData;
// Mapping from token ID to approved address.mapping(uint256=>address) private _tokenApprovals;
// Mapping from owner to operator approvalsmapping(address=>mapping(address=>bool)) private _operatorApprovals;
constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* @dev Returns the starting token ID.
* To change the starting token ID, please override this function.
*/function_startTokenId() internalviewvirtualreturns (uint256) {
return0;
}
/**
* @dev Returns the next token ID to be minted.
*/function_nextTokenId() internalviewreturns (uint256) {
return _currentIndex;
}
/**
* @dev Returns the total number of tokens in existence.
* Burned tokens will reduce the count.
* To get the total number of tokens minted, please see `_totalMinted`.
*/functiontotalSupply() publicviewoverridereturns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented// more than `_currentIndex - _startTokenId()` times.unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* @dev Returns the total amount of tokens minted in the contract.
*/function_totalMinted() internalviewreturns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,// and it is initialized to `_startTokenId()`unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev Returns the total number of tokens burned.
*/function_totalBurned() internalviewreturns (uint256) {
return _burnCounter;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
// The interface IDs are constants representing the first 4 bytes of the XOR of// all function selectors in the interface. See: https://eips.ethereum.org/EIPS/eip-165// e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`return
interfaceId ==0x01ffc9a7||// ERC165 interface ID for ERC165.
interfaceId ==0x80ac58cd||// ERC165 interface ID for ERC721.
interfaceId ==0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner) publicviewoverridereturns (uint256) {
if (owner ==address(0)) revert BalanceQueryForZeroAddress();
return _packedAddressData[owner] & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens minted by `owner`.
*/function_numberMinted(address owner) internalviewreturns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_MINTED) & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/function_numberBurned(address owner) internalviewreturns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_BURNED) & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
*/function_getAux(address owner) internalviewreturns (uint64) {
returnuint64(_packedAddressData[owner] >> BITPOS_AUX);
}
/**
* Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/function_setAux(address owner, uint64 aux) internal{
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
// Cast `aux` with assembly to avoid redundant masking.assembly {
auxCasted := aux
}
packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX);
_packedAddressData[owner] = packed;
}
/**
* Returns the packed ownership data of `tokenId`.
*/function_packedOwnershipOf(uint256 tokenId) privateviewreturns (uint256) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr)
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
// If not burned.if (packed & BITMASK_BURNED ==0) {
// Invariant:// There will always be an ownership that has an address and is not burned// before an ownership that does not have an address and is not burned.// Hence, curr will not underflow.//// We can directly compare the packed value.// If the address is zero, packed is zero.while (packed ==0) {
packed = _packedOwnerships[--curr];
}
return packed;
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* Returns the unpacked `TokenOwnership` struct from `packed`.
*/function_unpackedOwnership(uint256 packed) privatepurereturns (TokenOwnership memory ownership) {
ownership.addr =address(uint160(packed));
ownership.startTimestamp =uint64(packed >> BITPOS_START_TIMESTAMP);
ownership.burned = packed & BITMASK_BURNED !=0;
ownership.extraData =uint24(packed >> BITPOS_EXTRA_DATA);
}
/**
* Returns the unpacked `TokenOwnership` struct at `index`.
*/function_ownershipAt(uint256 index) internalviewreturns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnerships[index]);
}
/**
* @dev Initializes the ownership slot minted at `index` for efficiency purposes.
*/function_initializeOwnershipAt(uint256 index) internal{
if (_packedOwnerships[index] ==0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/function_ownershipOf(uint256 tokenId) internalviewreturns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
/**
* @dev Packs ownership data into a single uint256.
*/function_packOwnershipData(address owner, uint256 flags) privateviewreturns (uint256 result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
owner :=and(owner, BITMASK_ADDRESS)
// `owner | (block.timestamp << BITPOS_START_TIMESTAMP) | flags`.
result :=or(owner, or(shl(BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewoverridereturns (address) {
returnaddress(uint160(_packedOwnershipOf(tokenId)));
}
/**
* @dev See {IERC721Metadata-name}.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/functiontokenURI(uint256 tokenId) publicviewvirtualoverridereturns (stringmemory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length!=0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
}
/**
* @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, it can be overridden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return'';
}
/**
* @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
*/function_nextInitializedFlag(uint256 quantity) privatepurereturns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.assembly {
// `(quantity == 1) << BITPOS_NEXT_INITIALIZED`.
result :=shl(BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicoverride{
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId) publicviewoverridereturns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtualoverride{
if (operator == _msgSenderERC721A()) revert ApproveToCaller();
_operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) publicvirtualoverride{
transferFrom(from, to, tokenId);
if (to.code.length!=0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/function_exists(uint256 tokenId) internalviewreturns (bool) {
return
_startTokenId() <= tokenId &&
tokenId < _currentIndex &&// If within bounds,
_packedOwnerships[tokenId] & BITMASK_BURNED ==0; // and not burned.
}
/**
* @dev Equivalent to `_safeMint(to, quantity, '')`.
*/function_safeMint(address to, uint256 quantity) internal{
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* See {_mint}.
*
* Emits a {Transfer} event for each mint.
*/function_safeMint(address to,
uint256 quantity,
bytesmemory _data
) internal{
_mint(to, quantity);
unchecked {
if (to.code.length!=0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
// Reentrancy protection.if (_currentIndex != end) revert();
}
}
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event for each mint.
*/function_mint(address to, uint256 quantity) internal{
uint256 startTokenId = _currentIndex;
if (to ==address(0)) revert MintToZeroAddress();
if (quantity ==0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.// `balance` and `numberMinted` have a maximum limit of 2**64.// `tokenId` has a maximum limit of 2**256.unchecked {
// Updates:// - `balance += quantity`.// - `numberMinted += quantity`.//// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1<< BITPOS_NUMBER_MINTED) |1);
// Updates:// - `address` to the owner.// - `startTimestamp` to the timestamp of minting.// - `burned` to `false`.// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 tokenId = startTokenId;
uint256 end = startTokenId + quantity;
do {
emit Transfer(address(0), to, tokenId++);
} while (tokenId < end);
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* This function is intended for efficient minting only during contract creation.
*
* It emits only one {ConsecutiveTransfer} as defined in
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
* instead of a sequence of {Transfer} event(s).
*
* Calling this function outside of contract creation WILL make your contract
* non-compliant with the ERC721 standard.
* For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
* {ConsecutiveTransfer} event is only permissible during contract creation.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {ConsecutiveTransfer} event.
*/function_mintERC2309(address to, uint256 quantity) internal{
uint256 startTokenId = _currentIndex;
if (to ==address(0)) revert MintToZeroAddress();
if (quantity ==0) revert MintZeroQuantity();
if (quantity > MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are unrealistic due to the above check for `quantity` to be below the limit.unchecked {
// Updates:// - `balance += quantity`.// - `numberMinted += quantity`.//// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1<< BITPOS_NUMBER_MINTED) |1);
// Updates:// - `address` to the owner.// - `startTimestamp` to the timestamp of minting.// - `burned` to `false`.// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity -1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Returns the storage slot and value for the approved address of `tokenId`.
*/function_getApprovedAddress(uint256 tokenId)
privateviewreturns (uint256 approvedAddressSlot, address approvedAddress)
{
mapping(uint256=>address) storage tokenApprovalsPtr = _tokenApprovals;
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId]`.assembly {
// Compute the slot.mstore(0x00, tokenId)
mstore(0x20, tokenApprovalsPtr.slot)
approvedAddressSlot :=keccak256(0x00, 0x40)
// Load the slot's value from storage.
approvedAddress :=sload(approvedAddressSlot)
}
}
/**
* @dev Returns whether the `approvedAddress` is equals to `from` or `msgSender`.
*/function_isOwnerOrApproved(address approvedAddress,
addressfrom,
address msgSender
) privatepurereturns (bool result) {
assembly {
// Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean.
from :=and(from, BITMASK_ADDRESS)
// Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
msgSender :=and(msgSender, BITMASK_ADDRESS)
// `msgSender == from || msgSender == approvedAddress`.
result :=or(eq(msgSender, from), eq(msgSender, approvedAddress))
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) !=from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
// The nested ifs save around 20+ gas over a compound boolean condition.if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to ==address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner.assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender's balance is impossible because we check for// ownership above and the recipient's balance can't realistically overflow.// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.unchecked {
// We can directly increment and decrement the balances.--_packedAddressData[from]; // Updates: `balance -= 1`.++_packedAddressData[to]; // Updates: `balance += 1`.// Updates:// - `address` to the next owner.// - `startTimestamp` to the timestamp of transfering.// - `burned` to `false`.// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED ==0) {
uint256 nextTokenId = tokenId +1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).if (_packedOwnerships[nextTokenId] ==0) {
// If the next slot is within bounds.if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Equivalent to `_burn(tokenId, false)`.
*/function_burn(uint256 tokenId) internalvirtual{
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId, bool approvalCheck) internalvirtual{
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
addressfrom=address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
// The nested ifs save around 20+ gas over a compound boolean condition.if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner.assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender's balance is impossible because we check for// ownership above and the recipient's balance can't realistically overflow.// Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.unchecked {
// Updates:// - `balance -= 1`.// - `numberBurned += 1`.//// We can directly decrement the balance, and increment the number burned.// This is equivalent to `packed -= 1; packed += 1 << BITPOS_NUMBER_BURNED;`.
_packedAddressData[from] += (1<< BITPOS_NUMBER_BURNED) -1;
// Updates:// - `address` to the last owner.// - `startTimestamp` to the timestamp of burning.// - `burned` to `true`.// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED ==0) {
uint256 nextTokenId = tokenId +1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).if (_packedOwnerships[nextTokenId] ==0) {
// If the next slot is within bounds.if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.unchecked {
_burnCounter++;
}
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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_checkContractOnERC721Received(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) privatereturns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Directly sets the extra data for the ownership data `index`.
*/function_setExtraDataAt(uint256 index, uint24 extraData) internal{
uint256 packed = _packedOwnerships[index];
if (packed ==0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast `extraData` with assembly to avoid redundant masking.assembly {
extraDataCasted := extraData
}
packed = (packed & BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
/**
* @dev Returns the next extra data for the packed ownership data.
* The returned result is shifted into position.
*/function_nextExtraData(addressfrom,
address to,
uint256 prevOwnershipPacked
) privateviewreturns (uint256) {
uint24 extraData =uint24(prevOwnershipPacked >> BITPOS_EXTRA_DATA);
returnuint256(_extraData(from, to, extraData)) << BITPOS_EXTRA_DATA;
}
/**
* @dev Called during each token transfer to set the 24bit `extraData` field.
* Intended to be overridden by the cosumer contract.
*
* `previousExtraData` - the value of `extraData` before transfer.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/function_extraData(addressfrom,
address to,
uint24 previousExtraData
) internalviewvirtualreturns (uint24) {}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred.
* This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/function_beforeTokenTransfers(addressfrom,
address to,
uint256 startTokenId,
uint256 quantity
) internalvirtual{}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred.
* This includes minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/function_afterTokenTransfers(addressfrom,
address to,
uint256 startTokenId,
uint256 quantity
) internalvirtual{}
/**
* @dev Returns the message sender (defaults to `msg.sender`).
*
* If you are writing GSN compatible contracts, you need to override this function.
*/function_msgSenderERC721A() internalviewvirtualreturns (address) {
returnmsg.sender;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/function_toString(uint256 value) internalpurereturns (stringmemory ptr) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit),// but we allocate 128 bytes to keep the free memory pointer 32-byte word aliged.// We will need 1 32-byte word to store the length,// and 3 32-byte words to store a maximum of 78 digits. Total: 32 + 3 * 32 = 128.
ptr :=add(mload(0x40), 128)
// Update the free memory pointer to allocate.mstore(0x40, ptr)
// Cache the end of the memory to calculate the length later.let end := ptr
// We write the string from the rightmost digit to the leftmost digit.// The following is essentially a do-while loop that also handles the zero case.// Costs a bit more than early returning for the zero case,// but cheaper in terms of deployment and overall runtime costs.for {
// Initialize and perform the first pass without check.let temp := value
// Move the pointer 1 byte leftwards to point to an empty character slot.
ptr :=sub(ptr, 1)
// Write the character to the pointer. 48 is the ASCII index of '0'.mstore8(ptr, add(48, mod(temp, 10)))
temp :=div(temp, 10)
} temp {
// Keep dividing `temp` until zero.
temp :=div(temp, 10)
} {
// Body of the for loop.
ptr :=sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
}
let length :=sub(end, ptr)
// Move the pointer 32 bytes leftwards to make room for the length.
ptr :=sub(ptr, 32)
// Store the length.mstore(ptr, length)
}
}
}
Contract Source Code
File 4 of 19: ERC721ABurnable.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.1.0// Creator: Chiru Labspragmasolidity ^0.8.4;import'./IERC721ABurnable.sol';
import'../ERC721A.sol';
/**
* @title ERC721A Burnable Token
* @dev ERC721A Token that can be irreversibly burned (destroyed).
*/abstractcontractERC721ABurnableisERC721A, IERC721ABurnable{
/**
* @dev Burns `tokenId`. See {ERC721A-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/functionburn(uint256 tokenId) publicvirtualoverride{
_burn(tokenId, true);
}
}
Contract Source Code
File 5 of 19: ERC721AQueryable.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.1.0// Creator: Chiru Labspragmasolidity ^0.8.4;import'./IERC721AQueryable.sol';
import'../ERC721A.sol';
/**
* @title ERC721A Queryable
* @dev ERC721A subclass with convenience query functions.
*/abstractcontractERC721AQueryableisERC721A, IERC721AQueryable{
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
* - `addr` = `address(0)`
* - `startTimestamp` = `0`
* - `burned` = `false`
* - `extraData` = `0`
*
* If the `tokenId` is burned:
* - `addr` = `<Address of owner before token was burned>`
* - `startTimestamp` = `<Timestamp when token was burned>`
* - `burned = `true`
* - `extraData` = `<Extra data when token was burned>`
*
* Otherwise:
* - `addr` = `<Address of owner>`
* - `startTimestamp` = `<Timestamp of start of ownership>`
* - `burned = `false`
* - `extraData` = `<Extra data at start of ownership>`
*/functionexplicitOwnershipOf(uint256 tokenId) publicviewoverridereturns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/functionexplicitOwnershipsOf(uint256[] memory tokenIds) externalviewoverridereturns (TokenOwnership[] memory) {
unchecked {
uint256 tokenIdsLength = tokenIds.length;
TokenOwnership[] memory ownerships =new TokenOwnership[](tokenIdsLength);
for (uint256 i; i != tokenIdsLength; ++i) {
ownerships[i] = explicitOwnershipOf(tokenIds[i]);
}
return ownerships;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start` < `stop`
*/functiontokensOfOwnerIn(address owner,
uint256 start,
uint256 stop
) externalviewoverridereturns (uint256[] memory) {
unchecked {
if (start >= stop) revert InvalidQueryRange();
uint256 tokenIdsIdx;
uint256 stopLimit = _nextTokenId();
// Set `start = max(start, _startTokenId())`.if (start < _startTokenId()) {
start = _startTokenId();
}
// Set `stop = min(stop, stopLimit)`.if (stop > stopLimit) {
stop = stopLimit;
}
uint256 tokenIdsMaxLength = balanceOf(owner);
// Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,// to cater for cases where `balanceOf(owner)` is too big.if (start < stop) {
uint256 rangeLength = stop - start;
if (rangeLength < tokenIdsMaxLength) {
tokenIdsMaxLength = rangeLength;
}
} else {
tokenIdsMaxLength =0;
}
uint256[] memory tokenIds =newuint256[](tokenIdsMaxLength);
if (tokenIdsMaxLength ==0) {
return tokenIds;
}
// We need to call `explicitOwnershipOf(start)`,// because the slot at `start` may not be initialized.
TokenOwnership memory ownership = explicitOwnershipOf(start);
address currOwnershipAddr;
// If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.// `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.if (!ownership.burned) {
currOwnershipAddr = ownership.addr;
}
for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr !=address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
// Downsize the array to fit.assembly {
mstore(tokenIds, tokenIdsIdx)
}
return tokenIds;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(totalSupply) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K pfp collections should be fine).
*/functiontokensOfOwner(address owner) externalviewoverridereturns (uint256[] memory) {
unchecked {
uint256 tokenIdsIdx;
address currOwnershipAddr;
uint256 tokenIdsLength = balanceOf(owner);
uint256[] memory tokenIds =newuint256[](tokenIdsLength);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr !=address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/interfaceIERC1155UpgradeableisIERC165Upgradeable{
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/eventTransferSingle(addressindexed operator, addressindexedfrom, addressindexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/eventTransferBatch(addressindexed operator,
addressindexedfrom,
addressindexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/eventApprovalForAll(addressindexed account, addressindexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/eventURI(string value, uint256indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/functionbalanceOf(address account, uint256 id) externalviewreturns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/functionbalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
externalviewreturns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/functionsetApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/functionisApprovedForAll(address account, address operator) externalviewreturns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 id,
uint256 amount,
bytescalldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytescalldata data
) external;
}
Contract Source Code
File 10 of 19: IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165Upgradeable{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 11 of 19: IERC721A.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.1.0// Creator: Chiru Labspragmasolidity ^0.8.4;/**
* @dev Interface of an ERC721A compliant contract.
*/interfaceIERC721A{
/**
* The caller must own the token or be an approved operator.
*/errorApprovalCallerNotOwnerNorApproved();
/**
* The token does not exist.
*/errorApprovalQueryForNonexistentToken();
/**
* The caller cannot approve to their own address.
*/errorApproveToCaller();
/**
* Cannot query the balance for the zero address.
*/errorBalanceQueryForZeroAddress();
/**
* Cannot mint to the zero address.
*/errorMintToZeroAddress();
/**
* The quantity of tokens minted must be more than zero.
*/errorMintZeroQuantity();
/**
* The token does not exist.
*/errorOwnerQueryForNonexistentToken();
/**
* The caller must own the token or be an approved operator.
*/errorTransferCallerNotOwnerNorApproved();
/**
* The token must be owned by `from`.
*/errorTransferFromIncorrectOwner();
/**
* Cannot safely transfer to a contract that does not implement the ERC721Receiver interface.
*/errorTransferToNonERC721ReceiverImplementer();
/**
* Cannot transfer to the zero address.
*/errorTransferToZeroAddress();
/**
* The token does not exist.
*/errorURIQueryForNonexistentToken();
/**
* The `quantity` minted with ERC2309 exceeds the safety limit.
*/errorMintERC2309QuantityExceedsLimit();
/**
* The `extraData` cannot be set on an unintialized ownership slot.
*/errorOwnershipNotInitializedForExtraData();
structTokenOwnership {
// The address of the owner.address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.uint64 startTimestamp;
// Whether the token has been burned.bool burned;
// Arbitrary data similar to `startTimestamp` that can be set through `_extraData`.uint24 extraData;
}
/**
* @dev Returns the total amount of tokens stored by the contract.
*
* Burned tokens are calculated here, use `_totalMinted()` if you want to count just minted tokens.
*/functiontotalSupply() externalviewreturns (uint256);
// ==============================// IERC165// ==============================/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
// ==============================// IERC721// ==============================/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytescalldata data
) external;
/**
* @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.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
// ==============================// IERC721Metadata// ==============================/**
* @dev Returns the token collection name.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the token collection symbol.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/functiontokenURI(uint256 tokenId) externalviewreturns (stringmemory);
// ==============================// IERC2309// ==============================/**
* @dev Emitted when tokens in `fromTokenId` to `toTokenId` (inclusive) is transferred from `from` to `to`,
* as defined in the ERC2309 standard. See `_mintERC2309` for more details.
*/eventConsecutiveTransfer(uint256indexed fromTokenId, uint256 toTokenId, addressindexedfrom, addressindexed to);
}
Contract Source Code
File 12 of 19: IERC721ABurnable.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.1.0// Creator: Chiru Labspragmasolidity ^0.8.4;import'../IERC721A.sol';
/**
* @dev Interface of an ERC721ABurnable compliant contract.
*/interfaceIERC721ABurnableisIERC721A{
/**
* @dev Burns `tokenId`. See {ERC721A-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/functionburn(uint256 tokenId) external;
}
Contract Source Code
File 13 of 19: IERC721AQueryable.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.1.0// Creator: Chiru Labspragmasolidity ^0.8.4;import'../IERC721A.sol';
/**
* @dev Interface of an ERC721AQueryable compliant contract.
*/interfaceIERC721AQueryableisIERC721A{
/**
* Invalid query range (`start` >= `stop`).
*/errorInvalidQueryRange();
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
* - `addr` = `address(0)`
* - `startTimestamp` = `0`
* - `burned` = `false`
*
* If the `tokenId` is burned:
* - `addr` = `<Address of owner before token was burned>`
* - `startTimestamp` = `<Timestamp when token was burned>`
* - `burned = `true`
*
* Otherwise:
* - `addr` = `<Address of owner>`
* - `startTimestamp` = `<Timestamp of start of ownership>`
* - `burned = `false`
*/functionexplicitOwnershipOf(uint256 tokenId) externalviewreturns (TokenOwnership memory);
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/functionexplicitOwnershipsOf(uint256[] memory tokenIds) externalviewreturns (TokenOwnership[] memory);
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start` < `stop`
*/functiontokensOfOwnerIn(address owner,
uint256 start,
uint256 stop
) externalviewreturns (uint256[] memory);
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(totalSupply) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K pfp collections should be fine).
*/functiontokensOfOwner(address owner) externalviewreturns (uint256[] memory);
}
Contract Source Code
File 14 of 19: Merkle.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;libraryMerkle{
functioncheckMembership(bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytesmemory proof
) internalpurereturns (bool) {
require(proof.length%32==0, "Invalid proof length");
uint256 proofHeight = proof.length/32;
// Proof of size n means, height of the tree is n+1.// In a tree of height n+1, max #leafs possible is 2 ^ nrequire(index <2**proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i =32; i <= proof.length; i +=32) {
assembly {
proofElement :=mload(add(proof, i))
}
if (index %2==0) {
computedHash =keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash =keccak256(abi.encodePacked(proofElement, computedHash));
}
index = index /2;
}
return computedHash == rootHash;
}
}
Contract Source Code
File 15 of 19: MerklePatriciaProof.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import {RLPReader} from"./RLPReader.sol";
libraryMerklePatriciaProof{
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/functionverify(bytesmemory value,
bytesmemory encodedPath,
bytesmemory rlpParentNodes,
bytes32 root
) internalpurereturns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytesmemory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr =0;
bytesmemory path = _getNibbleArray(encodedPath);
if (path.length==0) {
returnfalse;
}
for (uint256 i =0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
returnfalse;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey !=keccak256(currentNode)) {
returnfalse;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length==17) {
if (pathPtr == path.length) {
if (keccak256(RLPReader.toBytes(currentNodeList[16])) ==keccak256(value)) {
returntrue;
} else {
returnfalse;
}
}
uint8 nextPathNibble =uint8(path[pathPtr]);
if (nextPathNibble >16) {
returnfalse;
}
nodeKey =bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble]));
pathPtr +=1;
} elseif (currentNodeList.length==2) {
uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr);
if (pathPtr + traversed == path.length) {
//leaf nodeif (keccak256(RLPReader.toBytes(currentNodeList[1])) ==keccak256(value)) {
returntrue;
} else {
returnfalse;
}
}
//extension nodeif (traversed ==0) {
returnfalse;
}
pathPtr += traversed;
nodeKey =bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
returnfalse;
}
}
}
function_nibblesToTraverse(bytesmemory encodedPartialPath,
bytesmemory path,
uint256 pathPtr
) privatepurereturns (uint256) {
uint256 len =0;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath// and slicedPath have elements that are each one hex character (1 nibble)bytesmemory partialPath = _getNibbleArray(encodedPartialPath);
bytesmemory slicedPath =newbytes(partialPath.length);
// pathPtr counts nibbles in path// partialPath.length is a number of nibblesfor (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) ==keccak256(slicedPath)) {
len = partialPath.length;
} else {
len =0;
}
return len;
}
// bytes b must be hp encodedfunction_getNibbleArray(bytesmemory b) internalpurereturns (bytesmemory) {
bytesmemory nibbles ="";
if (b.length>0) {
uint8 offset;
uint8 hpNibble =uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble ==1|| hpNibble ==3) {
nibbles =newbytes(b.length*2-1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset =1;
} else {
nibbles =newbytes(b.length*2-2);
offset =0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset +2, b);
}
}
return nibbles;
}
function_getNthNibbleOfBytes(uint256 n, bytesmemory str) privatepurereturns (bytes1) {
returnbytes1(n %2==0 ? uint8(str[n /2]) /0x10 : uint8(str[n /2]) %0x10);
}
}
Contract Source Code
File 16 of 19: MerkleProof.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (utils/cryptography/MerkleProof.sol)pragmasolidity ^0.8.0;/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/libraryMerkleProof{
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/functionverify(bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internalpurereturns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/functionprocessProof(bytes32[] memory proof, bytes32 leaf) internalpurereturns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i =0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function_efficientHash(bytes32 a, bytes32 b) privatepurereturns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value :=keccak256(0x00, 0x40)
}
}
}
Contract Source Code
File 17 of 19: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 18 of 19: RLPReader.sol
/*
* @author Hamdi Allam hamdi.allam97@gmail.com
* Please reach out with any questions or concerns
*/pragmasolidity ^0.8.0;libraryRLPReader{
uint8constant STRING_SHORT_START =0x80;
uint8constant STRING_LONG_START =0xb8;
uint8constant LIST_SHORT_START =0xc0;
uint8constant LIST_LONG_START =0xf8;
uint8constant WORD_SIZE =32;
structRLPItem {
uint256 len;
uint256 memPtr;
}
structIterator {
RLPItem item; // Item that's being iterated over.uint256 nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/functionnext(Iterator memoryself) internalpurereturns (RLPItem memory) {
require(hasNext(self));
uint256 ptr =self.nextPtr;
uint256 itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/functionhasNext(Iterator memoryself) internalpurereturns (bool) {
RLPItem memory item =self.item;
returnself.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/functiontoRlpItem(bytesmemory item) internalpurereturns (RLPItem memory) {
uint256 memPtr;
assembly {
memPtr :=add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/functioniterator(RLPItem memoryself) internalpurereturns (Iterator memory) {
require(isList(self));
uint256 ptr =self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/functionrlpLen(RLPItem memory item) internalpurereturns (uint256) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/functionpayloadLen(RLPItem memory item) internalpurereturns (uint256) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/functiontoList(RLPItem memory item) internalpurereturns (RLPItem[] memory) {
require(isList(item));
uint256 items = numItems(item);
RLPItem[] memory result =new RLPItem[](items);
uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 dataLen;
for (uint256 i =0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.functionisList(RLPItem memory item) internalpurereturns (bool) {
if (item.len ==0) returnfalse;
uint8 byte0;
uint256 memPtr = item.memPtr;
assembly {
byte0 :=byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) returnfalse;
returntrue;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/functionrlpBytesKeccak256(RLPItem memory item) internalpurereturns (bytes32) {
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result :=keccak256(ptr, len)
}
return result;
}
functionpayloadLocation(RLPItem memory item) internalpurereturns (uint256, uint256) {
uint256 offset = _payloadOffset(item.memPtr);
uint256 memPtr = item.memPtr + offset;
uint256 len = item.len - offset; // data lengthreturn (memPtr, len);
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/functionpayloadKeccak256(RLPItem memory item) internalpurereturns (bytes32) {
(uint256 memPtr, uint256 len) = payloadLocation(item);
bytes32 result;
assembly {
result :=keccak256(memPtr, len)
}
return result;
}
/** RLPItem conversions into data types **/// @returns raw rlp encoding in bytesfunctiontoRlpBytes(RLPItem memory item) internalpurereturns (bytesmemory) {
bytesmemory result =newbytes(item.len);
if (result.length==0) return result;
uint256 ptr;
assembly {
ptr :=add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered truefunctiontoBoolean(RLPItem memory item) internalpurereturns (bool) {
require(item.len ==1);
uint256 result;
uint256 memPtr = item.memPtr;
assembly {
result :=byte(0, mload(memPtr))
}
return result ==0 ? false : true;
}
functiontoAddress(RLPItem memory item) internalpurereturns (address) {
// 1 byte for the length prefixrequire(item.len ==21);
returnaddress(uint160(toUint(item)));
}
functiontoUint(RLPItem memory item) internalpurereturns (uint256) {
require(item.len >0&& item.len <=33);
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset;
uint256 result;
uint256 memPtr = item.memPtr + offset;
assembly {
result :=mload(memPtr)
// shfit to the correct location if neccesaryiflt(len, 32) {
result :=div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte lengthfunctiontoUintStrict(RLPItem memory item) internalpurereturns (uint256) {
// one byte prefixrequire(item.len ==33);
uint256 result;
uint256 memPtr = item.memPtr +1;
assembly {
result :=mload(memPtr)
}
return result;
}
functiontoBytes(RLPItem memory item) internalpurereturns (bytesmemory) {
require(item.len >0);
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset; // data lengthbytesmemory result =newbytes(len);
uint256 destPtr;
assembly {
destPtr :=add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/// @return number of payload items inside an encoded list.functionnumItems(RLPItem memory item) privatepurereturns (uint256) {
if (item.len ==0) return0;
uint256 count =0;
uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte lengthfunction_itemLength(uint256 memPtr) privatepurereturns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 :=byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) itemLen =1;
elseif (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START +1;
elseif (byte0 < LIST_SHORT_START) {
assembly {
let byteLen :=sub(byte0, 0xb7) // # of bytes the actual length is
memPtr :=add(memPtr, 1) // skip over the first byte/* 32 byte word size */let dataLen :=div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen :=add(dataLen, add(byteLen, 1))
}
} elseif (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START +1;
} else {
assembly {
let byteLen :=sub(byte0, 0xf7)
memPtr :=add(memPtr, 1)
let dataLen :=div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen :=add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the datafunction_payloadOffset(uint256 memPtr) privatepurereturns (uint256) {
uint256 byte0;
assembly {
byte0 :=byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) return0;
elseif (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return1;
elseif (byte0 < LIST_SHORT_START)
// being explicitreturn byte0 - (STRING_LONG_START -1) +1;
elsereturn byte0 - (LIST_LONG_START -1) +1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/functioncopy(uint256 src,
uint256 dest,
uint256 len
) privatepure{
if (len ==0) return;
// copy as many word sizes as possiblefor (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
if (len ==0) return;
// left over bytes. Mask is used to remove unwanted bytes from the worduint256 mask =256**(WORD_SIZE - len) -1;
assembly {
let srcpart :=and(mload(src), not(mask)) // zero out srclet destpart :=and(mload(dest), mask) // retrieve the bytesmstore(dest, or(destpart, srcpart))
}
}
}
Contract Source Code
File 19 of 19: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)pragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
if (value ==0) {
return"0x00";
}
uint256 temp = value;
uint256 length =0;
while (temp !=0) {
length++;
temp >>=8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _HEX_SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
}