// Contract: Smolbirds
// Target function: function safeTransferWhileNesting(
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

/*
Smolbirds:
    - Max Supply: 5.555 
    - Twitter: https://twitter.com/smolbirds_NFT
    - Discord: https://discord.gg/UWbptH9p8y

    ::::::::::::::::::::::::::::::::::::::::::
    ::::::::::::__:::::::::::::__:::::::::::::
    ::::::::::::_=___::_____:__,_:::::::::::::
    ::::::::::::_.==,__.,,,,__,,_:::::::::::::
    :::::::::::::_.,..,,,,==,._._:::::::::::::
    ::::::::::::::_...,,,,,=,,._::::::::::::::
    ::::::::::::::_..,,,,,,,,,,._:::::::::::::
    ::::::::::::::_..,:::,,,:::=_:::::::::::::
    ::::::::::::::_.=:,,::,::,,:_:::::::::::::
    ::::::::::::::_==,::,:::,::,_:::::::::::::
    ::::::::::::::_=,: ;:,:,: ;:_:::::::::::::
    ::::::::::::::_=,:  :,:,:  :_:::::::::::::
    ::::::::::::::_==,::,...,::,_:::::::::::::
    ::::::::::::::_.==,,.--.:,,:_:::::::::::::
    ::::::::::::::_..==::.-.:::=_:::::::::::::
    ::::::::::::::_....==:.:===._:::::::::::::
    :::::::::::::_...,,..===....._::::::::::::
    :::::::::::::_....,,,...,,,,._::::::::::::
    :::::::::::::_....,,,,,,,,,,._::::::::::::
    :::::::::::::_....,,,,,,,,,,._::::::::::::
*/

/**
 * @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();

    /**
     * The caller cannot approve to their own address.
     */
    error ApproveToCaller();

    /**
     * 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;

    /**
     * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @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;

    /**
     * @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;

    /**
     * @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);
}



contract Smolbirds is IERC721A { 

    address private _owner;
    function owner() public view returns(address){
        return _owner;
    }

    modifier onlyOwner() { 
        require(_owner==msg.sender);
        _; 
    }

    modifier nonContract(){
        require(!(msg.sender.code.length>0), "no contracts allowed");
        _;
    }
    

    uint256 public constant MAX_SUPPLY = 5555;
    uint256 public MAX_FREE = 5555;
    uint256 public MAX_FREE_PER_WALLET = 1;
    uint256 public COST = 0.003 ether;

    string private constant _name = "Smolbirds";
    string private constant _symbol = "SMOLBIRD";
    string private _baseURI = "QmX6oqwtPcwi3yV1garMNZeZGhM9W7vNHiqe8njqhHaYbz";

    constructor() {
        _owner = msg.sender;
    }

    function mint(uint256 amount) external payable{
        address _caller = _msgSenderERC721A();

        require(totalSupply() + amount <= MAX_SUPPLY, "Sold Out");
        require(amount*COST <= msg.value, "Value to Low");

        _mint(_caller, amount);
    }

    function freeMint() external nonContract{
        address _caller = _msgSenderERC721A();
        uint256 amount = 1;

        require(totalSupply() + amount <= MAX_FREE, "Freemint Sold Out");
        require(amount + _numberMinted(_caller) <= MAX_FREE_PER_WALLET, "Max per Wallet");

        _mint(_caller, amount);
    }

    // NESTING

    modifier onlyApprovedOrOwner(uint tokenId){
        address approvedAddress = _tokenApprovals[tokenId];
        address owner = ownerOf(tokenId);

        bool isApprovedOrOwner = (_msgSenderERC721A() == owner ||
                isApprovedForAll(owner, _msgSenderERC721A()) ||
                approvedAddress == _msgSenderERC721A());
        
        require(isApprovedOrOwner, "Not Owner, Not Approved");
        _;
    }
    /**
    @dev tokenId to nesting start time (0 = not nesting).
     */
    mapping(uint256 => uint256) private nestingStarted;

    /**
    @dev Cumulative per-token nesting, excluding the current period.
     */
    mapping(uint256 => uint256) private nestingTotal;


    function nestingPeriod(uint256 tokenId)
        external
        view
        returns (
            bool nesting,
            uint256 current,
            uint256 total
        )
    {
        uint256 start = nestingStarted[tokenId];
        if (start != 0) {
            nesting = true;
            current = block.timestamp - start;
        }
        total = current + nestingTotal[tokenId];
    }

    /**
    @dev MUST only be modified by safeTransferWhileNesting(); if set to 2 then
    the _beforeTokenTransfer() block while nesting is disabled.
     */
    uint256 private nestingTransfer = 1;