// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC2981 NFT Royalty Standard implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC2981.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/common/ERC2981.sol)
abstract contract ERC2981 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The royalty fee numerator exceeds the fee denominator.
error RoyaltyOverflow();
/// @dev The royalty receiver cannot be the zero address.
error RoyaltyReceiverIsZeroAddress();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The default royalty info is given by:
/// ```
/// let packed := sload(_ERC2981_MASTER_SLOT_SEED)
/// let receiver := shr(96, packed)
/// let royaltyFraction := xor(packed, shl(96, receiver))
/// ```
///
/// The per token royalty info is given by.
/// ```
/// mstore(0x00, tokenId)
/// mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
/// let packed := sload(keccak256(0x00, 0x40))
/// let receiver := shr(96, packed)
/// let royaltyFraction := xor(packed, shl(96, receiver))
/// ```
uint256 private constant _ERC2981_MASTER_SLOT_SEED = 0xaa4ec00224afccfdb7;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC2981 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Checks that `_feeDenominator` is non-zero.
constructor() {
require(_feeDenominator() != 0, "Fee denominator cannot be zero.");
}
/// @dev Returns the denominator for the royalty amount.
/// Defaults to 10000, which represents fees in basis points.
/// Override this function to return a custom amount if needed.
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/// @dev Returns true if this contract implements the interface defined by `interfaceId`.
/// See: https://eips.ethereum.org/EIPS/eip-165
/// This function call must use less than 30000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let s := shr(224, interfaceId)
// ERC165: 0x01ffc9a7, ERC2981: 0x2a55205a.
result := or(eq(s, 0x01ffc9a7), eq(s, 0x2a55205a))
}
}
/// @dev Returns the `receiver` and `royaltyAmount` for `tokenId` sold at `salePrice`.
function royaltyInfo(uint256 tokenId, uint256 salePrice)
public
view
virtual
returns (address receiver, uint256 royaltyAmount)
{
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
let packed := sload(keccak256(0x00, 0x40))
receiver := shr(96, packed)
if iszero(receiver) {
packed := sload(mload(0x20))
receiver := shr(96, packed)
}
let x := salePrice
let y := xor(packed, shl(96, receiver)) // `feeNumerator`.
// Overflow check, equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
// Out-of-gas revert. Should not be triggered in practice, but included for safety.
returndatacopy(returndatasize(), returndatasize(), mul(y, gt(x, div(not(0), y))))
royaltyAmount := div(mul(x, y), feeDenominator)
}
}
/// @dev Sets the default royalty `receiver` and `feeNumerator`.
///
/// Requirements:
/// - `receiver` must not be the zero address.
/// - `feeNumerator` must not be greater than the fee denominator.
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
feeNumerator := shr(160, shl(160, feeNumerator))
if gt(feeNumerator, feeDenominator) {
mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.
revert(0x1c, 0x04)
}
let packed := shl(96, receiver)
if iszero(packed) {
mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.
revert(0x1c, 0x04)
}
sstore(_ERC2981_MASTER_SLOT_SEED, or(packed, feeNumerator))
}
}
/// @dev Sets the default royalty `receiver` and `feeNumerator` to zero.
function _deleteDefaultRoyalty() internal virtual {
/// @solidity memory-safe-assembly
assembly {
sstore(_ERC2981_MASTER_SLOT_SEED, 0)
}
}
/// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId`.
///
/// Requirements:
/// - `receiver` must not be the zero address.
/// - `feeNumerator` must not be greater than the fee denominator.
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator)
internal
virtual
{
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
feeNumerator := shr(160, shl(160, feeNumerator))
if gt(feeNumerator, feeDenominator) {
mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.
revert(0x1c, 0x04)
}
let packed := shl(96, receiver)
if iszero(packed) {
mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.
revert(0x1c, 0x04)
}
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
sstore(keccak256(0x00, 0x40), or(packed, feeNumerator))
}
}
/// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId` to zero.
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
sstore(keccak256(0x00, 0x40), 0)
}
}
}
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.3.0
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './IERC721A.sol';
/**
* @dev Interface of ERC721 token receiver.
*/
interface ERC721A__IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC721A
*
* @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
* Non-Fungible Token Standard, including the Metadata extension.
* Optimized for lower gas during batch mints.
*
* Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
* starting from `_startTokenId()`.
*
* The `_sequentialUpTo()` function can be overriden to enable spot mints
* (i.e. non-consecutive mints) for `tokenId`s greater than `_sequentialUpTo()`.
*
* Assumptions:
*
* - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
* - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is IERC721A {
// Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
struct TokenApprovalRef {
address value;
}
// =============================================================
// CONSTANTS
// =============================================================
// Mask of an entry in packed address data.
uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
// The bit position of `numberMinted` in packed address data.
uint256 private constant _BITPOS_NUMBER_MINTED = 64;
// The bit position of `numberBurned` in packed address data.
uint256 private constant _BITPOS_NUMBER_BURNED = 128;
// The bit position of `aux` in packed address data.
uint256 private constant _BITPOS_AUX = 192;
// Mask of all 256 bits in packed address data except the 64 bits for `aux`.
uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
// The bit position of `startTimestamp` in packed ownership.
uint256 private constant _BITPOS_START_TIMESTAMP = 160;
// The bit mask of the `burned` bit in packed ownership.
uint256 private constant _BITMASK_BURNED = 1 << 224;
// The bit position of the `nextInitialized` bit in packed ownership.
uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
// The bit mask of the `nextInitialized` bit in packed ownership.
uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
// The bit position of `extraData` in packed ownership.
uint256 private constant _BITPOS_EXTRA_DATA = 232;
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
// The mask of the lower 160 bits for addresses.
uint256 private constant _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.
uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
// The `Transfer` event signature is given by:
// `keccak256(bytes("Transfer(address,address,uint256)"))`.
bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
// =============================================================
// STORAGE
// =============================================================
// The next token ID to be minted.
uint256 private _currentIndex;
// The number of tokens burned.
uint256 private _burnCounter;
// Token name
string private _name;
// Token symbol
string private _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 => TokenApprovalRef) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// The amount of tokens minted above `_sequentialUpTo()`.
// We call these spot mints (i.e. non-sequential mints).
uint256 private _spotMinted;
// =============================================================
// CONSTRUCTOR
// =============================================================
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
if (_sequentialUpTo() < _startTokenId()) _revert(SequentialUpToTooSmall.selector);
}
// =============================================================
// TOKEN COUNTING OPERATIONS
// =============================================================
/**
* @dev Returns the starting token ID for sequential mints.
*
* Override this function to change the starting token ID for sequential mints.
*
* Note: The value returned must never change after any tokens have been minted.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Returns the maximum token ID (inclusive) for sequential mints.
*
* Override this function to return a value less than 2**256 - 1,
* but greater than `_startTokenId()`, to enable spot (non-sequential) mints.
*
* Note: The value returned must never change after any tokens have been minted.
*/
function _sequentialUpTo() internal view virtual returns (uint256) {
return type(uint256).max;
}
/**
* @dev Returns the next token ID to be minted.
*/
function _nextTokenId() internal view virtual returns (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}.
*/
function totalSupply() public view virtual override returns (uint256 result) {
// Counter underflow is impossible as `_burnCounter` cannot be incremented
// more than `_currentIndex + _spotMinted - _startTokenId()` times.
unchecked {
// With spot minting, the intermediate `result` can be temporarily negative,
// and the computation must be unchecked.
result = _currentIndex - _burnCounter - _startTokenId();
if (_sequentialUpTo() != type(uint256).max) result += _spotMinted;
}
}
/**
* @dev Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view virtual returns (uint256 result) {
// Counter underflow is impossible as `_currentIndex` does not decrement,
// and it is initialized to `_startTokenId()`.
unchecked {
result = _currentIndex - _startTokenId();
if (_sequentialUpTo() != type(uint256).max) result += _spotMinted;
}
}
/**
* @dev Returns the total number of tokens burned.
*/
function _totalBurned() internal view virtual returns (uint256) {
return _burnCounter;
}
/**
* @dev Returns the total number of tokens that are spot-minted.
*/
function _totalSpotMinted() internal view virtual returns (uint256) {
return _spotMinted;
}
// =============================================================
// ADDRESS DATA OPERATIONS
// =============================================================
/**
* @dev Returns the number of tokens in `owner`'s account.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
if (owner == address(0)) _revert(BalanceQueryForZeroAddress.selector);
return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (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) internal view returns (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) internal view returns (uint64) {
return uint64(_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 virtual {
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;
}
// =============================================================
// IERC165
// =============================================================
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
// The interface IDs are constants representing the first 4 bytes
// of the XOR of all function selectors in the interface.
// See: [ERC165](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.
}
// =============================================================
// IERC721Metadata
// =============================================================
/**
* @dev Returns the token collection name.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the token collection symbol.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) _revert(URIQueryForNonexistentToken.selector);
string memory baseURI = _baseURI();
return bytes(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() internal view virtual returns (string memory) {
return '';
}
// =============================================================
// OWNERSHIPS OPERATIONS
// =============================================================
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return address(uint160(_packedOwnershipOf(tokenId)));
}
/**
* @dev Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around over time.
*/
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
/**
* @dev Returns the unpacked `TokenOwnership` struct at `index`.
*/
function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnerships[index]);
}
/**
* @dev Returns whether the ownership slot at `index` is initialized.
* An uninitialized slot does not necessarily mean that the slot has no owner.
*/
function _ownershipIsInitialized(uint256 index) internal view virtual returns (bool) {
return _packedOwnerships[index] != 0;
}
/**
* @dev Initializes the ownership slot minted at `index` for efficiency purposes.
*/
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == uint256(0)) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* @dev Returns the packed ownership data of `tokenId`.
*/
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
if (tokenId > _sequentialUpTo()) {
if (_packedOwnershipExists(packed)) return packed;
_revert(OwnerQueryForNonexistentToken.selector);
}
// If the data at the starting slot does not exist, start the scan.
if (packed == uint256(0)) {
if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
// Invariant:
// There will always be an initialized ownership slot
// (i.e. `ownership.addr != address(0) && ownership.burned == false`)
// before an unintialized ownership slot
// (i.e. `ownership.addr == address(0) && ownership.burned == false`)
// Hence, `tokenId` will not underflow.
//
// We can directly compare the packed value.
// If the address is zero, packed will be zero.
for (;;) {
unchecked {
packed = _packedOwnerships[--tokenId];
}
if (packed == uint256(0)) continue;
if (packed & _BITMASK_BURNED == uint256(0)) return packed;
// Otherwise, the token is burned, and we must revert.
// This handles the case of batch burned tokens, where only the burned bit
// of the starting slot is set, and remaining slots are left uninitialized.
_revert(OwnerQueryForNonexistentToken.selector);
}
}
// Otherwise, the data exists and we can skip the scan.
// This is possible because we have already achieved the target condition.
// This saves 2143 gas on transfers of initialized tokens.
// If the token is not burned, return `packed`. Otherwise, revert.
if (packed & _BITMASK_BURNED == uint256(0)) return packed;
}
_revert(OwnerQueryForNonexistentToken.selector);
}
/**
* @dev Returns the unpacked `TokenOwnership` struct from `packed`.
*/
function _unpackedOwnership(uint256 packed) private pure returns (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);
}
/**
* @dev Packs ownership data into a single uint256.
*/
function _packOwnershipData(address owner, uint256 flags) private view returns (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 Returns the `nextInitialized` flag set if `quantity` equals 1.
*/
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.
assembly {
// `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
// =============================================================
// APPROVAL OPERATIONS
// =============================================================
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
*/
function approve(address to, uint256 tokenId) public payable virtual override {
_approve(to, tokenId, true);
}
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) _revert(ApprovalQueryForNonexistentToken.selector);
return _tokenApprovals[tokenId].value;
}
/**
* @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.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
}
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @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. See {_mint}.
*/
function _exists(uint256 tokenId) internal view virtual returns (bool result) {
if (_startTokenId() <= tokenId) {
if (tokenId > _sequentialUpTo()) return _packedOwnershipExists(_packedOwnerships[tokenId]);
if (tokenId < _currentIndex) {
uint256 packed;
while ((packed = _packedOwnerships[tokenId]) == uint256(0)) --tokenId;
result = packed & _BITMASK_BURNED == uint256(0);
}
}
}
/**
* @dev Returns whether `packed` represents a token that exists.
*/
function _packedOwnershipExists(uint256 packed) private pure returns (bool result) {
assembly {
// The following is equivalent to `owner != address(0) && burned == false`.
// Symbolically tested.
result := gt(and(packed, _BITMASK_ADDRESS), and(packed, _BITMASK_BURNED))
}
}
/**
* @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
*/
function _isSenderApprovedOrOwner(
uint256 approvedAddressValue,
uint256 ownerMasked,
uint256 msgSenderMasked
) private pure returns (bool result) {
assembly {
result := or(eq(msgSenderMasked, ownerMasked), eq(msgSenderMasked, approvedAddressValue))
}
}
/**
* @dev Returns the storage slot and value for the approved address of `tokenId` casted to a uint256.
*/
function _getApprovedSlotAndValue(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, uint256 approvedAddressValue)
{
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
// The following is equivalent to `approvedAddressValue = uint160(_tokenApprovals[tokenId].value)`.
assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddressValue := sload(approvedAddressSlot)
}
}
// =============================================================
// TRANSFER OPERATIONS
// =============================================================
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
uint256 fromMasked = uint160(from);
if (uint160(prevOwnershipPacked) != fromMasked) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, uint256 approvedAddressValue) = _getApprovedSlotAndValue(tokenId);
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isSenderApprovedOrOwner(approvedAddressValue, fromMasked, uint160(_msgSenderERC721A())))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddressValue {
sstore(approvedAddressSlot, 0) // Equivalent to `delete _tokenApprovals[tokenId]`.
}
}
// 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 == uint256(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] == uint256(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;
}
}
}
}
// Mask to the lower 160 bits, in case the upper bits somehow aren't clean.
uint256 toMasked = uint160(to);
assembly {
// Emit the `Transfer` event.
log4(
0, // Start of data (0, since no data).
0, // End of data (0, since no data).
_TRANSFER_EVENT_SIGNATURE, // Signature.
fromMasked, // `from`.
toMasked, // `to`.
tokenId // `tokenId`.
)
}
if (toMasked == uint256(0)) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @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.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public payable virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
}
/**
* @dev Equivalent to `_batchTransferFrom(from, to, tokenIds)`.
*/
function _batchTransferFrom(
address from,
address to,
uint256[] memory tokenIds
) internal virtual {
_batchTransferFrom(address(0), from, to, tokenIds);
}
/**
* @dev Transfers `tokenIds` in batch from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenIds` tokens must be owned by `from`.
* - `tokenIds` must be strictly ascending.
* - If `by` is not `from`, it must be approved to move these tokens
* by either {approve} or {setApprovalForAll}.
*
* `by` is the address that to check token approval for.
* If token approval check is not needed, pass in `address(0)` for `by`.
*
* Emits a {Transfer} event for each transfer.
*/
function _batchTransferFrom(
address by,
address from,
address to,
uint256[] memory tokenIds
) internal virtual {
uint256 byMasked = uint160(by);
uint256 fromMasked = uint160(from);
uint256 toMasked = uint160(to);
// Disallow transfer to zero address.
if (toMasked == uint256(0)) _revert(TransferToZeroAddress.selector);
// Whether `by` may transfer the tokens.
bool mayTransfer = _orERC721A(byMasked == uint256(0), byMasked == fromMasked) || isApprovedForAll(from, by);
// Early return if `tokenIds` is empty.
if (tokenIds.length == uint256(0)) return;
// The next `tokenId` to be minted (i.e. `_nextTokenId()`).
uint256 end = _currentIndex;
// Pointer to start and end (exclusive) of `tokenIds`.
(uint256 ptr, uint256 ptrEnd) = _mdataERC721A(tokenIds);
uint256 prevTokenId;
uint256 prevOwnershipPacked;
unchecked {
do {
uint256 tokenId = _mloadERC721A(ptr);
uint256 miniBatchStart = tokenId;
// Revert `tokenId` is out of bounds.
if (_orERC721A(tokenId < _startTokenId(), end <= tokenId))
_revert(OwnerQueryForNonexistentToken.selector);
// Revert if `tokenIds` is not strictly ascending.
if (prevOwnershipPacked != 0)
if (tokenId <= prevTokenId) _revert(TokenIdsNotStrictlyAscending.selector);
// Scan backwards for an initialized packed ownership slot.
// ERC721A's invariant guarantees that there will always be an initialized slot as long as
// the start of the backwards scan falls within `[_startTokenId() .. _nextTokenId())`.
for (uint256 j = tokenId; (prevOwnershipPacked = _packedOwnerships[j]) == uint256(0); ) --j;
// If the initialized slot is burned, revert.
if (prevOwnershipPacked & _BITMASK_BURNED != 0) _revert(OwnerQueryForNonexistentToken.selector);
// Check that `tokenId` is owned by `from`.
if (uint160(prevOwnershipPacked) != fromMasked) _revert(TransferFromIncorrectOwner.selector);
do {
(uint256 approvedAddressSlot, uint256 approvedAddressValue) = _getApprovedSlotAndValue(tokenId);
_beforeTokenTransfers(address(uint160(fromMasked)), address(uint160(toMasked)), tokenId, 1);
// Revert if the sender is not authorized to transfer the token.
if (!mayTransfer)
if (byMasked != approvedAddressValue) _revert(TransferCallerNotOwnerNorApproved.selector);
assembly {
if approvedAddressValue {
sstore(approvedAddressSlot, 0) // Equivalent to `delete _tokenApprovals[tokenId]`.
}
// Emit the `Transfer` event.
log4(0, 0, _TRANSFER_EVENT_SIGNATURE, fromMasked, toMasked, tokenId)
}
if (_mloadERC721A(ptr += 0x20) != ++tokenId) break;
if (ptr == ptrEnd) break;
} while (_packedOwnerships[tokenId] == uint256(0));
// Updates tokenId:
// - `address` to the next owner.
// - `startTimestamp` to the timestamp of transferring.
// - `burned` to `false`.
// - `nextInitialized` to `false`, as it is optional.
_packedOwnerships[miniBatchStart] = _packOwnershipData(
address(uint160(toMasked)),
_nextExtraData(address(uint160(fromMasked)), address(uint160(toMasked)), prevOwnershipPacked)
);
uint256 miniBatchLength = tokenId - miniBatchStart;
// Update the address data.
_packedAddressData[address(uint160(fromMasked))] -= miniBatchLength;
_packedAddressData[address(uint160(toMasked))] += miniBatchLength;
// Initialize the next slot if needed.
if (tokenId != end)
if (_packedOwnerships[tokenId] == uint256(0)) _packedOwnerships[tokenId] = prevOwnershipPacked;
// Perform the after hook for the batch.
_afterTokenTransfers(
address(uint160(fromMasked)),
address(uint160(toMasked)),
miniBatchStart,
miniBatchLength
);
// Set the `prevTokenId` for checking that the `tokenIds` is strictly ascending.
prevTokenId = tokenId - 1;
} while (ptr != ptrEnd);
}
}
/**
* @dev Safely transfers `tokenIds` in batch from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenIds` tokens must be owned by `from`.
* - If `by` is not `from`, it must be approved to move these tokens
* by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each transferred token.
*
* `by` is the address that to check token approval for.
* If token approval check is not needed, pass in `address(0)` for `by`.
*
* Emits a {Transfer} event for each transfer.
*/
function _safeBatchTransferFrom(
address by,
address from,
address to,
uint256[] memory tokenIds,
bytes memory _data
) internal virtual {
_batchTransferFrom(by, from, to, tokenIds);
unchecked {
if (to.code.length != 0) {
for ((uint256 ptr, uint256 ptrEnd) = _mdataERC721A(tokenIds); ptr != ptrEnd; ptr += 0x20) {
if (!_checkContractOnERC721Received(from, to, _mloadERC721A(ptr), _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
}
}
}
}
/**
* @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(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @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(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* `from` - Previous owner of the given token ID.
* `to` - Target address that will receive the token.
* `tokenId` - Token ID to be transferred.
* `_data` - Optional data to send along with the call.
*
* Returns whether the call correctly returned the expected magic value.
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == uint256(0)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
assembly {
revert(add(32, reason), mload(reason))
}
}
}
// =============================================================
// MINT OPERATIONS
// =============================================================
/**
* @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 virtual {
uint256 startTokenId = _currentIndex;
if (quantity == uint256(0)) _revert(MintZeroQuantity.selector);
_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:
// - `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)
);
// Updates:
// - `balance += quantity`.
// - `numberMinted += quantity`.
//
// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
// Mask to the lower 160 bits, in case the upper bits somehow aren't clean.
uint256 toMasked = uint160(to);
if (toMasked == uint256(0)) _revert(MintToZeroAddress.selector);
uint256 end = startTokenId + quantity;
uint256 tokenId = startTokenId;
if (end - 1 > _sequentialUpTo()) _revert(SequentialMintExceedsLimit.selector);
do {
assembly {
// Emit the `Transfer` event.
log4(
0, // Start of data (0, since no data).
0, // End of data (0, since no data).
_TRANSFER_EVENT_SIGNATURE, // Signature.
0, // `address(0)`.
toMasked, // `to`.
tokenId // `tokenId`.
)
}
// The `!=` check ensures that large values of `quantity`
// that overflows uint256 will make the loop run out of gas.
} 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 virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) _revert(MintToZeroAddress.selector);
if (quantity == uint256(0)) _revert(MintZeroQuantity.selector);
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) _revert(MintERC2309QuantityExceedsLimit.selector);
_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)
);
if (startTokenId + quantity - 1 > _sequentialUpTo()) _revert(SequentialMintExceedsLimit.selector);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, 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,
bytes memory _data
) internal virtual {
_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.selector);
}
} while (index < end);
// This prevents reentrancy to `_safeMint`.
// It does not prevent reentrancy to `_safeMintSpot`.
if (_currentIndex != end) revert();
}
}
}
/**
* @dev Equivalent to `_safeMint(to, quantity, '')`.
*/
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, '');
}
/**
* @dev Mints a single token at `tokenId`.
*
* Note: A spot-minted `tokenId` that has been burned can be re-minted again.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` must be greater than `_sequentialUpTo()`.
* - `tokenId` must not exist.
*
* Emits a {Transfer} event for each mint.
*/
function _mintSpot(address to, uint256 tokenId) internal virtual {
if (tokenId <= _sequentialUpTo()) _revert(SpotMintTokenIdTooSmall.selector);
uint256 prevOwnershipPacked = _packedOwnerships[tokenId];
if (_packedOwnershipExists(prevOwnershipPacked)) _revert(TokenAlreadyExists.selector);
_beforeTokenTransfers(address(0), to, tokenId, 1);
// Overflows are incredibly unrealistic.
// The `numberMinted` for `to` is incremented by 1, and has a max limit of 2**64 - 1.
// `_spotMinted` is incremented by 1, and has a max limit of 2**256 - 1.
unchecked {
// Updates:
// - `address` to the owner.
// - `startTimestamp` to the timestamp of minting.
// - `burned` to `false`.
// - `nextInitialized` to `true` (as `quantity == 1`).
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_nextInitializedFlag(1) | _nextExtraData(address(0), to, prevOwnershipPacked)
);
// Updates:
// - `balance += 1`.
// - `numberMinted += 1`.
//
// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += (1 << _BITPOS_NUMBER_MINTED) | 1;
// Mask to the lower 160 bits, in case the upper bits somehow aren't clean.
uint256 toMasked = uint160(to);
if (toMasked == uint256(0)) _revert(MintToZeroAddress.selector);
assembly {
// Emit the `Transfer` event.
log4(
0, // Start of data (0, since no data).
0, // End of data (0, since no data).
_TRANSFER_EVENT_SIGNATURE, // Signature.
0, // `address(0)`.
toMasked, // `to`.
tokenId // `tokenId`.
)
}
++_spotMinted;
}
_afterTokenTransfers(address(0), to, tokenId, 1);
}
/**
* @dev Safely mints a single token at `tokenId`.
*
* Note: A spot-minted `tokenId` that has been burned can be re-minted again.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}.
* - `tokenId` must be greater than `_sequentialUpTo()`.
* - `tokenId` must not exist.
*
* See {_mintSpot}.
*
* Emits a {Transfer} event.
*/
function _safeMintSpot(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mintSpot(to, tokenId);
unchecked {
if (to.code.length != 0) {
uint256 currentSpotMinted = _spotMinted;
if (!_checkContractOnERC721Received(address(0), to, tokenId, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
// This prevents reentrancy to `_safeMintSpot`.
// It does not prevent reentrancy to `_safeMint`.
if (_spotMinted != currentSpotMinted) revert();
}
}
}
/**
* @dev Equivalent to `_safeMintSpot(to, tokenId, '')`.
*/
function _safeMintSpot(address to, uint256 tokenId) internal virtual {
_safeMintSpot(to, tokenId, '');
}
// =============================================================
// APPROVAL OPERATIONS
// =============================================================
/**
* @dev Equivalent to `_approve(to, tokenId, false)`.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_approve(to, tokenId, false);
}
/**
* @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:
*
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
bool approvalCheck
) internal virtual {
address owner = ownerOf(tokenId);
if (approvalCheck && _msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
_revert(ApprovalCallerNotOwnerNorApproved.selector);
}
_tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
// =============================================================
// BURN OPERATIONS
// =============================================================
/**
* @dev Equivalent to `_burn(tokenId, false)`.
*/
function _burn(uint256 tokenId) internal virtual {
_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) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
uint256 fromMasked = uint160(prevOwnershipPacked);
address from = address(uint160(fromMasked));
(uint256 approvedAddressSlot, uint256 approvedAddressValue) = _getApprovedSlotAndValue(tokenId);
if (approvalCheck) {
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isSenderApprovedOrOwner(approvedAddressValue, fromMasked, uint160(_msgSenderERC721A())))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddressValue {
sstore(approvedAddressSlot, 0) // Equivalent to `delete _tokenApprovals[tokenId]`.
}
}
// 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 == uint256(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] == uint256(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 + _spotMinted` times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Destroys `tokenIds`.
* Approvals are not cleared when tokenIds are burned.
*
* Requirements:
*
* - `tokenIds` must exist.
* - `tokenIds` must be strictly ascending.
* - `by` must be approved to burn these tokens by either {approve} or {setApprovalForAll}.
*
* `by` is the address that to check token approval for.
* If token approval check is not needed, pass in `address(0)` for `by`.
*
* Emits a {Transfer} event for each token burned.
*/
function _batchBurn(address by, uint256[] memory tokenIds) internal virtual {
// Early return if `tokenIds` is empty.
if (tokenIds.length == uint256(0)) return;
// The next `tokenId` to be minted (i.e. `_nextTokenId()`).
uint256 end = _currentIndex;
// Pointer to start and end (exclusive) of `tokenIds`.
(uint256 ptr, uint256 ptrEnd) = _mdataERC721A(tokenIds);
uint256 prevOwnershipPacked;
address prevTokenOwner;
uint256 prevTokenId;
bool mayBurn;
unchecked {
do {
uint256 tokenId = _mloadERC721A(ptr);
uint256 miniBatchStart = tokenId;
// Revert `tokenId` is out of bounds.
if (_orERC721A(tokenId < _startTokenId(), end <= tokenId))
_revert(OwnerQueryForNonexistentToken.selector);
// Revert if `tokenIds` is not strictly ascending.
if (prevOwnershipPacked != 0)
if (tokenId <= prevTokenId) _revert(TokenIdsNotStrictlyAscending.selector);
// Scan backwards for an initialized packed ownership slot.
// ERC721A's invariant guarantees that there will always be an initialized slot as long as
// the start of the backwards scan falls within `[_startTokenId() .. _nextTokenId())`.
for (uint256 j = tokenId; (prevOwnershipPacked = _packedOwnerships[j]) == uint256(0); ) --j;
// If the initialized slot is burned, revert.
if (prevOwnershipPacked & _BITMASK_BURNED != 0) _revert(OwnerQueryForNonexistentToken.selector);
address tokenOwner = address(uint160(prevOwnershipPacked));
if (tokenOwner != prevTokenOwner) {
prevTokenOwner = tokenOwner;
mayBurn = _orERC721A(by == address(0), tokenOwner == by) || isApprovedForAll(tokenOwner, by);
}
do {
(uint256 approvedAddressSlot, uint256 approvedAddressValue) = _getApprovedSlotAndValue(tokenId);
_beforeTokenTransfers(tokenOwner, address(0), tokenId, 1);
// Revert if the sender is not authorized to transfer the token.
if (!mayBurn)
if (uint160(by) != approvedAddressValue) _revert(TransferCallerNotOwnerNorApproved.selector);
assembly {
if approvedAddressValue {
sstore(approvedAddressSlot, 0) // Equivalent to `delete _tokenApprovals[tokenId]`.
}
// Emit the `Transfer` event.
log4(0, 0, _TRANSFER_EVENT_SIGNATURE, and(_BITMASK_ADDRESS, tokenOwner), 0, tokenId)
}
if (_mloadERC721A(ptr += 0x20) != ++tokenId) break;
if (ptr == ptrEnd) break;
} while (_packedOwnerships[tokenId] == uint256(0));
// Updates tokenId:
// - `address` to the same `tokenOwner`.
// - `startTimestamp` to the timestamp of transferring.
// - `burned` to `true`.
// - `nextInitialized` to `false`, as it is optional.
_packedOwnerships[miniBatchStart] = _packOwnershipData(
tokenOwner,
_BITMASK_BURNED | _nextExtraData(tokenOwner, address(0), prevOwnershipPacked)
);
uint256 miniBatchLength = tokenId - miniBatchStart;
// Update the address data.
_packedAddressData[tokenOwner] += (miniBatchLength << _BITPOS_NUMBER_BURNED) - miniBatchLength;
// Initialize the next slot if needed.
if (tokenId != end)
if (_packedOwnerships[tokenId] == uint256(0)) _packedOwnerships[tokenId] = prevOwnershipPacked;
// Perform the after hook for the batch.
_afterTokenTransfers(tokenOwner, address(0), miniBatchStart, miniBatchLength);
// Set the `prevTokenId` for checking that the `tokenIds` is strictly ascending.
prevTokenId = tokenId - 1;
} while (ptr != ptrEnd);
// Increment the overall burn counter.
_burnCounter += tokenIds.length;
}
}
// =============================================================
// EXTRA DATA OPERATIONS
// =============================================================
/**
* @dev Directly sets the extra data for the ownership data `index`.
*/
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == uint256(0)) _revert(OwnershipNotInitializedForExtraData.selector);
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 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(
address from,
address to,
uint24 previousExtraData
) internal view virtual returns (uint24) {}
/**
* @dev Returns the next extra data for the packed ownership data.
* The returned result is shifted into position.
*/
function _nextExtraData(
address from,
address to,
uint256 prevOwnershipPacked
) private view returns (uint256) {
uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
}
// =============================================================
// PRIVATE HELPERS
// =============================================================
/**
* @dev Returns a memory pointer to the start of `a`'s data.
*/
function _mdataERC721A(uint256[] memory a) private pure returns (uint256 start, uint256 end) {
assembly {
start := add(a, 0x20)
end := add(start, shl(5, mload(a)))
}
}
/**
* @dev Returns the uint256 at `p` in memory.
*/
function _mloadERC721A(uint256 p) private pure returns (uint256 result) {
assembly {
result := mload(p)
}
}
/**
* @dev Branchless boolean or.
*/
function _orERC721A(bool a, bool b) private pure returns (bool result) {
assembly {
result := or(iszero(iszero(a)), iszero(iszero(b)))
}
}
// =============================================================
// OTHER OPERATIONS
// =============================================================
/**
* @dev Returns the message sender (defaults to `msg.sender`).
*
* If you are writing GSN compatible contracts, you need to override this function.
*/
function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
}
/**
* @dev Converts a uint256 to its ASCII string decimal representation.
*/
function _toString(uint256 value) internal pure virtual returns (string memory str) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
let m := add(mload(0x40), 0xa0)
// Update the free memory pointer to allocate.
mstore(0x40, m)
// Assign the `str` to the end.
str := sub(m, 0x20)
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// prettier-ignore
for { let temp := value } 1 {} {
str := sub(str, 1)
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
// prettier-ignore
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
/**
* @dev For more efficient reverts.
*/
function _revert(bytes4 errorSelector) internal pure {
assembly {
mstore(0x00, errorSelector)
revert(0x00, 0x04)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {ICreatorToken} from "../interfaces/ICreatorToken.sol";
import {ITransferValidator721} from "../interfaces/ITransferValidator721.sol";
/**
* @title ERC721TransferValidator
* @author 0xkuwabatake (@0xkuwabatake)
* Modified from ProjectOpenSea's ERC721TransferValidator:
* https://github.com/ProjectOpenSea/seadrop/blob/main/src/lib/ERC721TransferValidator.sol
* @notice Abstract contract for ERC721 transfer validation.
* @dev Designed for ERC721 contracts implementing OpenSea's creator fee standard:
* https://docs.opensea.io/docs/creator-fee-enforcement#creator-token-standard
*/
abstract contract ERC721TransferValidator is ICreatorToken {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev ERC721 transfer validation function signature.
bytes4 private constant _ERC721_TRANSFER_VALIDATION_FUNCTION_SIGNATURE = 0xcaee23ea;
/// @dev Interface ID for ICreatorToken.
bytes4 internal constant INTERFACE_ID_ICREATORTOKEN = 0xad0d7f6c;
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @dev Address of the transfer validator contract.
ITransferValidator721 internal _transferValidator;
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ICreatorToken
function getTransferValidator() public view override returns (address) {
return address(_transferValidator);
}
/// @inheritdoc ICreatorToken
function getTransferValidationFunction()
public
pure
override
returns (bytes4 functionSignature, bool isViewFunction)
{
functionSignature = _ERC721_TRANSFER_VALIDATION_FUNCTION_SIGNATURE;
isViewFunction = true;
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTION
//////////////////////////////////////////////////////////////*/
/**
* @dev Sets the transfer validator.
* @param validator The address of the transfer validator contract.
* @notice Passing `address(0)` removes the current transfer validator.
*/
function _setTransferValidator(address validator) internal {
emit TransferValidatorUpdated(address(_transferValidator), validator);
_transferValidator = ITransferValidator721(validator);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title IBasedOnchainOwner
* @dev Interface for accessing the `balanceOf` function from the following onchain NFT collections
* released on the Base network: Based Onchain Dinos, Tiny Dino Punks, and 1Bit Chonks
*/
interface IBasedOnchainOwner {
/**
* @notice Retrieves the token balance of a specified address.
* @param owner The address whose balance is to be queried.
* @return The number of tokens owned by the specified address.
*/
function balanceOf(address owner) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @title ICreatorToken
* @author 0xkuwabatake
* @notice Interface for a minimal creator token standard, allowing integration with
* OpenSea's creator fee enforcement. Reference:
* https://docs.opensea.io/docs/creator-fee-enforcement#creator-token-standard
*/
interface ICreatorToken {
/**
* @dev Emitted when the transfer `validator` contract address is updated.
* @param oldValidator The previous validator contract address.
* @param newValidator The new validator contract address.
*/
event TransferValidatorUpdated(address oldValidator, address newValidator);
/**
* @notice Retrieves the current transfer validator contract address.
* @return validator The address of the current transfer validator contract.
* @custom:note A zero address indicates no validator is set.
*/
function getTransferValidator() external view returns (address validator);
/**
* @notice Retrieves information about the transfer validation function.
* @return functionSignature The selector of the implemented validation function.
* @return isViewFunction Indicates whether the validation function is a view function.
*/
function getTransferValidationFunction()
external
view
returns (bytes4 functionSignature, bool isViewFunction);
/**
* @notice Updates the transfer validator contract address.
* @param validator The address of the new validator contract.
*/
function setTransferValidator(address validator) external;
}
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.3.0
// Creator: Chiru Labs
pragma solidity ^0.8.4;
/**
* @dev Interface of ERC721A.
*/
interface IERC721A {
/**
* The caller must own the token or be an approved operator.
*/
error ApprovalCallerNotOwnerNorApproved();
/**
* The token does not exist.
*/
error ApprovalQueryForNonexistentToken();
/**
* Cannot query the balance for the zero address.
*/
error BalanceQueryForZeroAddress();
/**
* Cannot mint to the zero address.
*/
error MintToZeroAddress();
/**
* The quantity of tokens minted must be more than zero.
*/
error MintZeroQuantity();
/**
* The token does not exist.
*/
error OwnerQueryForNonexistentToken();
/**
* The caller must own the token or be an approved operator.
*/
error TransferCallerNotOwnerNorApproved();
/**
* The token must be owned by `from`.
*/
error TransferFromIncorrectOwner();
/**
* Cannot safely transfer to a contract that does not implement the
* ERC721Receiver interface.
*/
error TransferToNonERC721ReceiverImplementer();
/**
* Cannot transfer to the zero address.
*/
error TransferToZeroAddress();
/**
* The token does not exist.
*/
error URIQueryForNonexistentToken();
/**
* The `quantity` minted with ERC2309 exceeds the safety limit.
*/
error MintERC2309QuantityExceedsLimit();
/**
* The `extraData` cannot be set on an unintialized ownership slot.
*/
error OwnershipNotInitializedForExtraData();
/**
* The `tokenIds` must be strictly ascending.
*/
error TokenIdsNotStrictlyAscending();
/**
* `_sequentialUpTo()` must be greater than `_startTokenId()`.
*/
error SequentialUpToTooSmall();
/**
* The `tokenId` of a sequential mint exceeds `_sequentialUpTo()`.
*/
error SequentialMintExceedsLimit();
/**
* Spot minting requires a `tokenId` greater than `_sequentialUpTo()`.
*/
error SpotMintTokenIdTooSmall();
/**
* Cannot mint over a token that already exists.
*/
error TokenAlreadyExists();
/**
* The feature is not compatible with spot mints.
*/
error NotCompatibleWithSpotMints();
// =============================================================
// STRUCTS
// =============================================================
struct TokenOwnership {
// The address of the owner.
address addr;
// Stores 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 via {_extraData}.
uint24 extraData;
}
// =============================================================
// TOKEN COUNTERS
// =============================================================
/**
* @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}.
*/
function totalSupply() external view returns (uint256);
// =============================================================
// IERC165
// =============================================================
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
// =============================================================
// IERC721
// =============================================================
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables
* (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in `owner`'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (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.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external payable;
/**
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
/**
* @dev Transfers `tokenId` 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.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external payable;
/**
* @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.
*/
function approve(address to, uint256 tokenId) external payable;
/**
* @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.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
// =============================================================
// IERC721Metadata
// =============================================================
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
// =============================================================
// IERC2309
// =============================================================
/**
* @dev Emitted when tokens in `fromTokenId` to `toTokenId`
* (inclusive) is transferred from `from` to `to`, as defined in the
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
*
* See {_mintERC2309} for more details.
*/
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title IOGRegistry
* @dev Interface for interacting with the `isOGOwner` function in the OGRegistry contract on Base.
* The OGRegistry maintains a registry of owner addresses from 1 mfer and 1 tiny dino on the mainnet.
*/
interface IOGRegistry {
/**
* @notice Checks if a given address is recognized as an OG Owner in the OGRegistry.
* @param addr The address to verify for OG ownership.
* @return True if the address is an OG Owner in the registry, false otherwise.
*/
function isOGOwner(address addr) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title ITraitGenerator
* @dev Interface for interacting with the `getNFTMetadata` function in the trait generator contract.
*/
interface ITraitGenerator {
/**
* @notice Retrieves metadata for a specific NFT.
* @param traitComboIndex The index of the trait combo.
* @param id The identifier for the NFT.
* @return The metadata as a JSON-formatted string.
*/
function getNFTMetadata(uint256 traitComboIndex, uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @title ITransferValidator721
* @author 0xkuwabatake (@0xkuwabatake)
* Modified from ProjectOpenSea/seadrop:
* https://github.com/ProjectOpenSea/seadrop/blob/main/src/interfaces/ITransferValidator.sol
* @notice Interface for validating ERC721 token transfers.
*/
interface ITransferValidator721 {
/**
* @notice Validates if `caller` is authorized to transfer `tokenId` from `from` to `to`.
* @param caller The initiator of the transfer.
* @param from The current owner of the token.
* @param to The recipient of the token.
* @param tokenId The token ID being transferred.
*/
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
library SoladyLib {
/*//////////////////////////////////////////////////////////////
STRUCT
//////////////////////////////////////////////////////////////*/
/// @dev A pseudorandom number state in memory.
struct PRNG {
uint256 state;
}
/*//////////////////////////////////////////////////////////////
CONSTANT
//////////////////////////////////////////////////////////////*/
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/*//////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////*/
/// @dev The input is invalid.
error ParsingFailed();
/// @dev Unable to deploy the storage contract.
error DeploymentFailed();
/*//////////////////////////////////////////////////////////////
OPERATIONS
//////////////////////////////////////////////////////////////*/
/// Multicallable ///
/// @dev `DELEGATECALL` with the current contract to each calldata in `data`.
function multicall(bytes[] calldata data) internal returns (bytes[] memory) {
assembly {
mstore(0x00, 0x20)
mstore(0x20, data.length) // Store `data.length` into `results`.
// Early return if no data.
if iszero(data.length) { return(0x00, 0x40) }
let results := 0x40
// `shl` 5 is equivalent to multiplying by 0x20.
let end := shl(5, data.length)
// Copy the offsets from calldata into memory.
calldatacopy(0x40, data.offset, end)
// Offset into `results`.
let resultsOffset := end
// Pointer to the end of `results`.
end := add(results, end)
for {} 1 {} {
// The offset of the current bytes in the calldata.
let o := add(data.offset, mload(results))
let m := add(resultsOffset, 0x40)
// Copy the current bytes from calldata to the memory.
calldatacopy(
m,
add(o, 0x20), // The offset of the current bytes' bytes.
calldataload(o) // The length of the current bytes.
)
if iszero(delegatecall(gas(), address(), m, calldataload(o), codesize(), 0x00)) {
// Bubble up the revert if the delegatecall reverts.
returndatacopy(0x00, 0x00, returndatasize())
revert(0x00, returndatasize())
}
// Append the current `resultsOffset` into `results`.
mstore(results, resultsOffset)
results := add(results, 0x20)
// Append the `returndatasize()`, and the return data.
mstore(m, returndatasize())
returndatacopy(add(m, 0x20), 0x00, returndatasize())
// Advance the `resultsOffset` by `returndatasize() + 0x20`,
// rounded up to the next multiple of 32.
resultsOffset :=
and(add(add(resultsOffset, returndatasize()), 0x3f), 0xffffffffffffffe0)
if iszero(lt(results, end)) { break }
}
return(0x00, add(resultsOffset, 0x40))
}
}
/// LibPRNG ///
/// @dev Seeds the `prng` with `state`.
function seed(PRNG memory prng, uint256 state) internal pure {
/// @solidity memory-safe-assembly
assembly {
mstore(prng, state)
}
}
/// @dev Shuffles the array in-place with Fisher-Yates shuffle.
function shuffle(PRNG memory prng, uint256[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let n := mload(a)
let w := not(0)
let mask := shr(128, w)
if n {
for { a := add(a, 0x20) } 1 {} {
// We can just directly use `keccak256`, cuz
// the other approaches don't save much.
let r := keccak256(prng, 0x20)
mstore(prng, r)
// Note that there will be a very tiny modulo bias
// if the length of the array is not a power of 2.
// For all practical purposes, it is negligible
// and will not be a fairness or security concern.
{
let j := add(a, shl(5, mod(shr(128, r), n)))
n := add(n, w) // `sub(n, 1)`.
if iszero(n) { break }
let i := add(a, shl(5, n))
let t := mload(i)
mstore(i, mload(j))
mstore(j, t)
}
{
let j := add(a, shl(5, mod(and(r, mask), n)))
n := add(n, w) // `sub(n, 1)`.
if iszero(n) { break }
let i := add(a, shl(5, n))
let t := mload(i)
mstore(i, mload(j))
mstore(j, t)
}
}
}
}
}
/// SSTORE2 ///
/// @dev Writes `data` into the bytecode of a storage contract and returns its address.
function write(bytes memory data) internal returns (address pointer) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode.
/**
* ---------------------------------------------------+
* Opcode | Mnemonic | Stack | Memory |
* ---------------------------------------------------|
* 61 l | PUSH2 l | l | |
* 80 | DUP1 | l l | |
* 60 0xa | PUSH1 0xa | 0xa l l | |
* 3D | RETURNDATASIZE | 0 0xa l l | |
* 39 | CODECOPY | l | [0..l): code |
* 3D | RETURNDATASIZE | 0 l | [0..l): code |
* F3 | RETURN | | [0..l): code |
* 00 | STOP | | |
* ---------------------------------------------------+
* @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called.
* Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16.
*/
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
// Deploy a new contract with the generated creation code.
pointer := create(0, add(data, 0x15), add(n, 0xb))
if iszero(pointer) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`.
function read(address pointer) internal view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21))
mstore(data, n) // Store the length.
mstore(0x40, add(n, add(data, 0x40))) // Allocate memory.
}
}
/// JsonParserLib ///
/// @dev Parses an unsigned integer from a string (in decimal, i.e. base 10).
/// Reverts if `s` is not a valid uint256 string matching the RegEx `^[0-9]+$`,
/// or if the parsed number is too big for a uint256.
function parseUint(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let preMulOverflowThres := div(not(0), 10)
for { let i := 0 } 1 {} {
i := add(i, 1)
let digit := sub(and(mload(add(s, i)), 0xff), 48)
let mulOverflowed := gt(result, preMulOverflowThres)
let product := mul(10, result)
result := add(product, digit)
n := mul(n, iszero(or(or(mulOverflowed, lt(result, product)), gt(digit, 9))))
if iszero(lt(i, n)) { break }
}
if iszero(n) {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
}
}
/// LibString ///
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end of the memory to calculate the length later.
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 1)`.
// Store the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(result, add(48, mod(temp, 10)))
temp := div(temp, 10) // Keep dividing `temp` until zero.
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
mstore(result, n) // Store the length.
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
/// Source: https://github.com/Vectorized/solady/blob/main/src/utils/LibString.sol#L739
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(gt(subjectLength, end)) { end := subjectLength }
if iszero(gt(subjectLength, start)) { start := subjectLength }
if lt(start, end) {
result := mload(0x40)
let resultLength := sub(end, start)
mstore(result, resultLength)
subject := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(resultLength, 0x1f), w) } 1 {} {
mstore(add(result, o), mload(add(subject, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(result, 0x20), resultLength), 0)
mstore(0x40, add(result, add(resultLength, 0x40))) // Allocate the memory.
}
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the string.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
/// Base64 ///
/// @dev Encodes `data` using the base64 encoding described in RFC 4648.
/// Note: It does not replace '+' with '-' and '/' with '_' and strip away the padding.
function encode(bytes memory data)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let dataLength := mload(data)
if dataLength {
// Multiply by 4/3 rounded up.
// The `shl(2, ...)` is equivalent to multiplying by 4.
let encodedLength := shl(2, div(add(dataLength, 2), 3))
// Set `result` to point to the start of the free memory.
result := mload(0x40)
// Store the table into the scratch space.
// Offsetted by -1 byte so that the `mload` will load the character.
// We will rewrite the free memory pointer at `0x40` later with
// the allocated size.
// The magic constant 0x0670 will turn "-_" into "+/".
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
// Do not replace '+' with '-' and '/' with '_'.
mstore(0x3f, xor("ghijklmnopqrstuvwxyz0123456789-_", mul(iszero(false), 0x0670)))
// Skip the first slot, which stores the length.
let ptr := add(result, 0x20)
let end := add(ptr, encodedLength)
let dataEnd := add(add(0x20, data), dataLength)
let dataEndValue := mload(dataEnd) // Cache the value at the `dataEnd` slot.
mstore(dataEnd, 0x00) // Zeroize the `dataEnd` slot to clear dirty bits.
// Run over the input, 3 bytes at a time.
for {} 1 {} {
data := add(data, 3) // Advance 3 bytes.
let input := mload(data)
// Write 4 bytes. Optimized for fewer stack operations.
mstore8(0, mload(and(shr(18, input), 0x3F)))
mstore8(1, mload(and(shr(12, input), 0x3F)))
mstore8(2, mload(and(shr(6, input), 0x3F)))
mstore8(3, mload(and(input, 0x3F)))
mstore(ptr, mload(0x00))
ptr := add(ptr, 4) // Advance 4 bytes.
if iszero(lt(ptr, end)) { break }
}
mstore(dataEnd, dataEndValue) // Restore the cached value at `dataEnd`.
mstore(0x40, add(end, 0x20)) // Allocate the memory.
// Equivalent to `o = [0, 2, 1][dataLength % 3]`.
let o := div(2, mod(dataLength, 3))
// Offset `ptr` and pad with '='. We can simply write over the end.
mstore(sub(ptr, o), shl(240, 0x3d3d))
// Set `o` to zero if there is padding.
o := mul(iszero(iszero(false)), o) // No padding.
mstore(sub(ptr, o), 0) // Zeroize the slot after the string.
mstore(result, sub(encodedLength, o)) // Store the length.
}
}
}
/// SafeTransferLib ///
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::------=====-------:::::::::::::::::::-=====-::::::::::::::::::
:::::::::::::::::::::::::::::::::::::=*****#@@@@@@#*****-::::::::::::::::::@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::::::::=*****#@@@@@@#*****-::::::::::::::::::@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::::::::=*****#@@@@@@#*****-::::::::::::::::::@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::******%@@@@@#............:-----:::::::::::::@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::******%@@@@@#............:-----:::::::::::::@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::******%@@@@@#............:-----:::::::::::::@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::#%%%%%%@@@@@%+++++=:.....+*****=......::::::******=::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@%%%%%@@@@@@%: #@@@@@+. .:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@%%%%%@@@@@@%: #@@@@@+. .:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@%%%%%@@@@@@%: #@@@@@+. .:::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@%%%%%* :@@@@@@@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@%%%%%* :@@@@@@@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@%%%%%* :@@@@@@@@@@@@+::::::::::::::::::
:::::::::::::::::::::::::::::::======#@@@@@%************-...........:============-::::::::::::::::::
:::::::::::::::::::::::::::::::::::::*@@@@@@%%%%%%%%%%%%-:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::*@@@@@@%%%%%%%%%%%%-:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::*@@@@@@%%%%%%%%%%%%-:::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::-@@@@@@%%%%%%@@@@@@@@@@@@@%%%%%%@@@@@@*:::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::-@@@@@@%%%%%%@@@@@@@@@@@@@%%%%%%@@@@@@*:::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::-@@@@@@%%%%%%@@@@@@@@@@@@@%%%%%%@@@@@@*:::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::------@@@@@@@@@@@@@%%%%%%%%%%%%=-----::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@@@@@@@%%%%%%%%%%%%-:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::@@@@@@@@@@@@@%%%%%%%%%%%%-:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::%%%%%%@@@@@@@######%%%%%%-:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::*@@@@@#:::::-%@@@@@=:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::*@@@@@#:::::-%@@@@@=:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::*@@@@@#:::::-%@@@@@=:::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::-----:::::::------::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/
import {ERC721A} from "ERC721A/ERC721A.sol";
import {ERC2981} from "solady/tokens/ERC2981.sol";
import {Ownable} from "solady/auth/Ownable.sol";
import {SoladyLib} from "./utils/SoladyLib.sol";
import {ERC721TransferValidator} from "./extensions/ERC721TransferValidator.sol";
import "./TinyDinoMfersConstants.sol";
/**
* @title TinyDinoMfers
* @author 0xkuwabatake (@0xkuwabatake)
* @notice Implementation contract for the onchain tiny dino mfers (TDMFER) NFT collection.
*/
contract TinyDinoMfers is ERC721A, ERC2981, ERC721TransferValidator, Ownable {
using SoladyLib for *;
/*//////////////////////////////////////////////////////////////
STRUCT
//////////////////////////////////////////////////////////////*/
/// @dev Represents a trait combination in the collection.
struct TraitCombo {
/// @dev The total supply allocated to this trait combination.
uint256 totalSupply;
}
/*//////////////////////////////////////////////////////////////
PUBLIC CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev The maximum number of tokens that can be minted in this collection.
uint256 public constant MAX_SUPPLY = 2005;
/// @dev The maximum number of tokens a single wallet can mint.
uint256 public constant MAX_NUMBER_MINTED = 20;
/// @dev Start of the public sale timestamp: January 23, 2025, 4:20 PM EST (9:20 PM UTC).
uint256 public constant PUBLIC_SALE_TIMESTAMP = 1737667200;
/// @dev The address designated for receiving withdrawals and royalty payments.
address public constant RECEIVER_ADDRESS = 0x000000003D0b24A0aC1dC5b7A436887DcD6ecD81;
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @dev Maps `traitComboIndex` to a `TraitCombo` structure.
mapping(uint256 => TraitCombo) private _traitCombo;
/// @dev Seed value to initiate trait combo index generation.
uint256 private _seed;
/// @dev Sale prices in ETH for minting a single token.
/// Uses data packing to store multiple price tiers within a single uint240 variable.
/// Bits Layout:
/// - [0..79] `firstPriceTier`
/// - [80..159] `secondPriceTier`
/// - [160..239] `publicPrice`
uint240 private _mintPrices;
/// @dev Boolean value for mint live status. `true` if it's live, `false` otherwise.
bool private _isMintLive;
/*//////////////////////////////////////////////////////////////
ERC-4906 EVENTS
//////////////////////////////////////////////////////////////*/
/// @dev Emitted when the metadata of a `tokenId` is changed.
event MetadataUpdate(uint256 tokenId);
/// @dev Emitted when the metadata from `fromTokenId` to `toTokenId` are changed.
event BatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId);
/*//////////////////////////////////////////////////////////////
CUSTOM ERRORS
//////////////////////////////////////////////////////////////*/
/// @dev Revert with an error if mint status is not live.
error MintIsNotLive();
/// @dev Revert with an error if `quantity`exceeds minimum or maximum number minted.
error InvalidQuantity();
/// @dev Revert with an error if total tokens to mint plus recent total supply
/// exceeds maximum supply of tokens.
error ExceedsMaxSupply();
/// @dev Revert with an error if `msg.value` from `msg.sender` is not equal to total price.
error InvalidMintPrice();
/// @dev Revert if the specified token does not exist.
error TokenDoesNotExist();
/// @dev Revert with an error if current total number of tokens minted plus total tokens to mint
/// exceeds maximum number of tokens minted per wallet.
error ExceedsMaxNumberMinted();
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor() payable ERC721A("tiny dino mfers", "TDMFER") {
_initializeOwner(tx.origin);
_initializeSeed();
_setDefaultRoyalty(RECEIVER_ADDRESS, 500);
_setTransferValidator(0xA000027A9B2802E1ddf7000061001e5c005A0000); // StrictAuthorizedTransferSecurityRegistry
_setMintPrices(0.0015 ether, 0.00175 ether, 0.002 ether);
// See: {_setTraitCombos}
_setTraitCombos(
[
TraitCombo({totalSupply: 699}), // #0: plain/charcoal-hat under headphones-headphones-shirt
TraitCombo({totalSupply: 499}), // #1: plain/charcoal-short hair-headphones-shirt
TraitCombo({totalSupply: 213}), // #2: plain/charcoal-hat under headphones-headphones
TraitCombo({totalSupply: 150}), // #3: plain/charcoal-short hair-headphones
TraitCombo({totalSupply: 99}), // #4: plain/charcoal-spikes-headphones
TraitCombo({totalSupply: 69}), // #5: plain/charcoal-headphones-shirt-hat over headphones
TraitCombo({totalSupply: 59}), // #6: plain/charcoal-spikes-hat under headphones-headphones-shirt
TraitCombo({totalSupply: 47}), // #7: plain/charcoal-spikes-headphones-shirt
TraitCombo({totalSupply: 27}), // #8: zombie-spikes-headphones-shirt
TraitCombo({totalSupply: 23}), // #9: plain/charcoal-shirt-hat over headphones
TraitCombo({totalSupply: 21}), // #10: plain/charcoal-headphones-hat over headphones
TraitCombo({totalSupply: 21}), // #11: plain/charcoal-headphones
TraitCombo({totalSupply: 21}), // #12: plain/charcoal-hat over headphones
TraitCombo({totalSupply: 13}), // #13: zombie-hat under headphones-headphones
TraitCombo({totalSupply: 9}), // #14: zombie-headphones
TraitCombo({totalSupply: 9}), // #15: ape-hat under headphones-headphones
TraitCombo({totalSupply: 9}), // #16: alien-headphones
TraitCombo({totalSupply: 7}), // #17: ape-shirt-hat over headphones
TraitCombo({totalSupply: 5}), // #18: ape-headphones
TraitCombo({totalSupply: 1}), // #19: genesis (1/1)
TraitCombo({totalSupply: 1}), // #20: bot (1/1)
TraitCombo({totalSupply: 1}), // #21: toadz (1/1)
TraitCombo({totalSupply: 1}), // #22: xcopy (1/1)
TraitCombo({totalSupply: 1}) // #23: PETSCII Dino (1/1)
]
);
// See: {ERC721A - _mintERC2309}
_mintERC2309(tx.origin, 50); // Allocated for @0xkuwabake (dev) & @filter8_tez (arts)
}
/*//////////////////////////////////////////////////////////////
EXTERNAL PAYABLE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Mints a specified number of tokens to the caller's address.
* @dev Mint `quantity` of tokens to `msg.sender`.
* @param quantity The total number of tokens to mint.
*/
function mint(uint256 quantity) external payable {
if (!isMintLive() || block.timestamp < PUBLIC_SALE_TIMESTAMP) _revert(MintIsNotLive.selector);
if (quantity == 0 || quantity > MAX_NUMBER_MINTED) _revert(InvalidQuantity.selector);
uint256 currentSupply = totalSupply();
uint256 currentNumberMinted = numberMinted(msg.sender);
unchecked {
if (quantity + currentSupply > MAX_SUPPLY) _revert(ExceedsMaxSupply.selector);
if (currentNumberMinted + quantity > MAX_NUMBER_MINTED) _revert(ExceedsMaxNumberMinted.selector);
_setAux(msg.sender, uint64(currentNumberMinted + quantity));
}
// Determine applicable price ('isFirsTier' has priority if user qualifies for multiple).
// If totalPrice is 0, user must send exactly 0 ETH; otherwise, must send the correct `totalPrice`.
(uint80 firstTierPrice, uint80 secondTierPrice, uint80 publicPrice) = mintPrices();
bool isFirstTier = isOGOwner(msg.sender);
bool isSecondTier = isBasedOnchainOwner(msg.sender);
uint256 totalPrice;
if (isFirstTier) totalPrice = uint256(firstTierPrice) * quantity;
else if (isSecondTier) totalPrice = uint256(secondTierPrice) * quantity;
else totalPrice = uint256(publicPrice) * quantity;
if (msg.value != totalPrice) _revert(InvalidMintPrice.selector);
// Mint tokens using {ERC721A - _safeMint) for smart contract wallet compatibility.
_safeMint(msg.sender, quantity);
}
/**
* @notice Transfers multiple tokens from one owner to another in a single transaction.
* @dev Transfer from `from` to `to` for array of `tokenIds`.
* Delegates the transfer logic to the internal {ERC721A - _batchTransferFrom} function.
* @param from The current owner of the tokens.
* @param to The address to receive the tokens.
* @param tokenIds An array of token IDs to be transferred.
* @custom:note This function does not validate the length of `tokenIds`.
* Providing a very large array may cause the transaction to exceed the gas limit.
*/
function batchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
) external payable {
_batchTransferFrom(from, to, tokenIds);
}
/**
* @notice Safe ransfers multiple tokens from one owner to another in a single transaction.
* @dev Safe transfer from `from` to `to` for array of `tokenIds`.
* Delegates the transfer logic to the internal {ERC721A - _safeBatchTransferFrom} function.
* @param from The current owner of the tokens.
* @param to The address to receive the tokens.
* @param tokenIds An array of token IDs to be transferred.
* @custom:note This function does not validate the length of `tokenIds`.
* Providing a very large array may cause the transaction to exceed the gas limit.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
) external payable {
_safeBatchTransferFrom(address(0), from, to, tokenIds, "");
}
/*//////////////////////////////////////////////////////////////
EXTERNAL ONLY OWNER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Airdrops single token to each address in the recipients array.
* @dev Iterates through the `recipients` array and mints `AIRDROP_QUANTITY` to each address.
* @param recipients An array of addresses to receive the airdropped tokens.
*
* Requirement:
* - Caller must be the `owner`.
*
* Revert:
* - `Unauthorized` if block.timestamp is greater than `PUBLIC_SALE_TIMESTAMP`.
*/
function airdrop(address[] calldata recipients) external payable onlyOwner {
if (block.timestamp > PUBLIC_SALE_TIMESTAMP) _revert(Unauthorized.selector);
uint256 i;
do {
_mint(recipients[i], AIRDROP_QUANTITY);
unchecked { ++i; }
} while (i != recipients.length);
}
/**
* @notice Sets the mint prices for `firstTierPrice`, `secondTierPrice`, and `publicPrice`.
* @dev Delegates the setting of mint prices to the internal `_setMintPrices` function.
* @param firstTierPrice The mint price for the owner of 1 OG mfer & 1 OG dino.
* @param secondTierPrice The mint price for the owner of 1 DINO or 1 TDP or 1 1BITCHONKS.
* @param publicPrice The mint price for the public.
*
* Requirement:
* - Caller must be the `owner`.
*/
function setMintPrices(uint80 firstTierPrice, uint80 secondTierPrice, uint80 publicPrice)
external
payable
onlyOwner
{
_setMintPrices(firstTierPrice, secondTierPrice, publicPrice);
}
/**
* @notice Toggles the minting status between active and paused.
*
* Requirement:
* - Caller must be the `owner`.
*
* Reverts:
* - `Unauthorized` if the current time is less than 5 minutes before the public sale starts.
*/
function toggleMintLive() external payable onlyOwner {
if (block.timestamp < PUBLIC_SALE_TIMESTAMP - 5 minutes) _revert(Unauthorized.selector);
_isMintLive = !_isMintLive;
}
/**
* @notice Emits a BatchMetadataUpdate event for all tokens in the collection.
* @dev Emits the ERC-4906 BatchMetadataUpdate event covering token IDs
* from `_startTokenId()` to `_nextTokenId() - 1`.
*
* Requirement:
* - Caller must be the `owner`.
*/
function emitAllMetadataUpdate() external payable onlyOwner {
emit BatchMetadataUpdate(_startTokenId(), _nextTokenId() - 1);
}
/**
* @notice Sets the default royalty information for all tokens.
* @dev Sets the default royalty for `receiver` and `feeNumerator`.
* @param receiver The address that will receive royalty payments.
* @param feeNumerator The royalty fee in basis points (parts per 10,000).
*
* Requirement:
* - Caller must be the `owner`.
*/
function setDefaultRoyalty(address receiver, uint96 feeNumerator) external payable onlyOwner {
_setDefaultRoyalty(receiver, feeNumerator);
}
/**
* @notice Reset the default royalty information for all tokens.
* @dev Delegates the operation to {ERC2981 - _deleteDefaultRoyalty}.
*
* Requirement:
* - Caller must be the `owner`.
*/
function resetDefaultRoyalty() external payable onlyOwner {
_deleteDefaultRoyalty();
}
/**
* @dev Sets transfer `validator` contract.
* @param validator The address of the new transfer validator contract.
*
* Requirement:
* - Caller must be the `owner`.
*/
function setTransferValidator(address validator) external onlyOwner {
_setTransferValidator(validator);
}
/**
* @dev Withdraws the entire Ether balance of the contract to the designated `RECEIVER_ADDRESS`.
*
* Requirement:
* - Caller must be the `owner`.
*/
function withdraw() external payable onlyOwner {
SoladyLib.forceSafeTransferAllETH(RECEIVER_ADDRESS);
}
/*//////////////////////////////////////////////////////////////
PUBLIC VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if the contract implements a specific interface as per ERC-165.
* @dev Supports ERC-4906, ERC2981, ICreatorToken, and ERC721A interfaces.
* @param interfaceId The interface identifier, as specified in ERC-165.
* @return result True if the contract implements the specified interface, false otherwise.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC2981, ERC721A)
returns (bool result)
{
return interfaceId == 0x49064906 // Interface ID for ERC4906
|| interfaceId == 0x2a55205a // Interface ID for ERC2981
|| interfaceId == INTERFACE_ID_ICREATORTOKEN // Interface ID for ICreatorToken
|| ERC721A.supportsInterface(interfaceId); // Interface IDs ERC165, ERC721, ERC721Metadata
}
/**
* @notice Retrieves the on-chain metadata URI for the specified `tokenId`.
* @dev Returns the URI for `tokenId` in data URI format by querying the `TraitGenerator` contract.
* @param tokenId The unique identifier for an NFT. Must exist.
* @return The metadata URI associated with the specified `tokenId`.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (!_exists(tokenId)) _revert(TokenDoesNotExist.selector);
uint256 tci = _traitComboIndex(tokenId);
return TRAIT_GENERATOR.getNFTMetadata(tci, tokenId);
}
/**
* @notice Retrieves the trait combination index for the specified `tokenId`.
* @dev Ensures that the `tokenId` exists before returning its trait combination index.
* @param tokenId The unique identifier for an NFT. Must exist.
* @return The trait combination index associated with the specified `tokenId`.
*/
function traitComboIndex(uint256 tokenId) public view returns (uint256) {
if (!_exists(tokenId)) _revert(TokenDoesNotExist.selector);
return _traitComboIndex(tokenId);
}
/**
* @notice Returns the total number of tokens minted by a specific address.
* @dev Retrieves the ERC721A's auxiliary data associated with `addr`, representing the mint count.
* @param addr The address to query for minted tokens.
* @return The total number of tokens minted by `addr`.
*/
function numberMinted(address addr) public view returns (uint64) {
return _getAux(addr);
}
/**
* @notice Retrieves the current mint prices for each sale tier.
* @dev Unpacks the packed `_mintPrices` variable into individual price tiers.
* @return firstPriceTier The mint price for the owner of 1 OG mfer & 1 OG dino.
* @return secondPriceTier The mint price for the owner of 1 DINO or 1 TDP or 1 1BITCHONKS.
* @return publicPrice The mint price for the public sale tier.
*/
function mintPrices()
public
view
returns (uint80 firstPriceTier, uint80 secondPriceTier, uint80 publicPrice)
{
return (
uint80(_mintPrices),
uint80(_mintPrices >> 80),
uint80(_mintPrices >> 160)
);
}
/**
* @notice Checks whether minting is currently active.
* @dev Returns `false` if the current time is before the `PUBLIC_SALE_TIMESTAMP`;
* otherwise, returns the value of `_isMintLive`.
* @return `true` if minting is live, `false` otherwise.
*/
function isMintLive() public view returns (bool) {
if (block.timestamp < PUBLIC_SALE_TIMESTAMP) return false;
return _isMintLive;
}
/**
* @notice Determines if a given address is an OG Owner.
* @dev Delegates the ownership check to the `OGRegistry` contract's `isOGOwner` function.
* @param owner The address to verify for OG ownership.
* @return `true` if the address is an OG Owner in the `OGRegistry`, `false` otherwise.
*/
function isOGOwner(address owner) public view returns (bool) {
return OG_REGISTRY.isOGOwner(owner);
}
/**
* @notice Determines if an address owns at least one token from three onchain based NFT collection.
* @dev Checks the balance of the `owner` in the `DINO`, `TDP`, and `ONEBITCHONKS` contracts.
* @param owner The address to verify for ownership across specified NFT collections.
* @return `true` if the `owner` holds at least one token in `DINO`, or `TDP`, or `ONEBITCHONKS`; otherwise, false.
*/
function isBasedOnchainOwner(address owner) public view returns (bool) {
return DINO.balanceOf(owner) != 0
|| TDP.balanceOf(owner) != 0
|| ONEBITCHONKS.balanceOf(owner) != 0;
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @dev Overrides {ERC721A-_beforeTokenTransfers} to include transfer validation.
* Validates transfers using the `transferValidator` contract, if one is set.
* @param from The address initiating the transfer.
* @param to The address receiving the transfer.
* @param startTokenId The starting token ID being transferred.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 /* quantity */
) internal virtual override {
if (from != address(0) && to != address(0)) {
address transferValidator = address(_transferValidator);
// Call the transfer validator if `validator` is set.
if (transferValidator != address(0)) {
_transferValidator.validateTransfer(
msg.sender,
from,
to,
startTokenId
);
}
}
}
/**
* @dev Initialize the seed for trait combination index generation.
*/
function _initializeSeed() internal {
_seed = uint256(
keccak256(
abi.encodePacked(
tx.gasprice,
block.number,
block.timestamp,
block.prevrandao,
blockhash(block.number - 1),
msg.sender
)
)
);
}
/**
* @notice Initializes trait combinations for the entire collection.
* @dev Stores each `TraitCombo` from `traitCombos` into the `_traitCombo` mapping using the index `i` as the key.
* @param traitCombos An array of `TraitCombo` structs with a length of `TOTAL_TRAIT_COMBOS`.
* @custom:note This function is intended to be called exclusively within the constructor.
* Once initialized, trait combinations are immutable.
*/
function _setTraitCombos(TraitCombo[TOTAL_TRAIT_COMBOS] memory traitCombos) internal {
uint256 i;
do {
_traitCombo[i] = TraitCombo(traitCombos[i].totalSupply);
{ ++i; }
} while (i != TOTAL_TRAIT_COMBOS);
}
/**
* @dev Sets the mint prices by packing `firstTierPrice`, `secondTierPrice`, and `publicPrice`
* into the `_mintPrices` variable.
* Each price is stored as a `uint80` within a `uint240`, with `firstTierPrice` in the lowest 80 bits,
* `secondTierPrice` in the next 80 bits, and `publicPrice` in the highest 80 bits.
* @param firstTierPrice The mint price for the first-tier.
* @param secondTierPrice The mint price for the second-tier.
* @param publicPrice The mint price for the public sale tier.
*/
function _setMintPrices(
uint80 firstTierPrice,
uint80 secondTierPrice,
uint80 publicPrice
) internal {
_mintPrices = uint240(firstTierPrice) | uint240(secondTierPrice) << 80 | uint240(publicPrice) << 160;
}
/**
* @dev Calculates the trait combination index for a given `tokenId` using a randomized algorithm.
* Combines a randomized token ID with the contract's seed and `TRAIT_COMBO_PRIME` to generate the index.
* @param tokenId The unique identifier for the NFT.
* @return The trait combination index associated with the specified `tokenId`.
*/
function _traitComboIndex(uint256 tokenId) internal view returns (uint256) {
unchecked {
uint256 rtid = _randomizedTokenId(tokenId);
uint256 s = _seed % MAX_SUPPLY;
return _traitComboIndexGenerator(((rtid + s) * TRAIT_COMBO_PRIME) % MAX_SUPPLY);
}
}
/**
* @dev Randomizes the `tokenId` using the Fisher-Yates shuffle algorithm.
* @param tokenId The unique identifier for the NFT.
* @custom:note This is used as part of the modified seed to generate a pseudo-random number at {_traitComboIndex}.
*/
function _randomizedTokenId(uint256 tokenId) internal view returns (uint256) {
uint256[] memory indices = new uint256[](MAX_SUPPLY);
for (uint256 i; i != MAX_SUPPLY;) {
indices[i] = i;
unchecked { ++i; }
}
SoladyLib.PRNG memory prng;
prng.seed(_seed);
prng.shuffle(indices);
return indices[tokenId];
}
/**
* @dev Weighted random selection algorithm for `randomNumber`.
* @param randomNumber Pseudo-random number generated in {_traitComboIndex}.
* @custom:notes
* - Rarity is determined by `totalSupply`.
* - Higher `totalSupply` are more likely to be selected because they span a larger range of numbers.
* - Conversely, trait combo indexes with lower `totalSupply` are less likely to be selected due to their smaller range.
*/
function _traitComboIndexGenerator(uint256 randomNumber) internal view returns (uint256) {
uint256 lowerBound;
for (uint256 i; i != TOTAL_TRAIT_COMBOS;) {
unchecked {
uint256 occurence = _traitCombo[i].totalSupply;
if (randomNumber >= lowerBound && randomNumber < lowerBound + occurence) return i;
lowerBound = lowerBound + occurence;
++i;
}
}
revert();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {ITraitGenerator} from "./interfaces/ITraitGenerator.sol";
import {IOGRegistry} from "./interfaces/IOGRegistry.sol";
import {IBasedOnchainOwner} from "./interfaces/IBasedOnchainOwner.sol";
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Trait generator contract address on Base.
ITraitGenerator constant TRAIT_GENERATOR = ITraitGenerator(0x0000000006EfC9A4D3667A297c824d0e904A952c);
/// @dev OG registry contract address on Base.
IOGRegistry constant OG_REGISTRY = IOGRegistry(0x0000000085256756c00864e898352856E8cB804c);
/// @dev Based Onchain Dinos contract address on Base.
IBasedOnchainOwner constant DINO = IBasedOnchainOwner(0xD4c5292b9689238f0A51C8505B1d1D6714Ce95a0);
/// @dev Tiny Dino Punks contract address on Base.
IBasedOnchainOwner constant TDP = IBasedOnchainOwner(0x20Be3B999421A12F1247C33519874a73FcE88FD1);
/// @dev 1Bit Chonks contract address on Base.
IBasedOnchainOwner constant ONEBITCHONKS = IBasedOnchainOwner(0x22CA771878C9BD8C594969E871d01267553EEaC2);
/// @dev Prime number for pseudo-random number generation used in `traitComboIndex`.
uint256 constant TRAIT_COMBO_PRIME = 809964495083245361527940381794788695820367981156436813625509;
/// @dev Total number of trait combinations (common and 1/1 special traits).
uint256 constant TOTAL_TRAIT_COMBOS = 24; // 19 + 5
/// @dev The fixed quantity of tokens to be airdropped per eligible address.
uint256 constant AIRDROP_QUANTITY = 1;
{
"compilationTarget": {
"src/TinyDinoMfers.sol": "TinyDinoMfers"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":ERC721A/=lib/ERC721A/contracts/",
":forge-std/=lib/solady/test/utils/forge-std/",
":solady/=lib/solady/src/"
]
}
[{"inputs":[],"stateMutability":"payable","type":"constructor"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"ApprovalCallerNotOwnerNorApproved","type":"error"},{"inputs":[],"name":"ApprovalQueryForNonexistentToken","type":"error"},{"inputs":[],"name":"BalanceQueryForZeroAddress","type":"error"},{"inputs":[],"name":"ExceedsMaxNumberMinted","type":"error"},{"inputs":[],"name":"ExceedsMaxSupply","type":"error"},{"inputs":[],"name":"InvalidMintPrice","type":"error"},{"inputs":[],"name":"InvalidQuantity","type":"error"},{"inputs":[],"name":"MintERC2309QuantityExceedsLimit","type":"error"},{"inputs":[],"name":"MintIsNotLive","type":"error"},{"inputs":[],"name":"MintToZeroAddress","type":"error"},{"inputs":[],"name":"MintZeroQuantity","type":"error"},{"inputs":[],"name":"NewOwnerIsZeroAddress","type":"error"},{"inputs":[],"name":"NoHandoverRequest","type":"error"},{"inputs":[],"name":"NotCompatibleWithSpotMints","type":"error"},{"inputs":[],"name":"OwnerQueryForNonexistentToken","type":"error"},{"inputs":[],"name":"OwnershipNotInitializedForExtraData","type":"error"},{"inputs":[],"name":"RoyaltyOverflow","type":"error"},{"inputs":[],"name":"RoyaltyReceiverIsZeroAddress","type":"error"},{"inputs":[],"name":"SequentialMintExceedsLimit","type":"error"},{"inputs":[],"name":"SequentialUpToTooSmall","type":"error"},{"inputs":[],"name":"SpotMintTokenIdTooSmall","type":"error"},{"inputs":[],"name":"TokenAlreadyExists","type":"error"},{"inputs":[],"name":"TokenDoesNotExist","type":"error"},{"inputs":[],"name":"TokenIdsNotStrictlyAscending","type":"error"},{"inputs":[],"name":"TransferCallerNotOwnerNorApproved","type":"error"},{"inputs":[],"name":"TransferFromIncorrectOwner","type":"error"},{"inputs":[],"name":"TransferToNonERC721ReceiverImplementer","type":"error"},{"inputs":[],"name":"TransferToZeroAddress","type":"error"},{"inputs":[],"name":"URIQueryForNonexistentToken","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"fromTokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"toTokenId","type":"uint256"}],"name":"BatchMetadataUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"fromTokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"toTokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"ConsecutiveTransfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"MetadataUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldValidator","type":"address"},{"indexed":false,"internalType":"address","name":"newValidator","type":"address"}],"name":"TransferValidatorUpdated","type":"event"},{"inputs":[],"name":"MAX_NUMBER_MINTED","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_SUPPLY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PUBLIC_SALE_TIMESTAMP","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"RECEIVER_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"recipients","type":"address[]"}],"name":"airdrop","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"batchTransferFrom","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"cancelOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"completeOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"emitAllMetadataUpdate","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTransferValidationFunction","outputs":[{"internalType":"bytes4","name":"functionSignature","type":"bytes4"},{"internalType":"bool","name":"isViewFunction","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getTransferValidator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"isBasedOnchainOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isMintLive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"isOGOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"quantity","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"mintPrices","outputs":[{"internalType":"uint80","name":"firstPriceTier","type":"uint80"},{"internalType":"uint80","name":"secondPriceTier","type":"uint80"},{"internalType":"uint80","name":"publicPrice","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"numberMinted","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"ownershipHandoverExpiresAt","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"requestOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"resetDefaultRoyalty","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"salePrice","type":"uint256"}],"name":"royaltyInfo","outputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"royaltyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"safeBatchTransferFrom","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint96","name":"feeNumerator","type":"uint96"}],"name":"setDefaultRoyalty","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint80","name":"firstTierPrice","type":"uint80"},{"internalType":"uint80","name":"secondTierPrice","type":"uint80"},{"internalType":"uint80","name":"publicPrice","type":"uint80"}],"name":"setMintPrices","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"setTransferValidator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"result","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"toggleMintLive","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"traitComboIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"withdraw","outputs":[],"stateMutability":"payable","type":"function"}]