// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)pragmasolidity ^0.8.0;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in// construction, since the code is only stored at the end of the// constructor execution.uint256 size;
assembly {
size :=extcodesize(account)
}
return size >0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Contract Source Code
File 2 of 18: 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 18: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 4 of 18: ERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)pragmasolidity ^0.8.0;import"./IERC721.sol";
import"./IERC721Receiver.sol";
import"./extensions/IERC721Metadata.sol";
import"../../utils/Address.sol";
import"../../utils/Context.sol";
import"../../utils/Strings.sol";
import"../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/contractERC721isContext, ERC165, IERC721, IERC721Metadata{
usingAddressforaddress;
usingStringsforuint256;
// Token namestringprivate _name;
// Token symbolstringprivate _symbol;
// Mapping from token ID to owner addressmapping(uint256=>address) private _owners;
// Mapping owner address to token countmapping(address=>uint256) private _balances;
// Mapping from token ID to approved addressmapping(uint256=>address) private _tokenApprovals;
// Mapping from owner to operator approvalsmapping(address=>mapping(address=>bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC721).interfaceId||
interfaceId ==type(IERC721Metadata).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner) publicviewvirtualoverridereturns (uint256) {
require(owner !=address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewvirtualoverridereturns (address) {
address owner = _owners[tokenId];
require(owner !=address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @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) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length>0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return"";
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicvirtualoverride{
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId) publicviewvirtualoverridereturns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtualoverride{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
//solhint-disable-next-line max-line-lengthrequire(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @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{
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeTransfer(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) internalvirtual{
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/function_exists(uint256 tokenId) internalviewvirtualreturns (bool) {
return _owners[tokenId] !=address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/function_isApprovedOrOwner(address spender, uint256 tokenId) internalviewvirtualreturns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeMint(address to, uint256 tokenId) internalvirtual{
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/function_safeMint(address to,
uint256 tokenId,
bytesmemory _data
) internalvirtual{
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/function_mint(address to, uint256 tokenId) internalvirtual{
require(to !=address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] +=1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId) internalvirtual{
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -=1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/function_transfer(addressfrom,
address to,
uint256 tokenId
) internalvirtual{
require(ERC721.ownerOf(tokenId) ==from, "ERC721: transfer of token that is not own");
require(to !=address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -=1;
_balances[to] +=1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/function_approve(address to, uint256 tokenId) internalvirtual{
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/function_setApprovalForAll(address owner,
address operator,
bool approved
) internalvirtual{
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/function_checkOnERC721Received(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) privatereturns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
returntrue;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* 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, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internalvirtual{}
}
Contract Source Code
File 5 of 18: ERC721A.sol
// SPDX-License-Identifier: MIT// Creator: Chiru Labspragmasolidity ^0.8.4;import'@openzeppelin/contracts/token/ERC721/IERC721.sol';
import'@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import'@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import'@openzeppelin/contracts/utils/Address.sol';
import'@openzeppelin/contracts/utils/Context.sol';
import'@openzeppelin/contracts/utils/Strings.sol';
import'@openzeppelin/contracts/utils/introspection/ERC165.sol';
errorApprovalCallerNotOwnerNorApproved();
errorApprovalQueryForNonexistentToken();
errorApproveToCaller();
errorApprovalToCurrentOwner();
errorBalanceQueryForZeroAddress();
errorMintToZeroAddress();
errorMintZeroQuantity();
errorOwnerQueryForNonexistentToken();
errorTransferCallerNotOwnerNorApproved();
errorTransferFromIncorrectOwner();
errorTransferToNonERC721ReceiverImplementer();
errorTransferToZeroAddress();
errorURIQueryForNonexistentToken();
/**
* @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).
*/contractERC721AisContext, ERC165, IERC721, IERC721Metadata{
usingAddressforaddress;
usingStringsforuint256;
// Compiler will pack this into a single 256bit word.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;
}
// Compiler will pack this into a single 256bit word.structAddressData {
// Realistically, 2**64-1 is more than enough.uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address// (e.g. number of whitelist mint slots used).// If there are multiple variables, please pack them into a uint64.uint64 aux;
}
// The tokenId of the next token to be minted.uint256internal _currentIndex;
// The number of tokens burned.uint256internal _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 _ownershipOf implementation for details.mapping(uint256=> TokenOwnership) internal _ownerships;
// Mapping owner address to address datamapping(address=> AddressData) private _addressData;
// Mapping from token ID to approved addressmapping(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();
}
/**
* To change the starting tokenId, please override this function.
*/function_startTokenId() internalviewvirtualreturns (uint256) {
return0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/functiontotalSupply() publicviewreturns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented// more than _currentIndex - _startTokenId() timesunchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* 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 See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC721).interfaceId||
interfaceId ==type(IERC721Metadata).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner) publicviewoverridereturns (uint256) {
if (owner ==address(0)) revert BalanceQueryForZeroAddress();
returnuint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/function_numberMinted(address owner) internalviewreturns (uint256) {
returnuint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/function_numberBurned(address owner) internalviewreturns (uint256) {
returnuint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/function_getAux(address owner) internalviewreturns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary 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{
_addressData[owner].aux = aux;
}
/**
* 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) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr !=address(0)) {
return ownership;
}
// 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.while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr !=address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewoverridereturns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @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, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return'';
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicoverride{
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner &&!isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @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 == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
_transfer(from, to, tokenId);
}
/**
* @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{
_transfer(from, to, tokenId);
if (to.isContract() &&!_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 &&!_ownerships[tokenId].burned;
}
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.
*
* Emits a {Transfer} event.
*/function_safeMint(address to,
uint256 quantity,
bytesmemory _data
) internal{
_mint(to, quantity, _data, true);
}
/**
* @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.
*/function_mint(address to,
uint256 quantity,
bytesmemory _data,
bool safe
) 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 or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1unchecked {
_addressData[to].balance+=uint64(quantity);
_addressData[to].numberMinted +=uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp =uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protectionif (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @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.
*/function_transfer(addressfrom,
address to,
uint256 tokenId
) private{
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr !=from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() ==from||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to ==address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// 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 {
_addressData[from].balance-=1;
_addressData[to].balance+=1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp =uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.uint256 nextTokenId = tokenId +1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr ==address(0)) {
// This will suffice for checking _exists(nextTokenId),// as a burned slot cannot contain the zero address.if (nextTokenId != _currentIndex) {
nextSlot.addr =from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is 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{
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
addressfrom= prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() ==from||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// 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 {
AddressData storage addressData = _addressData[from];
addressData.balance-=1;
addressData.numberBurned +=1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr =from;
currSlot.startTimestamp =uint64(block.timestamp);
currSlot.burned =true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.uint256 nextTokenId = tokenId +1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr ==address(0)) {
// This will suffice for checking _exists(nextTokenId),// as a burned slot cannot contain the zero address.if (nextTokenId != _currentIndex) {
nextSlot.addr =from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
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 Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/function_approve(address to,
uint256 tokenId,
address owner
) private{
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @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 IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @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{}
}
Contract Source Code
File 6 of 18: ERC721AQueryable.sol
// SPDX-License-Identifier: MIT// Creator: Chiru Labspragmasolidity ^0.8.4;import'../ERC721A.sol';
errorInvalidQueryRange();
/**
* @title ERC721A Queryable
* @dev ERC721A subclass with convenience query functions.
*/abstractcontractERC721AQueryableisERC721A{
/**
* @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) publicviewreturns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _currentIndex) {
return ownership;
}
ownership = _ownerships[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) externalviewreturns (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
) externalviewreturns (uint256[] memory) {
unchecked {
if (start >= stop) revert InvalidQueryRange();
uint256 tokenIdsIdx;
uint256 stopLimit = _currentIndex;
// Set `start = max(start, _startTokenId())`.if (start < _startTokenId()) {
start = _startTokenId();
}
// Set `stop = min(stop, _currentIndex)`.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 = _ownerships[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) externalviewreturns (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 = _ownerships[i];
if (ownership.burned) {
continue;
}
if (ownership.addr !=address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
}
Contract Source Code
File 7 of 18: ERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)pragmasolidity ^0.8.0;import"../ERC721.sol";
import"./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/abstractcontractERC721EnumerableisERC721, IERC721Enumerable{
// Mapping from owner to list of owned token IDsmapping(address=>mapping(uint256=>uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens listmapping(uint256=>uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumerationuint256[] private _allTokens;
// Mapping from token id to position in the allTokens arraymapping(uint256=>uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(IERC165, ERC721) returns (bool) {
return interfaceId ==type(IERC721Enumerable).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) publicviewvirtualoverridereturns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/functiontokenByIndex(uint256 index) publicviewvirtualoverridereturns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* 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, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internalvirtualoverride{
super._beforeTokenTransfer(from, to, tokenId);
if (from==address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} elseif (from!= to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to ==address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} elseif (to !=from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @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 = ERC721.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(addressfrom, 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 = ERC721.balanceOf(from) -1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessaryif (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 arraydelete _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 arraydelete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// 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}.
*/interfaceIERC165{
/**
* @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 10 of 18: IERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @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`, 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @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 if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
/**
* @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;
}
Contract Source Code
File 11 of 18: IERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)pragmasolidity ^0.8.0;import"../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/interfaceIERC721EnumerableisIERC721{
/**
* @dev Returns the total amount of tokens stored by the contract.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) externalviewreturns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/functiontokenByIndex(uint256 index) externalviewreturns (uint256);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
Contract Source Code
File 14 of 18: MerkleProof.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (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.
*/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 Merklee 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 =keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash =keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
Contract Source Code
File 15 of 18: Oil.sol
// SPDX-License-Identifier: Unlicensepragmasolidity ^0.8.7;/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation./// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)/// Inspired by Solmate: https://github.com/Rari-Capital/solmate/// Developed originally by 0xBasset/// Upgraded by <redacted>/// Additions by Tsuki Labs: https://tsukiyomigroup.com/ :)contractOil{
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/addresspublic impl_;
addresspublic ruler;
addresspublic treasury;
addresspublic uniPair;
addresspublic weth;
uint256public totalSupply;
uint256public startingTime;
uint256public baseTax;
uint256public minSwap;
boolpublic paused;
boolpublic swapping;
ERC721Like public habibi;
mapping(address=>uint256) public balanceOf;
mapping(address=>mapping(address=>uint256)) public allowance;
mapping(address=>bool) public isMinter;
mapping(uint256=>uint256) public claims;
mapping(address=> Staker) internal stakers;
uint256public sellFee;
uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _status;
uint256public doubleBaseTimestamp;
structHabibi {
uint256 stakedTimestamp;
uint256 tokenId;
}
structStaker {
Habibi[] habibiz;
uint256 lastClaim;
}
structRescueable {
address revoker;
bool adminAllowedAsRevoker;
}
mapping(address=> Rescueable) private rescueable;
addresspublic sushiswapPair;
IUniswapV2Router02 public uniswapV2Router;
IUniswapV2Router02 public sushiswapV2Router;
mapping(address=>bool) public excludedFromFees;
mapping(address=>bool) public blockList;
structRoyalStaker {
Royal[] royals;
}
structRoyal {
uint256 stakedTimestamp;
uint256 tokenId;
}
ERC721Like public royals;
uint256[] frozenHabibiz;
mapping(uint256=>address) public claimedRoyals;
mapping(address=> RoyalStaker) internal royalStakers;
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/functionname() externalpurereturns (stringmemory) {
return"OIL";
}
functionsymbol() externalpurereturns (stringmemory) {
return"OIL";
}
functiondecimals() externalpurereturns (uint8) {
return18;
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/functioninitialize(address habibi_, address treasury_) external{
require(msg.sender== ruler, "NOT ALLOWED TO RULE");
ruler =msg.sender;
treasury = treasury_;
habibi = ERC721Like(habibi_);
sellFee =15000;
_status = _NOT_ENTERED;
}
functionapprove(address spender, uint256 value) externalreturns (bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
returntrue;
}
functiontransfer(address to, uint256 value) externalwhenNotPausedreturns (bool) {
require(!blockList[msg.sender], "Address Blocked");
_transfer(msg.sender, to, value);
returntrue;
}
functiontransferFrom(addressfrom,
address to,
uint256 value
) externalwhenNotPausedreturns (bool) {
require(!blockList[msg.sender], "Address Blocked");
if (allowance[from][msg.sender] !=type(uint256).max) {
allowance[from][msg.sender] -= value;
}
_transfer(from, to, value);
returntrue;
}
/*///////////////////////////////////////////////////////////////
STAKING
//////////////////////////////////////////////////////////////*/function_tokensOfStaker(address staker_, bool royals_) internalviewreturns (uint256[] memory) {
uint256 i;
if (royals_) {
uint256[] memory tokenIds =newuint256[](royalStakers[staker_].royals.length);
for (i =0; i < royalStakers[staker_].royals.length; i++) {
tokenIds[i] = royalStakers[staker_].royals[i].tokenId;
}
return tokenIds;
} else {
uint256[] memory tokenIds =newuint256[](stakers[staker_].habibiz.length);
for (i =0; i < stakers[staker_].habibiz.length; i++) {
tokenIds[i] = stakers[staker_].habibiz[i].tokenId;
}
return tokenIds;
}
}
functionhabibizOfStaker(address staker_) publicviewreturns (uint256[] memory) {
return _tokensOfStaker(staker_, false);
}
functionroyalsOfStaker(address staker_) publicviewreturns (uint256[] memory) {
return _tokensOfStaker(staker_, true);
}
functionallStakedOfStaker(address staker_) publicviewreturns (uint256[] memory, uint256[] memory) {
return (habibizOfStaker(staker_), royalsOfStaker(staker_));
}
functionstake(uint256[] memory habibiz_, uint256[] memory royals_) publicwhenNotPaused{
uint256 i;
for (i =0; i < habibiz_.length; i++) {
require(habibi.ownerOf(habibiz_[i]) ==msg.sender, "At least one Habibi is not owned by you.");
habibi.transferFrom(msg.sender, address(this), habibiz_[i]);
stakers[msg.sender].habibiz.push(Habibi(block.timestamp, habibiz_[i]));
}
for (i =0; i < royals_.length; i++) {
require(royals.ownerOf(royals_[i]) ==msg.sender, "At least one Royals is not owned by you.");
royals.transferFrom(msg.sender, address(this), royals_[i]);
royalStakers[msg.sender].royals.push(Royal(block.timestamp, royals_[i]));
}
}
functionstakeAll() externalwhenNotPaused{
uint256[] memory habibizTokenIds = habibi.walletOfOwner(msg.sender);
uint256[] memory royalsTokenIds = royals.tokensOfOwner(msg.sender);
stake(habibizTokenIds, royalsTokenIds);
}
functionisOwnedByStaker(address staker_,
uint256 tokenId_,
bool isRoyal_
) publicviewreturns (bool) {
uint256[] memory tokenIds;
if (isRoyal_) {
tokenIds = royalsOfStaker(staker_);
} else {
tokenIds = habibizOfStaker(staker_);
}
for (uint256 i =0; i < tokenIds.length; i++) {
if (tokenIds[i] == tokenId_) {
returntrue;
}
}
returnfalse;
}
function_unstake(bool habibiz_, bool royals_) internal{
/*
address staker_,
uint256 tokenId_,
uint256 stakedTimestamp_,
bool isRoyal_
*/uint256 i;
uint256 oil;
if (habibiz_) {
uint256[] memory tokenIds =newuint256[](stakers[msg.sender].habibiz.length);
for (i =0; i < tokenIds.length; i++) {
Habibi memory _habibi = stakers[msg.sender].habibiz[i];
habibi.transferFrom(address(this), msg.sender, _habibi.tokenId);
tokenIds[i] = _habibi.tokenId;
oil += _calculateOil(msg.sender, _habibi.tokenId, _habibi.stakedTimestamp, false);
}
_removeHabibizFromStaker(msg.sender, tokenIds);
}
if (royals_) {
uint256[] memory tokenIds =newuint256[](royalStakers[msg.sender].royals.length);
for (i =0; i < tokenIds.length; i++) {
Royal memory _royal = royalStakers[msg.sender].royals[i];
royals.transferFrom(address(this), msg.sender, _royal.tokenId);
tokenIds[i] = _royal.tokenId;
oil += _calculateOil(msg.sender, _royal.tokenId, _royal.stakedTimestamp, true);
}
_removeRoyalsFromStaker(msg.sender, tokenIds);
}
if (oil >0) _claimAmount(msg.sender, oil);
}
function_unstakeByIds(uint256[] memory habibizIds_, uint256[] memory royalsIds_) internal{
uint256 i;
uint256 oil = calculateOilRewards(msg.sender);
if (habibizIds_.length>0) {
uint256[] memory tokenIds =newuint256[](habibizIds_.length);
for (i =0; i < habibizIds_.length; i++) {
require(isOwnedByStaker(msg.sender, habibizIds_[i], false), "Habibi not owned by sender");
habibi.transferFrom(address(this), msg.sender, habibizIds_[i]);
tokenIds[i] = habibizIds_[i];
}
_removeHabibizFromStaker(msg.sender, tokenIds);
}
if (royalsIds_.length>0) {
uint256[] memory tokenIds =newuint256[](royalsIds_.length);
for (i =0; i < tokenIds.length; i++) {
require(isOwnedByStaker(msg.sender, royalsIds_[i], true), "Habibi not owned by sender");
royals.transferFrom(address(this), msg.sender, royalsIds_[i]);
tokenIds[i] = royalsIds_[i];
}
_removeRoyalsFromStaker(msg.sender, tokenIds);
}
if (oil >0) _claimAmount(msg.sender, oil);
}
functionunstakeAllHabibiz() externalwhenNotPaused{
require(stakers[msg.sender].habibiz.length>0, "No Habibiz staked");
_unstake(true, false);
}
functionunstakeAllRoyals() externalwhenNotPaused{
require(royalStakers[msg.sender].royals.length>0, "No Royals staked");
_unstake(false, true);
}
functionunstakeAll() externalwhenNotPaused{
require(
stakers[msg.sender].habibiz.length>0|| royalStakers[msg.sender].royals.length>0,
"No Habibiz or Royals staked"
);
_unstake(true, true);
}
functionunstakeHabibizByIds(uint256[] calldata tokenIds_) externalwhenNotPaused{
_unstakeByIds(tokenIds_, newuint256[](0));
}
functionunstakeRoyalsByIds(uint256[] calldata tokenIds_) externalwhenNotPaused{
_unstakeByIds(newuint256[](0), tokenIds_);
}
function_removeRoyalsFromStaker(address staker_, uint256[] memory tokenIds_) internal{
for (uint256 i =0; i < tokenIds_.length; i++) {
for (uint256 j =0; j < royalStakers[staker_].royals.length; j++) {
if (tokenIds_[i] == royalStakers[staker_].royals[j].tokenId) {
royalStakers[staker_].royals[j] = royalStakers[staker_].royals[
royalStakers[staker_].royals.length-1
];
royalStakers[staker_].royals.pop();
}
}
}
}
function_removeHabibizFromStaker(address staker_, uint256[] memory tokenIds_) internal{
for (uint256 i =0; i < tokenIds_.length; i++) {
for (uint256 j =0; j < stakers[staker_].habibiz.length; j++) {
if (tokenIds_[i] == stakers[staker_].habibiz[j].tokenId) {
stakers[staker_].habibiz[j] = stakers[staker_].habibiz[stakers[staker_].habibiz.length-1];
stakers[staker_].habibiz.pop();
}
}
}
}
functionapproveRescue(address revoker_,
bool confirm_,
bool rescueableByAdmin_
) external{
require(confirm_, "Did not confirm");
require(revoker_ !=address(0), "Revoker cannot be null address");
rescueable[msg.sender] = Rescueable(revoker_, rescueableByAdmin_);
}
functionrevokeRescue(address rescueable_, bool confirm_) external{
if (msg.sender== ruler) {
require(rescueable[rescueable_].adminAllowedAsRevoker, "Admin is not allowed to revoke");
} else {
require(rescueable[rescueable_].revoker ==msg.sender, "Sender is not revoker");
}
require(confirm_, "Did not confirm");
delete rescueable[rescueable_];
}
/*////////////////////////////////////////////////////////////
Sacrifice for Royals
////////////////////////////////////////////////////////////*/functionfreeze(address staker_,
uint256[] calldata habibizIds_,
uint256 royalId_
) externalreturns (bool) {
require(msg.sender==address(royals), "You do not have permission to call this function");
require(
royals.ownerOf(royalId_) ==address(this) && claimedRoyals[royalId_] ==address(0),
"Invalid or claimed token id"
);
uint256[] memory habibiz = habibizOfStaker(staker_);
uint256 count =0;
for (uint256 i =0; i < habibizIds_.length; i++) {
for (uint256 j =0; j < habibiz.length; j++) {
if (habibizIds_[i] == habibiz[j]) {
count++;
frozenHabibiz.push(habibizIds_[i]);
break;
}
}
}
require(habibizIds_.length== count, "Missing staked Habibiz");
_claim(staker_);
_removeHabibizFromStaker(staker_, habibizIds_);
claimedRoyals[royalId_] = staker_;
royalStakers[staker_].royals.push(Royal(block.timestamp, royalId_));
returntrue;
}
/*///////////////////////////////////////////////////////////////
CLAIMING
//////////////////////////////////////////////////////////////*/functionclaim() publicwhenNotPaused{
require(!blockList[msg.sender], "Address Blocked");
_claim(msg.sender);
}
function_claim(address to_) internal{
uint256 oil = calculateOilRewards(to_);
if (oil >0) {
_claimAmount(to_, oil);
}
}
function_claimAmount(address to_, uint256 amount_) internal{
stakers[to_].lastClaim =block.timestamp;
_mint(to_, amount_);
}
/*///////////////////////////////////////////////////////////////
OIL REWARDS
//////////////////////////////////////////////////////////////*/functioncalculateOilRewards(address staker_) publicviewreturns (uint256 oilAmount) {
uint256 balanceBonus = holderBonusPercentage(staker_);
uint256 habibizAmount = stakers[staker_].habibiz.length;
uint256 royalsAmount = royalStakers[staker_].royals.length;
uint256 totalStaked = habibizAmount + royalsAmount;
uint256 royalsBase = getRoyalsBase(staker_);
uint256 lastClaimTimestamp = stakers[staker_].lastClaim;
bool isAnimated;
for (uint256 i =0; i < totalStaked; i++) {
uint256 tokenId;
bool isRoyal;
uint256 stakedTimestamp;
if (i < habibizAmount) {
tokenId = stakers[staker_].habibiz[i].tokenId;
stakedTimestamp = stakers[staker_].habibiz[i].stakedTimestamp;
isAnimated = _isAnimated(tokenId);
} else {
tokenId = royalStakers[staker_].royals[i - habibizAmount].tokenId;
stakedTimestamp = royalStakers[staker_].royals[i - habibizAmount].stakedTimestamp;
isRoyal =true;
}
oilAmount += calculateOilOfToken(
isAnimated,
lastClaimTimestamp,
stakedTimestamp,
balanceBonus,
isRoyal,
royalsBase
);
}
}
function_calculateTimes(uint256 stakedTimestamp_, uint256 lastClaimedTimestamp_)
internalviewreturns (uint256, uint256)
{
if (lastClaimedTimestamp_ < stakedTimestamp_) {
lastClaimedTimestamp_ = stakedTimestamp_;
}
return (block.timestamp- stakedTimestamp_, block.timestamp- lastClaimedTimestamp_);
}
function_calculateOil(address staker_,
uint256 tokenId_,
uint256 stakedTimestamp_,
bool isRoyal_
) internalviewreturns (uint256) {
uint256 balanceBonus = holderBonusPercentage(staker_);
uint256 lastClaimTimestamp = stakers[staker_].lastClaim;
if (isRoyal_) {
return calculateOilOfToken(false, lastClaimTimestamp, stakedTimestamp_, balanceBonus, true, 0);
}
return
calculateOilOfToken(
_isAnimated(tokenId_),
lastClaimTimestamp,
stakedTimestamp_,
balanceBonus,
false,
getRoyalsBase(staker_)
);
}
functioncalculateOilOfToken(bool isAnimated_,
uint256 lastClaimedTimestamp_,
uint256 stakedTimestamp_,
uint256 balanceBonus_,
bool isRoyal_,
uint256 royalsBase
) internalviewreturns (uint256 oil) {
uint256 bonusPercentage;
uint256 baseOilMultiplier =1;
(uint256 stakedTime, uint256 unclaimedTime) = _calculateTimes(stakedTimestamp_, lastClaimedTimestamp_);
if (stakedTime >=15days|| stakedTimestamp_ <= doubleBaseTimestamp) {
baseOilMultiplier =2;
}
if (stakedTime >=90days) {
bonusPercentage =100;
} else {
for (uint256 i =2; i <4; i++) {
uint256 timeRequirement =15days* i;
if (timeRequirement >0&& timeRequirement <= stakedTime) {
bonusPercentage = bonusPercentage +15;
} else {
break;
}
}
}
if (isRoyal_) {
oil = (unclaimedTime * royalsBase *1ether) /1days;
} elseif (isAnimated_) {
oil = (unclaimedTime *2500ether* baseOilMultiplier) /1days;
} else {
bonusPercentage = bonusPercentage + balanceBonus_;
oil = (unclaimedTime *500ether* baseOilMultiplier) /1days;
}
oil += ((oil * bonusPercentage) /100);
}
functiongetRoyalsBase(address staker_) publicviewreturns (uint256 base) {
if (royalStakers[staker_].royals.length==1) {
base =12000;
} elseif (royalStakers[staker_].royals.length==2) {
base =13500;
} elseif (royalStakers[staker_].royals.length>=3) {
base =15000;
} else {
base =0;
}
return base;
}
functionstaker(address staker_) publicviewreturns (Staker memory, RoyalStaker memory) {
return (stakers[staker_], royalStakers[staker_]);
}
/*///////////////////////////////////////////////////////////////
OIL PRIVILEGE
//////////////////////////////////////////////////////////////*/functionmint(address to, uint256 value) externalonlyMinter{
_mint(to, value);
}
functionburn(addressfrom, uint256 value) externalonlyMinter{
_burn(from, value);
}
/*///////////////////////////////////////////////////////////////
Ruler Function
//////////////////////////////////////////////////////////////*/functionsetDoubleBaseTimestamp(uint256 doubleBaseTimestamp_) externalonlyRuler{
doubleBaseTimestamp = doubleBaseTimestamp_;
}
functionsetMinter(address minter_, bool canMint_) externalonlyRuler{
isMinter[minter_] = canMint_;
}
functionsetRuler(address ruler_) externalonlyRuler{
ruler = ruler_;
}
functionsetPaused(bool paused_) externalonlyRuler{
paused = paused_;
}
functionsetHabibiAddress(address habibiAddress_) externalonlyRuler{
habibi = ERC721Like(habibiAddress_);
}
functionsetRoyalsAddress(address royalsAddress_) externalonlyRuler{
royals = ERC721Like(royalsAddress_);
}
functionsetSellFee(uint256 fee_) externalonlyRuler{
sellFee = fee_;
}
functionsetUniswapV2Router(address router_) externalonlyRuler{
uniswapV2Router = IUniswapV2Router02(router_);
}
functionsetSushiswapV2Router(address router_) externalonlyRuler{
sushiswapV2Router = IUniswapV2Router02(router_);
}
functionsetV2Routers(address uniswapRouter_, address sushiswapRouter_) externalonlyRuler{
uniswapV2Router = IUniswapV2Router02(uniswapRouter_);
sushiswapV2Router = IUniswapV2Router02(sushiswapRouter_);
}
functionsetUniPair(address uniPair_) externalonlyRuler{
uniPair = uniPair_;
}
functionsetSushiswapPair(address sushiswapPair_) externalonlyRuler{
sushiswapPair = sushiswapPair_;
}
functionsetPairs(address uniPair_, address sushiswapPair_) externalonlyRuler{
uniPair = uniPair_;
sushiswapPair = sushiswapPair_;
}
functionexcludeFromFees(address[] calldata addresses_, bool[] calldata excluded_) externalonlyRuler{
for (uint256 i =0; i < addresses_.length; i++) {
excludedFromFees[addresses_[i]] = excluded_[i];
}
}
functionblockOrUnblockAddresses(address[] calldata addresses_, bool[] calldata blocked_) externalonlyRuler{
for (uint256 i =0; i < addresses_.length; i++) {
blockList[addresses_[i]] = blocked_[i];
}
}
/// emergencyfunctionrescue(address staker_,
address to_,
uint256[] calldata habibiIds_,
uint256[] calldata royalIds_
) externalonlyRuler{
require(rescueable[staker_].revoker !=address(0), "User has not opted-in for rescue");
if (habibiIds_.length>0) {
for (uint256 i =0; i < habibiIds_.length; i++) {
require(isOwnedByStaker(staker_, habibiIds_[i], false), "Habibi TokenID not found");
stakers[to_].habibiz.push(Habibi(block.timestamp, habibiIds_[i]));
}
_removeHabibizFromStaker(staker_, habibiIds_);
}
if (royalIds_.length>0) {
for (uint256 i =0; i < royalIds_.length; i++) {
require(isOwnedByStaker(staker_, royalIds_[i], true), "Royal TokenID not found");
royalStakers[to_].royals.push(Royal(block.timestamp, royalIds_[i]));
}
_removeRoyalsFromStaker(staker_, royalIds_);
}
}
/*///////////////////////////////////////////////////////////////
INTERNAL UTILS
//////////////////////////////////////////////////////////////*/function_getRouterFromPair(address pairAddress_) internalviewreturns (IUniswapV2Router02) {
return pairAddress_ ==address(uniPair) ? uniswapV2Router : sushiswapV2Router;
}
function_transfer(addressfrom,
address to,
uint256 value
) internal{
require(balanceOf[from] >= value, "ERC20: transfer amount exceeds balance");
uint256 tax;
bool shouldTax = ((to == uniPair && balanceOf[to] !=0) || (to == sushiswapPair && balanceOf[to] !=0)) &&!swapping;
if (shouldTax &&!excludedFromFees[from]) {
tax = (value * sellFee) /100_000;
if (tax >0) {
balanceOf[address(this)] += tax;
swapTokensForEth(to, tax, treasury);
}
}
uint256 taxedAmount = value - tax;
balanceOf[from] -= value;
balanceOf[to] += taxedAmount;
emit Transfer(from, to, taxedAmount);
}
functionswapTokensForEth(address pairAddress_,
uint256 amountIn_,
address to_
) privatelockTheSwap{
IUniswapV2Router02 router = _getRouterFromPair(pairAddress_);
IERC20(address(this)).approve(address(router), amountIn_);
address[] memory path =newaddress[](2);
path[0] =address(this);
path[1] = router.WETH(); // or router.WETH();
router.swapExactTokensForETHSupportingFeeOnTransferTokens(amountIn_, 1, path, to_, block.timestamp);
}
function_mint(address to, uint256 value) internal{
totalSupply += value;
// This is safe because the sum of all user// balances can't exceed type(uint256).max!unchecked {
balanceOf[to] += value;
}
emit Transfer(address(0), to, value);
}
function_burn(addressfrom, uint256 value) internal{
balanceOf[from] -= value;
// This is safe because a user won't ever// have a balance larger than totalSupply!unchecked {
totalSupply -= value;
}
emit Transfer(from, address(0), value);
}
functionholderBonusPercentage(address staker_) publicviewreturns (uint256) {
uint256 balance = stakers[staker_].habibiz.length+ royalStakers[staker_].royals.length*8;
if (balance <5) return0;
if (balance <10) return15;
if (balance <20) return25;
return35;
}
function_isAnimated(uint256 id_) internalpurereturns (bool animated) {
return
id_ ==40||
id_ ==108||
id_ ==169||
id_ ==191||
id_ ==246||
id_ ==257||
id_ ==319||
id_ ==386||
id_ ==496||
id_ ==562||
id_ ==637||
id_ ==692||
id_ ==832||
id_ ==942||
id_ ==943||
id_ ==957||
id_ ==1100||
id_ ==1108||
id_ ==1169||
id_ ==1178||
id_ ==1627||
id_ ==1706||
id_ ==1843||
id_ ==1884||
id_ ==2137||
id_ ==2158||
id_ ==2165||
id_ ==2214||
id_ ==2232||
id_ ==2238||
id_ ==2508||
id_ ==2629||
id_ ==2863||
id_ ==3055||
id_ ==3073||
id_ ==3280||
id_ ==3297||
id_ ==3322||
id_ ==3327||
id_ ==3361||
id_ ==3411||
id_ ==3605||
id_ ==3639||
id_ ==3774||
id_ ==4250||
id_ ==4267||
id_ ==4302||
id_ ==4362||
id_ ==4382||
id_ ==4397||
id_ ==4675||
id_ ==4707||
id_ ==4863;
}
/*///////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/modifieronlyMinter() {
require(isMinter[msg.sender], "FORBIDDEN TO MINT OR BURN");
_;
}
modifieronlyRuler() {
require(msg.sender== ruler, "NOT ALLOWED TO RULE");
_;
}
modifierwhenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
modifierlockTheSwap() {
swapping =true;
_;
swapping =false;
}
modifiernonReentrant() {
// On the first call to nonReentrant, _notEntered will be truerequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4) {
return ERC721Like.onERC721Received.selector;
}
}
interfaceERC721Like{
functionbalanceOf(address holder_) externalviewreturns (uint256);
functionownerOf(uint256 id_) externalviewreturns (address);
functionwalletOfOwner(address _owner) externalviewreturns (uint256[] calldata);
functiontokensOfOwner(address owner) externalviewreturns (uint256[] memory);
functionisApprovedForAll(address operator_, address address_) externalviewreturns (bool);
functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
interfaceIERC20{
functiontotalSupply() externalviewreturns (uint256);
functionbalanceOf(address account) externalviewreturns (uint256);
functiontransfer(address recipient, uint256 amount) externalreturns (bool);
functionallowance(address owner, address spender) externalviewreturns (uint256);
functionapprove(address spender, uint256 amount) externalreturns (bool);
functiontransferFrom(address sender,
address recipient,
uint256 amount
) externalreturns (bool);
eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
eventApproval(addressindexed owner, addressindexed spender, uint256 value);
}
interfaceIUniswapV2Router02{
functionWETH() externalpurereturns (address);
functionswapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
interfaceUniPairLike{
functiontoken0() externalreturns (address);
functionswap(uint256 amount0Out,
uint256 amount1Out,
address to,
bytescalldata data
) external;
functiongetReserves()
externalviewreturns (uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
Contract Source Code
File 16 of 18: 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 17 of 18: Royals.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.7;import"@openzeppelin/contracts/access/Ownable.sol";
import"erc721a/contracts/extensions/ERC721AQueryable.sol";
import"@openzeppelin/contracts/utils/Strings.sol";
import"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import"./Oil.sol";
import"./Habibi.sol";
contractRoyalsisERC721AQueryable, Ownable{
enumSaleState {
Disabled,
AllowlistSale,
PublicSale
}
Oil publicconstant OIL = Oil(0x5Fe8C486B5f216B9AD83C12958d8A03eb3fD5060);
Habibi publicconstant HABIBIZ = Habibi(0x98a0227E99E7AF0f1f0D51746211a245c3B859c2);
uint256publicconstant MAX_SUPPLY =300;
uint256public availableSupply =100;
uint256public maxClaimPerWallet =1;
uint256public amountRequiredToBurn =8;
bytes32public root;
stringpublic baseURI;
stringpublic notRevealedUri;
SaleState public saleState = SaleState.Disabled;
eventSaleStateChanged(uint256 previousState, uint256 nextState, uint256 timestamp);
eventClaimedRoyal(addressindexed staker, uint256[] frozenTokenIds, uint256indexed royalId);
// solhint-disable-next-line no-empty-blocksconstructor(stringmemory baseURI_) ERC721A("Royals", "ROYALS") {
baseURI = baseURI_;
}
modifierisClaimingActive() {
require(saleState != SaleState.Disabled, "Claiming is not active");
_;
}
modifierisInAllowlist(address address_, bytes32[] calldata proof_) {
require(saleState == SaleState.PublicSale || _verify(_leaf(address_), proof_), "Not in allowlist");
_;
}
//++++++++// Public functions//++++++++functionsacrificeAndClaim(uint256[] calldata habibizTokenIds_,
uint256 royalTokenId_,
bytes32[] calldata proof_
) externalisClaimingActiveisInAllowlist(msg.sender, proof_) {
require(habibizTokenIds_.length>= amountRequiredToBurn, "Must burn at least required amount of habibiz");
require(
habibizTokenIds_.length% amountRequiredToBurn ==0,
"Must burn multiples of required amount of habibiz"
);
setApprovalForAll(address(OIL), true);
// Count number of potential mintsuint256 numToClaim = habibizTokenIds_.length/ amountRequiredToBurn;
// O(N^2) loop, its more gas efficient to use this than a mapping with addresses, due to lower storage usagefor (uint256 i =0; i < habibizTokenIds_.length; i++) {
for (uint256 j = i +1; j < habibizTokenIds_.length; j++) {
require(habibizTokenIds_[i] != habibizTokenIds_[j], "No duplicates allowed");
}
}
// Now that we have amount a user can mint, lets ensure they can mint given maximum mints per wallet, and batch sizerequire(numToClaim <= availableSupply, "available supply reached");
// Ensure user doesn't already exceed maximum number of mintsrequire(_getAux(msg.sender) < maxClaimPerWallet, "Not have enough mints available");
// Ensure user doesn't exceed maxmium allowable number of mintsrequire(uint256(_getAux(msg.sender)) + numToClaim <= maxClaimPerWallet, "Would exceed maximum allowable mints");
// Burns staked habibis and if there was an issue burning, it revertsrequire(OIL.freeze(msg.sender, habibizTokenIds_, royalTokenId_), "Failed to claim Royal");
_setAux(_msgSender(), uint64(numToClaim) + _getAux(msg.sender)); // Kfish - moved this to happen before mintemit ClaimedRoyal(msg.sender, habibizTokenIds_, royalTokenId_);
}
//++++++++// Owner functions//++++++++functionmintToStakingContract(uint256 quantity_) externalonlyOwner{
require(quantity_ <= availableSupply, "Would exceed available supply");
_safeMint(address(OIL), quantity_);
}
functionsetRoot(bytes32 root_) externalonlyOwner{
root = root_;
}
// Sale functionsfunctionsetSaleState(uint256 state_) externalonlyOwner{
require(state_ <3, "Invalid state");
uint256 prevState =uint256(saleState);
saleState = SaleState(state_);
emit SaleStateChanged(prevState, state_, block.timestamp);
}
functionsetAvailableSupply(uint256 availableSupply_) externalonlyOwner{
require(availableSupply_ <= MAX_SUPPLY, "Would exceed max supply");
availableSupply = availableSupply_;
}
functionsetmaxClaimPerWallet(uint256 maxClaimPerWallet_) publiconlyOwner{
maxClaimPerWallet = maxClaimPerWallet_;
}
functionsetBaseURI(stringmemory newBaseURI_) publiconlyOwner{
baseURI = newBaseURI_;
}
functionsetNotRevealedURI(stringmemory notRevealedURI_) publiconlyOwner{
notRevealedUri = notRevealedURI_;
}
functionwithdraw() publicpayableonlyOwner{
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) =payable(msg.sender).call{value: address(this).balance}("");
require(success, "Withdrawal failed");
}
functionsetAmountRequiredToBurn(uint256 amountRequiredToBurn_) publiconlyOwner{
amountRequiredToBurn = amountRequiredToBurn_;
}
//++++++++// Internal functions//++++++++function_leaf(address account_) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked(account_));
}
function_verify(bytes32 leaf_, bytes32[] memory proof_) internalviewreturns (bool) {
return MerkleProof.verify(proof_, root, leaf_);
}
function_baseURI() internalviewvirtualoverridereturns (stringmemory) {
return baseURI;
}
function_startTokenId() internalviewvirtualoverridereturns (uint256) {
return1;
}
//++++++++// Override functions//++++++++functiontokenURI(uint256 tokenId) publicviewvirtualoverridereturns (stringmemory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if (bytes(baseURI).length==0) {
return notRevealedUri;
}
returnstring(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json"));
}
}
Contract Source Code
File 18 of 18: 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);
}
}