// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 32)
// Run over the input, 3 bytes at a time
for {
let dataPtr := data
let endPtr := add(data, mload(data))
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 bytes (18 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F which is the number of
// the previous character in the ASCII table prior to the Base64 Table
// The result is then added to the table to get the character to write,
// and finally write it in the result pointer but with a left shift
// of 256 (1 byte) - 8 (1 ASCII char) = 248 bits
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// 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()`.
*
* 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;
// =============================================================
// CONSTRUCTOR
// =============================================================
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
// =============================================================
// TOKEN COUNTING OPERATIONS
// =============================================================
/**
* @dev Returns the starting token ID.
* To change the starting token ID, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @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) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than `_currentIndex - _startTokenId()` times.
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* @dev Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view virtual returns (uint256) {
// Counter underflow is impossible as `_currentIndex` does not decrement,
// and it is initialized to `_startTokenId()`.
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev Returns the total number of tokens burned.
*/
function _totalBurned() internal view virtual returns (uint256) {
return _burnCounter;
}
// =============================================================
// 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] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* Returns the packed ownership data of `tokenId`.
*/
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
// If the data at the starting slot does not exist, start the scan.
if (packed == 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 == 0) continue;
if (packed & _BITMASK_BURNED == 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 == 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 < _currentIndex) {
uint256 packed;
while ((packed = _packedOwnerships[tokenId]) == 0) --tokenId;
result = packed & _BITMASK_BURNED == 0;
}
}
}
/**
* @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
*/
function _isSenderApprovedOrOwner(
address approvedAddress,
address owner,
address msgSender
) private pure returns (bool result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
owner := and(owner, _BITMASK_ADDRESS)
// Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
msgSender := and(msgSender, _BITMASK_ADDRESS)
// `msgSender == owner || msgSender == approvedAddress`.
result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
}
}
/**
* @dev Returns the storage slot and value for the approved address of `tokenId`.
*/
function _getApprovedSlotAndAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddress := 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);
// Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean.
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
unchecked {
// We can directly increment and decrement the balances.
--_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
// Updates:
// - `address` to the next owner.
// - `startTimestamp` to the timestamp of transfering.
// - `burned` to `false`.
// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).
if (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
// Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
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.
from, // `from`.
toMasked, // `to`.
tokenId // `tokenId`.
)
}
if (toMasked == 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 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 == 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 == 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` to the lower 160 bits, in case the upper bits somehow aren't clean.
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
if (toMasked == 0) _revert(MintToZeroAddress.selector);
uint256 end = startTokenId + quantity;
uint256 tokenId = startTokenId;
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 == 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)
);
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);
// Reentrancy protection.
if (_currentIndex != end) _revert(bytes4(0));
}
}
}
/**
* @dev Equivalent to `_safeMint(to, quantity, '')`.
*/
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, '');
}
// =============================================================
// 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);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
unchecked {
// Updates:
// - `balance -= 1`.
// - `numberBurned += 1`.
//
// We can directly decrement the balance, and increment the number burned.
// This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
// Updates:
// - `address` to the last owner.
// - `startTimestamp` to the timestamp of burning.
// - `burned` to `true`.
// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).
if (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
// =============================================================
// 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 == 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;
}
// =============================================================
// 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
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './IERC721AQueryable.sol';
import './ERC721A.sol';
/**
* @title ERC721AQueryable.
*
* @dev ERC721A subclass with convenience query functions.
*/
abstract contract ERC721AQueryable is ERC721A, IERC721AQueryable {
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
*
* - `addr = address(0)`
* - `startTimestamp = 0`
* - `burned = false`
* - `extraData = 0`
*
* If the `tokenId` is burned:
*
* - `addr = <Address of owner before token was burned>`
* - `startTimestamp = <Timestamp when token was burned>`
* - `burned = true`
* - `extraData = <Extra data when token was burned>`
*
* Otherwise:
*
* - `addr = <Address of owner>`
* - `startTimestamp = <Timestamp of start of ownership>`
* - `burned = false`
* - `extraData = <Extra data at start of ownership>`
*/
function explicitOwnershipOf(uint256 tokenId)
public
view
virtual
override
returns (TokenOwnership memory ownership)
{
unchecked {
if (tokenId >= _startTokenId()) {
if (tokenId < _nextTokenId()) {
// If the `tokenId` is within bounds,
// scan backwards for the initialized ownership slot.
while (!_ownershipIsInitialized(tokenId)) --tokenId;
return _ownershipAt(tokenId);
}
}
}
}
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] calldata tokenIds)
external
view
virtual
override
returns (TokenOwnership[] memory)
{
TokenOwnership[] memory ownerships;
uint256 i = tokenIds.length;
assembly {
// Grab the free memory pointer.
ownerships := mload(0x40)
// Store the length.
mstore(ownerships, i)
// Allocate one word for the length,
// `tokenIds.length` words for the pointers.
i := shl(5, i) // Multiply `i` by 32.
mstore(0x40, add(add(ownerships, 0x20), i))
}
while (i != 0) {
uint256 tokenId;
assembly {
i := sub(i, 0x20)
tokenId := calldataload(add(tokenIds.offset, i))
}
TokenOwnership memory ownership = explicitOwnershipOf(tokenId);
assembly {
// Store the pointer of `ownership` in the `ownerships` array.
mstore(add(add(ownerships, 0x20), i), ownership)
}
}
return ownerships;
}
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start < stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view virtual override returns (uint256[] memory) {
return _tokensOfOwnerIn(owner, start, stop);
}
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(`totalSupply`) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K collections should be fine).
*/
function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) {
uint256 start = _startTokenId();
uint256 stop = _nextTokenId();
uint256[] memory tokenIds;
if (start != stop) tokenIds = _tokensOfOwnerIn(owner, start, stop);
return tokenIds;
}
/**
* @dev Helper function for returning an array of token IDs owned by `owner`.
*
* Note that this function is optimized for smaller bytecode size over runtime gas,
* since it is meant to be called off-chain.
*/
function _tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) private view returns (uint256[] memory) {
unchecked {
if (start >= stop) _revert(InvalidQueryRange.selector);
// Set `start = max(start, _startTokenId())`.
if (start < _startTokenId()) {
start = _startTokenId();
}
uint256 stopLimit = _nextTokenId();
// Set `stop = min(stop, stopLimit)`.
if (stop >= stopLimit) {
stop = stopLimit;
}
uint256[] memory tokenIds;
uint256 tokenIdsMaxLength = balanceOf(owner);
bool startLtStop = start < stop;
assembly {
// Set `tokenIdsMaxLength` to zero if `start` is less than `stop`.
tokenIdsMaxLength := mul(tokenIdsMaxLength, startLtStop)
}
if (tokenIdsMaxLength != 0) {
// Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
// to cater for cases where `balanceOf(owner)` is too big.
if (stop - start <= tokenIdsMaxLength) {
tokenIdsMaxLength = stop - start;
}
assembly {
// Grab the free memory pointer.
tokenIds := mload(0x40)
// Allocate one word for the length, and `tokenIdsMaxLength` words
// for the data. `shl(5, x)` is equivalent to `mul(32, x)`.
mstore(0x40, add(tokenIds, shl(5, add(tokenIdsMaxLength, 1))))
}
// We need to call `explicitOwnershipOf(start)`,
// because the slot at `start` may not be initialized.
TokenOwnership memory ownership = explicitOwnershipOf(start);
address currOwnershipAddr;
// If the starting slot exists (i.e. not burned),
// initialize `currOwnershipAddr`.
// `ownership.address` will not be zero,
// as `start` is clamped to the valid token ID range.
if (!ownership.burned) {
currOwnershipAddr = ownership.addr;
}
uint256 tokenIdsIdx;
// Use a do-while, which is slightly more efficient for this case,
// as the array will at least contain one element.
do {
ownership = _ownershipAt(start);
assembly {
switch mload(add(ownership, 0x40))
// if `ownership.burned == false`.
case 0 {
// if `ownership.addr != address(0)`.
// The `addr` already has it's upper 96 bits clearned,
// since it is written to memory with regular Solidity.
if mload(ownership) {
currOwnershipAddr := mload(ownership)
}
// if `currOwnershipAddr == owner`.
// The `shl(96, x)` is to make the comparison agnostic to any
// dirty upper 96 bits in `owner`.
if iszero(shl(96, xor(currOwnershipAddr, owner))) {
tokenIdsIdx := add(tokenIdsIdx, 1)
mstore(add(tokenIds, shl(5, tokenIdsIdx)), start)
}
}
// Otherwise, reset `currOwnershipAddr`.
// This handles the case of batch burned tokens
// (burned bit of first slot set, remaining slots left uninitialized).
default {
currOwnershipAddr := 0
}
start := add(start, 1)
}
} while (!(start == stop || tokenIdsIdx == tokenIdsMaxLength));
// Store the length of the array.
assembly {
mstore(tokenIds, tokenIdsIdx)
}
}
return tokenIds;
}
}
}
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// 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();
// =============================================================
// 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
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './IERC721A.sol';
/**
* @dev Interface of ERC721AQueryable.
*/
interface IERC721AQueryable is IERC721A {
/**
* Invalid query range (`start` >= `stop`).
*/
error InvalidQueryRange();
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
*
* - `addr = address(0)`
* - `startTimestamp = 0`
* - `burned = false`
* - `extraData = 0`
*
* If the `tokenId` is burned:
*
* - `addr = <Address of owner before token was burned>`
* - `startTimestamp = <Timestamp when token was burned>`
* - `burned = true`
* - `extraData = <Extra data when token was burned>`
*
* Otherwise:
*
* - `addr = <Address of owner>`
* - `startTimestamp = <Timestamp of start of ownership>`
* - `burned = false`
* - `extraData = <Extra data at start of ownership>`
*/
function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory);
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory);
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start < stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view returns (uint256[] memory);
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(`totalSupply`) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K collections should be fine).
*/
function tokensOfOwner(address owner) external view returns (uint256[] memory);
}
pragma solidity 0.8.13;
import {ERC721AQueryable} from "./ERC721/ERC721AQueryable.sol";
import {ERC721A, IERC721A} from "./ERC721/ERC721A.sol";
import {IFruitToken,ISeedGenerator} from "./interfaces.sol";
import {TokenURI} from "./TokenURI.sol";
import {SVG} from "./SVG.sol";
import {
Tree,
TreeData,
StaticParams,
StartingParams,
_calculateFruit,
formatDays,
formatPercent,
scaleByPercent,
pickColor,
pickClouds,
unPackTree,
packTree
} from "./utils.sol";
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠖⠒⠢⣄⣀⡀⣀⣀⠀⡠⠔⠒⠒⢤⡀⠀⠀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡴⡇⠀⠀⠀⠁⠠⡋⠀⠀⠙⠦⠀⠀⠀⠀⣧⠤⣀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⡠⠖⠊⠑⠲⣄⣀⣠⠖⠘⠛⠀⠀⠀⠀⠀⠀⠀⠀⠁⠀⢸⠇⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⣸⣇⡀⠀⠀⠈⠁⠀⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠋⠲⣄⠀⠀
// ⠀⠀⠀⠀⣠⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡼⠂⠀
// ⠀⠀⠀⢀⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⠀⢱⠀⠀⠀⠀⠀⠀⠀⠐⠺⡄⠀⠀
// ⠀⡠⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⡀⠀⢀⡼⠀⠀⠀⠀⠀⠀⠀⠀⢀⡇⠀⠀
// ⢰⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠈⠉⠁⡹⠀⠀⠀⣄⣀⡠⠟⢘⣯⣀⠀⠀
// ⠸⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⡷⠺⡍⠒⣿⣀⣠⡀⠀⠀⠀⠀⠀⠈⠀⠈⡷⠀
// ⠀⢸⠚⠉⠀⠀⠀⠀⠀⠀⠀⠀⢀⣶⠺⡁⠀⠙⠚⠀⠁⡏⢧⣀⡄⠀⠀⠀⠀⠐⠒⣇⠀
// ⠀⠸⣄⣀⣰⠀⠀⠀⠀⠀⠀⠲⣟⣿⡦⣷⠀⠀⠀⠀⢠⠁⣸⣿⣷⢶⡆⢀⣤⡀⣠⡾⠁
// ⠀⠀⠀⠀⠱⣀⠀⢀⡱⠄⠤⠜⠋⠻⡄⠀⠀⠀⠀⠀⣸⣴⡿⣏⠀⢀⣭⣁⣀⡽⠁⠀⠀
// ⠀⠀⠀⠀⠀⠀⠈⠀⠀⠀⠀⠀⠀⠀⠸⠀⠀⠀⠀⠀⣿⡼⠁⠀⠉⠉⠀⠀⠀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡆⠀⠀⠀⠀⢿⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣧⠀⠀⠀⠀⠸⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡼⠁⠀⠀⠀⠀⠈⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡴⠒⢋⣁⡀⠀⠀⠀⠀⠀⠘⠢⢄⣀⠀⠀⠀⠀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠁⠉⠙⠒⠤⣘⣗⠒⠒⠒⠚⠛⠃⠀⠀⠀⠀⠀⠀
// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
contract RecursiveTrees is ERC721AQueryable {
uint public constant DEFAULT_GROW_PERIOD = 50 days;
uint constant HARVEST_PERIOD = 2 weeks;
uint constant DEFAULT_FRUIT_ODDS = 5_00;
uint public constant MAX_TREES = 5_000;
uint TREE_COUNTER = 0;
uint public constant PRICE = .03 ether;
uint constant MAX_MINT = 100;
uint constant ETH_PER_SECOND = .5 ether / DEFAULT_GROW_PERIOD; // amount of eth to speed growing up by 1 day
// extra tree variables:
uint public constant FRUIT_TOKEN_TREE_PRICE = 1_000 ether;
uint public constant EXTRA_TREES = 2_000;
uint public EXTRA_TREE_COUNTER = 0;
uint public MAX_FRUIT_TOKENS = 1_000_000 ether;
uint public totalDonated;
// address for One Tree Planted provided by Endaoment
// https://app.endaoment.org/orgs/46-4664562
// verify here: https://etherscan.io/address/0x42dc3bb63d6763a9e73948a1155a5538471071e4
address public constant ONE_TREE_PLANTED = 0x42dC3bB63d6763a9E73948a1155a5538471071e4;
address public immutable fruitToken;
ISeedGenerator seedGenerator;
// minified version on arweave:
// https://arweave.net/TisX5PFE_Czc0UkTftoPBNrAi2KW1_0CZfBcknCvGpY
string public keccakSrc = "https://cdn.jsdelivr.net/npm/keccak256@latest/keccak256.js";
mapping(uint => string[6]) private _colorIdToColors;
mapping(uint => uint) private _idToPackedTreeData;
mapping(uint => uint) private _idToMinter;
mapping(uint => uint) private _idToRenderMethod; // 1 == onchain render, 2 == off chain render
address public owner; // only used to set new keccak256 source
error CantOperateOnThisTree();
error HarvestPeriodNotReached();
error FruitPickPeriodNotReached();
error IncorrectMsgValue();
error TreeDoesNotExist();
error ExceedsTreeMax();
error ExceedsMaxPerMint();
error MaxFruitReached();
error MustWaterWithEth();
error OnlyOwner();
function treeExists(uint id) private view {
if(!_exists(id)) revert TreeDoesNotExist();
}
function onlyTreeOwner(uint id) private view {
if(msg.sender != ownerOf(id)) revert CantOperateOnThisTree();
}
function onlyOwner() private view {
if(msg.sender != owner) revert OnlyOwner();
}
constructor(address fruit, address seedGen) ERC721A("Recursive Trees", "TREES") {
fruitToken = fruit;
seedGenerator = ISeedGenerator(seedGen);
owner = msg.sender;
IFruitToken(fruit).setTrees();
// grass, sky, branch, leaf, fruit, clouds
_colorIdToColors[1] = ['#9ad18b','#ADD8E6','#6B4E31','#FF69B4','#FFD700', '#fffab5'];
_colorIdToColors[2] = ['#5a6328','#eaebbf','#49271f','#51b0ff','#ff3d8f', '#ff9ec7'];
_colorIdToColors[3] = ['#2d3319','#f2e9e4','#783114','#9ad18b','#e94f37', '#bfe7ff'];
_colorIdToColors[4] = ['#b05736','#deca8b','#251711','#9ad18b','#9e00ff', '#eaebbf'];
_colorIdToColors[5] = ['#228b22','#87ceeb','#23130f','#89963d','#ff3d41', '#ffffff'];
}
/**
* @notice override this from ERC721A so the first token id is 1.
*/
function _startTokenId() internal view override returns (uint256) {
return 1;
}
/**
* @notice public function to withdraw all ether in this contract and send to charity.
* @dev
*/
function withdraw() public {
unchecked {totalDonated += address(this).balance;}
ONE_TREE_PLANTED.call{value: address(this).balance}("");
}
/**
* @notice Allows contract owner to update the source for the keccak256 javascript library used in on the off chain svg rendering.
* @param newSrc updated url.
*/
function setKeccakSrc(string memory newSrc) external {
onlyOwner();
keccakSrc = newSrc;
}
function setOwner(address newOwner) external {
onlyOwner();
owner = newOwner;
}
/**
* @notice internal function to create a new tree and store it.
* @dev using uint48 to store timestamps more efficiently. since type(uint48).max = 281,474,976,710,655,.
that number in seconds equals about 8,925,512 years. so a uint48 as a timestamp will over flow 8,925,459 from now
eth is stored in uint72. will overflow if 4,722.366 ether is sent. will only affect the display
returns a packed uint with all the data inside
* @param id token id.
* @param timestamp time stamp of this function call.
* @param eth amount of eth sent with tx.
*/
function _createTree(uint id, uint timestamp, uint eth) private view returns(uint packedTreeData) {
packedTreeData = timestamp; //uint 48 || time tree was planted
packedTreeData |= timestamp + DEFAULT_GROW_PERIOD + HARVEST_PERIOD << 48; // uint 48 || time of next harvest
packedTreeData |= seedGenerator.fruitSeed(id) << 96; // uint 48 || starting fruit seed
packedTreeData |= eth << 144; //uint 72 || ether the tree received, usually its set to the mint price here, unless planted with fruit tokens
packedTreeData |= DEFAULT_FRUIT_ODDS << 216; // uint 16 || starting fruit odds
packedTreeData |= 0 << 232; // uint 24 || total fruit harvested
}
/**
* @notice plants 1 new tree with ether.
* @return uint id of the tree just planted.
*/
function plantTree() external payable returns (uint) {
if(++TREE_COUNTER > MAX_TREES) revert ExceedsTreeMax();
if(msg.value != PRICE) revert IncorrectMsgValue();
uint id = _nextTokenId();
_idToPackedTreeData[id] = _createTree(id, block.timestamp, msg.value);
_idToMinter[id] = uint(uint160(msg.sender));
_safeMint(msg.sender, 1);
return id;
}
/**
* @notice plant trees in batches, up to 100 at once.
* @param amount amount to plant.
*/
function batchPlant(uint amount) external payable {
if(amount > MAX_MINT) revert ExceedsMaxPerMint();
if(msg.value != (amount * PRICE)) revert IncorrectMsgValue();
unchecked {
TREE_COUNTER += amount;
}
if(TREE_COUNTER > MAX_TREES) revert ExceedsTreeMax();
uint startingId = _nextTokenId();
for(uint i=0; i<amount;) {
uint id = startingId+i;
_idToPackedTreeData[id] = _createTree(id, block.timestamp, PRICE);
_idToMinter[id] = uint(uint160(msg.sender));
unchecked {
i++;
}
}
_safeMint(msg.sender, amount);
}
/**
* @notice Plant a tree using fruit tokens, burning the fruit tokens. costs 1,000 fruit tokens
* @return uint id of the tree planted.
*/
function plantTreeWithFruitTokens() external returns (uint) {
if(++EXTRA_TREE_COUNTER > EXTRA_TREES) revert ExceedsTreeMax();
IFruitToken(fruitToken).burn(FRUIT_TOKEN_TREE_PRICE, msg.sender);
uint id = _nextTokenId();
_idToPackedTreeData[id] = _createTree(id, block.timestamp, 0);
_idToMinter[id] = uint(uint160(msg.sender));
_safeMint(msg.sender, 1);
return id;
}
/**
* @notice returns id of the last token minted.
*/
function currentId() external view returns(uint) {
return _nextTokenId()-1;
}
/**
* @notice toggle between on chain and off chain svg rendering.
* @param id token id.
Requirements:
- caller must be owner of id
*/
function toggleRenderMethod(uint id) external {
onlyTreeOwner(id);
uint state = _idToRenderMethod[id];
_idToRenderMethod[id] = state < 2 ? 2 : 1;
}
/**
* @notice returns the percent a tree is grown. multiplied by 100.
* @param tree tree.
*/
function _getPercentGrown(Tree memory tree) private view returns(uint percent) {
uint age = block.timestamp - tree.timestamp;
uint growPeriod = getGrowPeriod(tree);
if(age >= growPeriod) {
percent = 100_00;
}
else {
percent = age * 100_00 / growPeriod;
}
}
/**
* @notice returns the parameters used to generate the trees..
* @param id token id.
*/
function _getStartingParams(uint id) private view returns(StartingParams memory params, StaticParams memory staticParams) {
uint timestamp = block.timestamp;
Tree memory tree = unPackTree(_idToPackedTreeData[id]);
uint percentGrown = _getPercentGrown(tree);
uint seed = _getSeed(id, tree.timestamp);
uint fruitRadius;
uint startGrow = tree.nextHarvest - 1 weeks;
// if the current timestamp is inside the 1 week period where fruit is growing
// calculates the size of fruit by mapping the position in the grow period to 1-5
if(timestamp > startGrow && timestamp < tree.nextHarvest) {
uint percent = ((timestamp - startGrow) * 10) / 1 weeks;
fruitRadius = ((4 * percent) / 10) + 1;
}
// if the timestamp is past the next harvest, return 5
else if(timestamp >= tree.nextHarvest) {
fruitRadius = 5;
}
else {
fruitRadius = 0;
}
string[6] memory colors = _colorIdToColors[pickColor(seed)];
// these parameters are passed to each call in the recursion, but they never change so we keep these separate
staticParams = StaticParams({
fruitOdds: tree.fruitOdds,
fruitRadius: fruitRadius,
fruitColor: colors[4],
leafColor: colors[3],
angleScaler: scaleByPercent(75, percentGrown) + 25,
fruitStart: timestamp < startGrow //true = fruit is not growing, false == fruit is growing
});
// these values are updated each time the function is called in the recursion
params = StartingParams({
angle: 0,
y1: 540,
length: scaleByPercent(90, percentGrown),
width: scaleByPercent(30_000, percentGrown),
direction: 1,
seed: seed,
fruitLocationSeed: tree.fruitSeed
});
}
function _getSeed(uint id, uint timestamp) internal view returns(uint) {
unchecked {
return uint(uint160(uint(keccak256(abi.encode(id + _idToMinter[id] + timestamp)))));
}
}
/**
* @notice returns most of the tree data for `id`.
* for UI purposes.
* @param id token id.
*/
function getTreeData(uint id) external view returns(TreeData memory treeData) {
Tree memory tree = unPackTree(_idToPackedTreeData[id]);
uint seed = _getSeed(id, tree.timestamp);
treeData.fruitSeed = tree.fruitSeed;
treeData.fruitOdds = tree.fruitOdds;
treeData.treeSeed = seed;
treeData.colorId = pickColor(seed);
treeData.totalHarvested = tree.totalHarvested;
treeData.age = block.timestamp - tree.timestamp;
treeData.percentGrown = _getPercentGrown(tree);
treeData.ethReceived = tree.totalEthReceived;
treeData.nextHarvest = tree.nextHarvest;
treeData.plantedAt = tree.timestamp;
treeData.renderMethod = _idToRenderMethod[id] == 2;
treeData.clouds = pickClouds(seed);
}
/**
* @notice returns the token uri for `id`.
* @dev might fail if tree is too big.
* @param id token id.
*/
function tokenURI(uint id) public view override(ERC721A, IERC721A) returns(string memory) {
treeExists(id);
Tree memory tree = unPackTree(_idToPackedTreeData[id]);
uint percentGrown = _getPercentGrown(tree);
SVG memory svg = _getSvg(id);
bool renderMethod = _idToRenderMethod[id] == 2;
string memory _svg;
uint fruit;
if(renderMethod) {
_svg = svg.generateSvgWithScript();
}
else {
(_svg, fruit) = svg.generateRawSvg();
}
// if current time is before the grow period, set fruit to zero,
// otherwise (if its during or after the grow period) we leave it alone
block.timestamp < tree.nextHarvest - 1 weeks ? fruit = 0 : fruit;
TokenURI memory uri = TokenURI({
renderMethod: renderMethod,
svgString: bytes(_svg),
ethAsString: _formatEth(tree.totalEthReceived),
percentGrown: percentGrown,
id: id,
age: block.timestamp - tree.timestamp,
fruit: fruit,
cloudSeed: svg.cloudSeed,
colorId: pickColor(svg.startingParams.seed),
totalHarvested: tree.totalHarvested
});
return uri.getTokenURI();
}
/**
* @notice returns raw svg code as a string for tree # `id`.
* @param id token id.
*/
function getRawSvg(uint id) external view returns (string memory svgString) {
treeExists(id);
SVG memory svg = _getSvg(id);
(svgString,) = svg.generateRawSvg();
}
/**
* @notice returns an SVG struct for `id`
* @param id token id.
*/
function _getSvg(uint id) private view returns(SVG memory svg) {
(StartingParams memory startingParams, StaticParams memory staticParams) = _getStartingParams(id);
bool clouds = pickClouds(startingParams.seed);
string[6] memory colors = _colorIdToColors[pickColor(startingParams.seed)];
svg = SVG({
colors: colors,
staticParams: staticParams,
startingParams: startingParams,
keccakSrc: keccakSrc,
cloudSeed: clouds ? id : 0
});
}
/**
* @notice harvests fruit for tree #`id`. Also updates fruit seed and next harvest time.
Also mints fruit tokens to msg.sender 1:1 for each fruit
* @param id token id.
* Requirements:
- msg.sender must be the owner of the tree being harvested
*/
function harvestFruit(uint id) external {
onlyTreeOwner(id);
uint fruitTokenSupply = IFruitToken(fruitToken).totalSupply();
if(fruitTokenSupply >= MAX_FRUIT_TOKENS) revert MaxFruitReached();
Tree memory tree = unPackTree(_idToPackedTreeData[id]);
uint currentTime = block.timestamp;
if(currentTime < tree.nextHarvest) revert HarvestPeriodNotReached();
uint totalFruit = calculateFruit(id);
uint mintAmount = totalFruit * 1 ether;
if(mintAmount == 0) revert();
unchecked{
if(fruitTokenSupply + mintAmount > MAX_FRUIT_TOKENS) {
mintAmount = MAX_FRUIT_TOKENS - fruitTokenSupply;
}
tree.fruitSeed = seedGenerator.fruitSeed(id);
tree.nextHarvest = currentTime + HARVEST_PERIOD;
tree.totalHarvested += mintAmount / 1 ether;
}
_idToPackedTreeData[id] = packTree(tree);
IFruitToken(fruitToken).harvest(msg.sender, mintAmount);
}
/**
* @notice Allows users to update fruit seed and next harvest time with out spending gas to count the fruit.
does not mint fruit tokens
* @dev `ownerOf()` also checks for token existance, so we dont need to.
* @param id token id.
* Requirements:
* - `id` must exist
* - msg.sender must be owner of `id`
*/
function pickFruit(uint id) external {
onlyTreeOwner(id);
Tree memory tree = unPackTree(_idToPackedTreeData[id]);
uint currentTime = block.timestamp;
if(currentTime < tree.nextHarvest - 1 weeks) revert FruitPickPeriodNotReached();
unchecked {
tree.fruitSeed = seedGenerator.fruitSeed(id);
tree.nextHarvest = currentTime + HARVEST_PERIOD;
_idToPackedTreeData[id] = packTree(tree);
}
}
function getGrowPeriod(Tree memory tree) private view returns (uint) {
return tree.nextHarvest - tree.timestamp - HARVEST_PERIOD;
}
/**
* @notice If called while tree #`id` is growing, this function will speed the growing process depending on how much ether is sent.
if it called after the tree is fully grown, the functions increases the fruit odds depending on how much ether is sent.
* @param id token id.
* Requirements:
* - tree #`id` must exist.
*/
function water(uint id) external payable {
treeExists(id);
if(msg.value == 0) revert MustWaterWithEth();
Tree memory tree = unPackTree(_idToPackedTreeData[id]);
uint age = block.timestamp - tree.timestamp;
uint growPeriod = getGrowPeriod(tree);
// eth is stored as a uint72, will overflow at 4,722 eth, only affects metadata
tree.totalEthReceived += msg.value;
if(age < growPeriod) {
uint reducedTime = msg.value / ETH_PER_SECOND;
reducedTime >= growPeriod - age ? tree.nextHarvest = block.timestamp + HARVEST_PERIOD : tree.nextHarvest -= reducedTime;
}
else {
uint newOdds = tree.fruitOdds + (msg.value / .0005 ether);
// make sure it does not pass 100% odds
tree.fruitOdds = (newOdds > 100_00) ? 100_00 : newOdds;
}
_idToPackedTreeData[id] = packTree(tree);
}
/**
* @notice recursivly counts the fruit on tree #`id`. If current timestamp is during the first week of grow period,
automatically returns 0.
* @dev .
* @param id .
* Requirements:
* - tree #`id` must exist.
*/
function calculateFruit(uint id) public view returns(uint) {
treeExists(id);
uint nextHarvest = unPackTree(_idToPackedTreeData[id]).nextHarvest;
(StartingParams memory params, StaticParams memory staticParams) = _getStartingParams(id);
if(block.timestamp < nextHarvest - 1 weeks) {
return 0;
}
else {
(uint fruit,) = _calculateFruit(params.length, params.y1, params.seed, 0, params.fruitLocationSeed, staticParams.fruitOdds);
return fruit;
}
}
/**
* @notice Helper function only used by `formatEth`. Used to slice strings at an index.
* @param str eth in wei as a string.
* @param index where to put the decimal place.
* @param direction direction .
`str` must be in calldata, because string indices are only available in calldata im pretty sure.
must be external because it must be called like this: `this.splice()` (see `formatEth`) in order to pass a string
in memory as a string in calldata.
*/
function splice(string calldata str, uint index, bool direction) external pure returns(string memory) {
if(direction) {return(str[:index]);}
else { return(str[index: index+2]);}
}
/**
* @notice Helper function to format eth in wei as a uint, to eth with a decimal point as a string. Only for display purposes.
* @dev .
* @param amount eth in wei.
* @return string eth as a string.
*/
function _formatEth(uint amount) private view returns (string memory) {
string memory amountAsString = _toString(amount);
if(bytes(amountAsString).length > 18) {
uint decimalIndex = bytes(amountAsString).length - 18;
return string.concat(
this.splice(amountAsString, decimalIndex, true),
".",
this.splice(amountAsString, decimalIndex, false));
}
while(bytes(amountAsString).length < 18) {
amountAsString = string.concat("0", amountAsString);
}
return string.concat("0.", this.splice(amountAsString, 2, true));
}
}
pragma solidity 0.8.13;
import {
toString,
Tree,
StaticParams,
StartingParams
} from "./utils.sol";
struct SVG {
string[6] colors;
string keccakSrc;
uint cloudSeed;
StaticParams staticParams;
StartingParams startingParams;
}
/**
* @notice returns an svg image with an internal script that generates a tree.
* @param self svg struct.
* @return string svg code as a string.
*/
function generateSvgWithScript(SVG memory self) view returns(string memory) {
string memory clouds = self.cloudSeed != 0 ? getClouds(self.cloudSeed, self.colors[5]) : ""; // cloudseed is the token id, 0 means the tree doesnt have clouds
string memory params = string.concat(
"const p = {a: ",
toString(self.startingParams.angle),
", as: ",
toString(self.staticParams.angleScaler),
", y1: ",
toString(self.startingParams.y1),
", l: ",
toString(self.startingParams.length),
", w: ",
toString(self.startingParams.width),
", d:",
self.startingParams.direction == 0 ? "true" : "false",
", s: BigInt('"
);
params = string.concat(
params,
toString(self.startingParams.seed),
"'),fls: BigInt('",
toString(self.startingParams.fruitLocationSeed),
"'),fo: ",
toString(self.staticParams.fruitOdds),
",fr: ",
toString(self.staticParams.fruitRadius),
",f: ",
self.staticParams.fruitStart ? "true" : "false",
"}"
);
string memory start = getSvgStart(clouds, self.colors[1], self.colors[0], self.colors[2],self.staticParams, true);
string memory script = ",xmls='http://www.w3.org/2000/svg';function uintHash(t){return BigInt('0x'+keccak256('0x'+(hexString=t.toString(16)).padStart(64,'0')).toString('hex'))}function lr(t,e){return~~(t*(Number(e%BigInt(25))+65)/100)}function wr(t,e){return t<200?200:(t*(Number(e%BigInt(20))+55)/100).toFixed(2)}function gfl(t,e){if(Number(uintHash(t)%BigInt(10000))<p.fo && !p.f){let r=document.createElementNS(xmls,'circle');return r.setAttribute('cx','400'),r.setAttribute('r',p.fr),r.setAttribute('cy',e-p.fr),r.setAttribute('id','f'),r}{let i=Math.floor(2*p.as/100+2),n=document.createElementNS(xmls,'ellipse');return n.setAttribute('class','l'),n.setAttribute('cx','400'),n.setAttribute('cy',2*i<=e?e-2*i:0),n.setAttribute('rx',i),n.setAttribute('ry',2*i),n}}function tree(t,e,r,i,n,u,l){if(i<=4||r<i)return gfl(l,r);let a=uintHash(u),d=uintHash(u+BigInt('1')),$=lr(i,a),c=lr(i,d),s=wr(n,a),h=wr(n,d),o=Number(a%BigInt(30))+10,g=Number(d%BigInt(30))+10;o=Math.floor(o*p.as/100),g=Math.floor(g*p.as/100);let f=createBranch(t,e,r,i,n),b=tree(!1,o,r-=i,$,s,u+BigInt(3),l+BigInt(3)),A=tree(!0,g,r,c,h,u+BigInt(23),l+BigInt(23));return'g'==b.nodeName||'g'==A.nodeName?(f.appendChild(b),f.appendChild(A)):'circle'===A.nodeName?f.appendChild(A):f.appendChild(b),f}function createBranch(t,e,r,i,n){let u=t?`-${e}`:`${e}`,l=document.createElementNS(xmls,'g');l.setAttribute('transform','rotate('+u+',400,'+r+')');let a=document.createElementNS(xmls,'line');return a.setAttribute('x1','400'),a.setAttribute('y1',r),a.setAttribute('x2','400'),a.setAttribute('y2',r-i),a.setAttribute('stroke-width',n/1e3 < .5 ? .5 : (n/1e3).toFixed(3)),l.appendChild(a),l}function drawSvg(){let t=document.getElementById('starting'),e=tree(p.d,p.a,p.y1,p.l,p.w,p.s,p.fls);t.appendChild(e)}]]></script>";
return (string.concat(start, "</g></g>", "<script xlink:href='", self.keccakSrc, "'></script><script type='text/javascript'><![CDATA[", params, script, "</svg>"));
}
/**
* @notice returns svg code for the entire tree, also counts the fruit are on the tree.
* @param self svg struct.
* @return string svg code as a string.
* @return uint amount of fruit.
*/
function generateRawSvg(SVG memory self) view returns(string memory, uint) {
string memory clouds = self.cloudSeed != 0 ? getClouds(self.cloudSeed, self.colors[5]) : "";
(string memory tree, uint fruit,) = treeRecursion(self.startingParams, self.staticParams,0);
string memory start = getSvgStart(clouds, self.colors[1], self.colors[0], self.colors[2],self.staticParams,false);
return (string.concat(start, tree, "</g></g></svg>"), fruit);
}
using {generateRawSvg, generateSvgWithScript} for SVG global;
/////////////////////////////////////////////////// utils ////////////////////////////////////////////////////////////
/**
* @notice returns svg code for a group element with a line element inside of it.
* @dev .
* @param params params.
* @return line svg code as a string.
*/
function createLine(StartingParams memory params) pure returns (string memory line) {
string memory y1Str = toString(params.y1);
uint decimals = params.width % 1000;
uint integer = params.width / 1000;
string memory width = string.concat(toString(integer), decimals < 100 ? ".0" : ".", toString(integer == 0 && decimals < 500 ? 5 : decimals));
line = string.concat(
"<g transform='rotate(",
params.direction == 0 ? string.concat("-", toString(params.angle)) : toString(params.angle),
",400,",
y1Str,
")'><line x1='400' y1='",
y1Str,
"' x2='400' y2='",
toString(params.y1 - params.length),
"' stroke-width='",
width,
"'/>"
);
}
/**
* @notice updates parameters at each recursion.
* @param params params struct.
* @param angleScaler amount to scale the angles by.
*/
function updateParams(StartingParams memory params, uint angleScaler) pure returns(StartingParams memory params1,StartingParams memory params2) {
unchecked {
uint uintHash = (uint(keccak256(abi.encodePacked(params.seed))));
uint uintHashPlus1 = (uint(keccak256(abi.encodePacked(params.seed + 1))));
params1 = StartingParams({
angle: getAngle(angleScaler, uintHash),
y1: params.y1 - params.length,
length: lengthReducer(params.length, uintHash),
width: widthReducer(params.width, uintHash),
direction: 1,
seed: params.seed + 3,
fruitLocationSeed: params.fruitLocationSeed + 3
});
params2 = StartingParams({
angle: getAngle(angleScaler, uintHashPlus1),
y1: params.y1 - params.length,
length: lengthReducer(params.length, uintHashPlus1),
width: widthReducer(params.width, uintHashPlus1),
direction: 0,
seed: params.seed + 23 ,
fruitLocationSeed: params.fruitLocationSeed + 23
});
}
}
function treeRecursion(StartingParams memory params, StaticParams memory staticParams, uint totalFruit) pure returns(string memory, uint,uint) {
if(params.length < 5 || params.y1 < params.length){
return returnFruitOrLeaf(params, staticParams, totalFruit);
}
string memory start = createLine(params);
(StartingParams memory params1, StartingParams memory params2) = updateParams(params, staticParams.angleScaler);
(string memory branch1, uint totalFruit1, uint fruitOrLeaf1) = treeRecursion(params1,staticParams,totalFruit);
(string memory branch2, uint totalFruit2, uint fruitOrLeaf2) = treeRecursion(params2,staticParams,totalFruit);
// 0=branch, 1=leaf, 2=fruit
// if either one is a branch, we append both
if(fruitOrLeaf1 == 0 || fruitOrLeaf2 == 0) {
// saves gas for totalFruit1 + totalFruit2
// we also pass a 0 as fruitOrLeaf since this function returned a line
unchecked {
return (string.concat(start,branch1, branch2, "</g>"), totalFruit1 + totalFruit2, 0);
}
}
// these checks prevent duplicates:
// if fruitOrLeaf2 is a fruit, we append only branch2 and totalFruit2
else if( fruitOrLeaf2 == 2 ) {
return (string.concat(start,branch2, "</g>"), totalFruit2, 0);
}
// if they are both leaves, both fruit, or fruitOrLeaf1 is a fruit, we append only fruitOrLeaf1
else {
return (string.concat(start,branch1, "</g>"), totalFruit1, 0);
}
}
function lengthReducer(uint number, uint uintHash) pure returns(uint) {
uint multiplier;
uint newNumber;
unchecked {
multiplier = (uintHash % 25 ) + 65;
newNumber = (number * multiplier) / 100;
}
return newNumber;
}
// moving clouds function
function getClouds(uint seed, string memory fill) view returns(string memory) {
string memory start = "<filter id='t'><feTurbulence baseFrequency='0.03' seed='";
string memory mid = "' type='fractalNoise' numOctaves='3' result='noise' /><feDisplacementMap xChannelSelector='R' yChannelSelector='G' scale='50' in='SourceGraphic' /></filter><g fill='";
string memory ellipses;
for(uint i=1; i<=200;) {
unchecked {
uint blockHash = uint(blockhash(block.number - i)) + seed;
if(uint(keccak256(abi.encodePacked(blockHash))) % 50 == 1) {
// gives us number from 6-13. 6 is the slowest they can go and still go the whole way across
uint speed = (uint(keccak256(abi.encodePacked(blockHash + 1))) % 8) + 6;
uint distance = (speed * i);
uint translate = distance < 1200 ? 1200 - distance : 0;
// gets a number between 80-229
uint cy = (uint(keccak256(abi.encodePacked(blockHash + 2))) % 150) + 80;
// gets a number between 50-199
uint rx = (uint(keccak256(abi.encodePacked(blockHash + 3))) % 150) + 50;
// gets a number between 30-99
uint ry = (uint(keccak256(abi.encodePacked(blockHash + 4))) % 70) + 30;
// if the translate value is 0, then we dont add that cloud
translate > 0 ? ellipses = string.concat(ellipses, "<ellipse filter='url(#t)' transform='translate(", toString(translate), ")' cx='-200' cy='", toString(cy), "' rx='", toString(rx), "' ry='", toString(ry), "'/>") : ellipses;
}
i++;
}
}
return string.concat(start, toString(seed), mid, fill, "'>", ellipses, "</g>");
}
function widthReducer(uint number, uint uintHash) pure returns(uint) {
if(number < 200) {
return 200;
}
uint multiplier;
uint newNumber;
unchecked{
multiplier = (uintHash % 20 ) + 55;
newNumber = number * multiplier;
}
return (newNumber / 100);
}
function getAngle(uint scaler, uint uintHash) pure returns(uint newAngle) {
unchecked {
newAngle = (uintHash % 30) + 10;
// scale
newAngle = (newAngle * scaler) / 100;
}
}
function getSvgStart(string memory clouds, string memory skyFill, string memory grassFill, string memory branchFill, StaticParams memory staticParams, bool onload) pure returns(string memory) {
uint rx;
uint ry;
unchecked{
rx = ((2* staticParams.angleScaler) / 100) + 2;
ry = rx*2;
}
string memory start = string.concat(
"<svg id='svg' viewBox='0 0 800 800' width='800' height='800' ",
onload ? "onload='drawSvg()' " : " ",
"xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><rect id='sky' width='800' height='500' fill='",
skyFill,
"'/><style>.l {stroke-width: .3; fill:",
staticParams.leafColor,
";} circle {fill:",
staticParams.fruitColor,
";stroke-width: .3}</style><rect id='grass' y='500' width='800' height='300' fill='",
grassFill,
"'/> <clipPath id='clip'><rect width='800' height='800' /></clipPath><g clip-path='url(#clip)'>",
clouds,
"<g id='starting' stroke='",
branchFill,
"' stroke-linecap='round'>"
);
return start;
}
function returnFruitOrLeaf(StartingParams memory params, StaticParams memory staticParams, uint totalFruit) pure returns(string memory, uint,uint) {
bool fruitOrLeaf = (uint(keccak256(abi.encodePacked(params.fruitLocationSeed))) % 100_00 ) < staticParams.fruitOdds;
uint rx;
uint ry;
uint cy;
if(!fruitOrLeaf || staticParams.fruitStart) {
unchecked {
rx = ((2* staticParams.angleScaler) / 100) + 2;
ry = rx*2;
cy = ry <= params.y1 ? params.y1 - ry : 0;
}
return (string.concat("<ellipse class='l' cx='400' cy='", toString(cy), "' rx='",toString(rx), "' ry='", toString(ry), "'/>"), totalFruit,1);
}
else {
unchecked {
totalFruit++;
cy = staticParams.fruitRadius > params.y1 ? 0 : params.y1-staticParams.fruitRadius;
}
return (string.concat("<circle cx='400' cy='", toString(cy), "' r='", toString(staticParams.fruitRadius), "'/>"), totalFruit,2);
}
}
pragma solidity 0.8.13;
import '@openzeppelin/contracts/utils/Base64.sol';
import {
toString,
Tree,
formatDays,
formatPercent
} from "./utils.sol";
struct TokenURI {
bool renderMethod;
bytes svgString;
string ethAsString;
uint percentGrown;
uint id;
uint age;
uint fruit;
uint cloudSeed;
uint colorId;
uint totalHarvested;
}
function getTokenURI(TokenURI memory self) pure returns(string memory) {
string memory attributes = getAttributes(
self.colorId,
self.totalHarvested,
self.percentGrown,
self.age,
self.fruit,
self.renderMethod,
self.cloudSeed,
self.ethAsString
);
bytes memory json = getJson(self.id, Base64.encode(self.svgString), attributes, self.renderMethod);
return string.concat("data:application/json;base64,",Base64.encode(json));
}
function getAttributes(uint colorId,
uint totalHarvested,
uint percentGrown,
uint age,
uint fruit,
bool renderMethod,
uint cloudSeed,
string memory ethAsString
) pure returns(string memory attributes) {
attributes = string.concat(
'"attributes": [{"trait_type": "color", "value":"',
colorId == 1 ? "ultra rare" : colorId == 2 ? "very rare" : colorId == 3 ? "rare" : colorId == 4 ? "semi rare" : "common",
'"}, ',
percentGrown < 10000 ? string.concat('{"trait_type": "Percent Grown", "value":"', formatPercent(percentGrown),'"}, ') : "",
fruit > 0 ? string.concat('{"trait_type": "Fruit", "value":"', toString(fruit),'"}, ') : "",
'{"trait_type": "Total Harvested", "value":"',
toString(totalHarvested)
);
attributes = string.concat(
attributes,
'"}, {"trait_type": "Age", "value":"',
formatDays(age),
' days"},',
renderMethod ? '{"trait_type": "Render Method", "value": "off chain"},' : '',
cloudSeed != 0 ? '{"trait_type": "Clouds", "value":"yes"},' : '',
'{"trait_type": "Donated", "value":"',
ethAsString,
' eth"}]'
);
}
function getJson(uint id, string memory encodedSvg, string memory attributes, bool renderMethod) pure returns(bytes memory json) {
string memory animationUrl = Base64.encode(abi.encodePacked('<!DOCTYPE html><html><body style="margin:0;"><object type="image/svg+xml" width="800" height="800" data="data:image/svg+xml;base64,', encodedSvg, '" alt="tree"></object></body> </html>'));
json = abi.encodePacked(
'{"name": "Recursive Tree #',
toString(id),
'", "description": "Just some trees that live on Ethereum.", "image": "data:image/svg+xml;base64,',
encodedSvg,
renderMethod ? string.concat('", "animation_url": "data:text/html;base64,', animationUrl) : "",
'",',
attributes,
'}');
}
using {getTokenURI} for TokenURI global;
pragma solidity 0.8.13;
interface IFruitToken {
function harvest(address to, uint fruitAmount) external;
function burn(uint amount, address owner) external;
function burn(uint amount) external;
function totalSupply() external returns (uint);
function maxTokens() external returns (uint);
function setTrees() external;
}
interface ISeedGenerator {
function fruitSeed(uint id) external view returns(uint);
}
pragma solidity 0.8.13;
struct Tree {
uint timestamp; // when it was planted aka minted
uint nextHarvest;
uint fruitSeed; // seed to determine fruit locations and amounts, this changes everytime its harvested
uint fruitOdds; // percent chance that a leaf will be a fruit
uint totalEthReceived;
uint totalHarvested;
}
struct TreeData {
uint fruitSeed;
uint fruitOdds;
uint treeSeed;
uint colorId;
uint percentGrown;
uint totalHarvested;
uint age;
uint ethReceived;
uint nextHarvest;
uint plantedAt;
bool renderMethod;
bool clouds;
}
struct StaticParams {
uint fruitOdds;
uint fruitRadius;
string fruitColor;
string leafColor;
uint angleScaler;
bool fruitStart;
}
struct StartingParams {
uint angle;
uint y1;
uint length;
uint width;
uint seed;
uint fruitLocationSeed;
uint direction;
}
function log10(uint256 value) pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
function toString(uint256 value) pure returns (string memory) {
unchecked {
uint256 length = log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), "0123456789abcdef"))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function formatDays(uint age) pure returns (string memory) {
age *= 100;
age /= 1 days;
uint integer = age / 100;
uint decimals = age % 100;
return string.concat(toString(integer), ".",decimals < 10 ? "0" : "", toString(decimals), "");
}
function packTree(Tree memory tree) pure returns (uint packedTree) {
packedTree = tree.timestamp; //uint 48
packedTree |= tree.nextHarvest << 48; // uint 48
packedTree |= tree.fruitSeed << 96; // uint 48
packedTree |= tree.totalEthReceived << 144; //uint 72
packedTree |= tree.fruitOdds << 216; // uint 16
packedTree |= tree.totalHarvested << 232; // uint 24
}
function unPackTree(uint packedTree) pure returns (Tree memory tree) {
tree.timestamp = (uint48(packedTree));
tree.nextHarvest = (uint48(packedTree >> 48));
tree.fruitSeed = (uint48(packedTree >> 96));
tree.totalEthReceived = uint72(packedTree >> 144);
tree.fruitOdds = (uint16(packedTree >> 216));
tree.totalHarvested = (uint24(packedTree >> 232));
}
function formatPercent(uint percent) pure returns (string memory) {
// positionInGrowPeriod *= 10_000;
// uint percent = positionInGrowPeriod / growPeriod;
uint integer = percent / 100;
uint decimals = percent % 100;
return string(abi.encodePacked(toString(integer), ".", decimals < 10 ? "0" : "", toString(decimals)));
}
function scaleByPercent(uint max, uint percent) pure returns (uint) {
return (max * percent) / 10_000;
}
function _calculateFruit(uint length, uint y1, uint seed, uint fruit, uint fruitLocationSeed, uint fruitOdds) pure returns(uint,uint) {
uint multiplier;
uint newLength;
unchecked {
if(length < 5 || y1 < length){
bool fruitOrLeaf = (uint(keccak256(abi.encodePacked(fruitLocationSeed))) % 100_00 ) < fruitOdds;
if(!fruitOrLeaf) {
return (fruit,1);
}
else {
fruit += 1;
return (fruit,2);
}
}
multiplier = (uint(keccak256(abi.encodePacked(seed))) % 25 ) + 65;
newLength = (length * multiplier) / 100;
(uint fruit1, uint isFruit1) = _calculateFruit(newLength, y1 - length, seed + 3, fruit, fruitLocationSeed + 3, fruitOdds);
multiplier = (uint(keccak256(abi.encodePacked(seed+1))) % 25 ) + 65;
newLength = (length * multiplier) / 100;
(uint fruit2, uint isFruit2) = _calculateFruit(newLength, y1 - length, seed + 23, fruit, fruitLocationSeed + 23, fruitOdds);
if(isFruit1 == 2 && isFruit2 == 2) {
return (fruit1,0);
}
else {
return (fruit1 + fruit2,0);
}
}
}
function pickClouds(uint seed) pure returns(bool) {
return (uint(keccak256(abi.encodePacked(seed + 1))) % 100) < 50;
}
function pickColor(uint seed) pure returns(uint colorId) {
// we add 2 to the seed, because we also use the seed to determine clouds
uint colorOdds = uint(keccak256(abi.encodePacked(seed + 2))) % 1000;
if(colorOdds < 5) { // 0-4 =>.5%
colorId = 1;
}
else if(colorOdds >=5 && colorOdds < 25) {// 5-24 => 2%
colorId = 2;
}
else if(colorOdds >=25 && colorOdds<75) { // 25-74 => 5%
colorId = 3;
}
else if(colorOdds >=75 && colorOdds < 175) { // 75-174 => 10 %
colorId = 4;
}
else {
colorId = 5; // 82.5%
}
}
{
"compilationTarget": {
"src/RecursiveTrees.sol": "RecursiveTrees"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin/=lib/openzeppelin-contracts/",
":ds-test/=lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}
[{"inputs":[{"internalType":"address","name":"fruit","type":"address"},{"internalType":"address","name":"seedGen","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ApprovalCallerNotOwnerNorApproved","type":"error"},{"inputs":[],"name":"ApprovalQueryForNonexistentToken","type":"error"},{"inputs":[],"name":"BalanceQueryForZeroAddress","type":"error"},{"inputs":[],"name":"CantOperateOnThisTree","type":"error"},{"inputs":[],"name":"ExceedsMaxPerMint","type":"error"},{"inputs":[],"name":"ExceedsTreeMax","type":"error"},{"inputs":[],"name":"FruitPickPeriodNotReached","type":"error"},{"inputs":[],"name":"HarvestPeriodNotReached","type":"error"},{"inputs":[],"name":"IncorrectMsgValue","type":"error"},{"inputs":[],"name":"InvalidQueryRange","type":"error"},{"inputs":[],"name":"MaxFruitReached","type":"error"},{"inputs":[],"name":"MintERC2309QuantityExceedsLimit","type":"error"},{"inputs":[],"name":"MintToZeroAddress","type":"error"},{"inputs":[],"name":"MintZeroQuantity","type":"error"},{"inputs":[],"name":"MustWaterWithEth","type":"error"},{"inputs":[],"name":"OnlyOwner","type":"error"},{"inputs":[],"name":"OwnerQueryForNonexistentToken","type":"error"},{"inputs":[],"name":"OwnershipNotInitializedForExtraData","type":"error"},{"inputs":[],"name":"TransferCallerNotOwnerNorApproved","type":"error"},{"inputs":[],"name":"TransferFromIncorrectOwner","type":"error"},{"inputs":[],"name":"TransferToNonERC721ReceiverImplementer","type":"error"},{"inputs":[],"name":"TransferToZeroAddress","type":"error"},{"inputs":[],"name":"TreeDoesNotExist","type":"error"},{"inputs":[],"name":"URIQueryForNonexistentToken","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":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":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"},{"inputs":[],"name":"DEFAULT_GROW_PERIOD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EXTRA_TREES","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EXTRA_TREE_COUNTER","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FRUIT_TOKEN_TREE_PRICE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_FRUIT_TOKENS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_TREES","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ONE_TREE_PLANTED","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRICE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","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":"uint256","name":"amount","type":"uint256"}],"name":"batchPlant","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"calculateFruit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"explicitOwnershipOf","outputs":[{"components":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"uint64","name":"startTimestamp","type":"uint64"},{"internalType":"bool","name":"burned","type":"bool"},{"internalType":"uint24","name":"extraData","type":"uint24"}],"internalType":"struct IERC721A.TokenOwnership","name":"ownership","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"explicitOwnershipsOf","outputs":[{"components":[{"internalType":"address","name":"addr","type":"address"},{"internalType":"uint64","name":"startTimestamp","type":"uint64"},{"internalType":"bool","name":"burned","type":"bool"},{"internalType":"uint24","name":"extraData","type":"uint24"}],"internalType":"struct IERC721A.TokenOwnership[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fruitToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"getRawSvg","outputs":[{"internalType":"string","name":"svgString","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"getTreeData","outputs":[{"components":[{"internalType":"uint256","name":"fruitSeed","type":"uint256"},{"internalType":"uint256","name":"fruitOdds","type":"uint256"},{"internalType":"uint256","name":"treeSeed","type":"uint256"},{"internalType":"uint256","name":"colorId","type":"uint256"},{"internalType":"uint256","name":"percentGrown","type":"uint256"},{"internalType":"uint256","name":"totalHarvested","type":"uint256"},{"internalType":"uint256","name":"age","type":"uint256"},{"internalType":"uint256","name":"ethReceived","type":"uint256"},{"internalType":"uint256","name":"nextHarvest","type":"uint256"},{"internalType":"uint256","name":"plantedAt","type":"uint256"},{"internalType":"bool","name":"renderMethod","type":"bool"},{"internalType":"bool","name":"clouds","type":"bool"}],"internalType":"struct TreeData","name":"treeData","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"harvestFruit","outputs":[],"stateMutability":"nonpayable","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":[],"name":"keccakSrc","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","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":"uint256","name":"id","type":"uint256"}],"name":"pickFruit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"plantTree","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"plantTreeWithFruitTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","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":"string","name":"newSrc","type":"string"}],"name":"setKeccakSrc","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"str","type":"string"},{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"bool","name":"direction","type":"bool"}],"name":"splice","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"toggleRenderMethod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"tokensOfOwner","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"stop","type":"uint256"}],"name":"tokensOfOwnerIn","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDonated","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","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":"uint256","name":"id","type":"uint256"}],"name":"water","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]