// Contract: AstroLama
// Target function: function tokenURI(uint256 tokenId) public view virtual returns (string memory)
x80)
        // Update the free memory pointer to allocate.
            mstore(0x40, str)

        // 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 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);
}

/**
 * @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) {
        TokenOwnership memory ownership;
        if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
            return ownership;
        }
        ownership = _ownershipAt(tokenId);
        if (ownership.burned) {
            return ownership;
        }
        return _ownershipOf(tokenId);
    }

    /**
     * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
     * See {ERC721AQueryable-explicitOwnershipOf}
     */
    function explicitOwnershipsOf(uint256[] calldata tokenIds)
    external
    view
    virtual
    override
    returns (TokenOwnership[] memory)
    {
    unchecked {
        uint256 tokenIdsLength = tokenIds.length;
        TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
        for (uint256 i; i != tokenIdsLength; ++i) {
            ownerships[i] = explicitOwnershipOf(tokenIds[i]);
        }
        return ownerships;
    }
    }

    /**
     * @dev Returns an array of token IDs owned by `owner`,
     * in the range [`start`, `stop`)
     * (i.e. `start <= tokenId < stop`).
     *
     * This function allows for tokens to be queried if the collection
     * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
     *
     * Requirements:
     *
     * - `start < stop`
     */
    function tokensOfOwnerIn(
        address owner,
        uint256 start,
        uint256 stop
    ) external view virtual override returns (uint256[] memory) {
    unchecked {
        if (start >= stop) revert InvalidQueryRange();
        uint256 tokenIdsIdx;
        uint256 stopLimit = _nextTokenId();
        // Set `start = max(start, _startTokenId())`.
        if (start < _startTokenId()) {
            start = _startTokenId();
        }
        // Set `stop = min(stop, stopLimit)`.
        if (stop > stopLimit) {
            stop = stopLimit;
        }
        uint256 tokenIdsMaxLength = balanceOf(owner);
        // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
        // to cater for cases where `balanceOf(owner)` is too big.
        if (start < stop) {
            uint256 rangeLength = stop - start;
            if (rangeLength < tokenIdsMaxLength) {
                tokenIdsMaxLength = rangeLength;
            }
        } else {
            tokenIdsMaxLength = 0;
        }
        uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
        if (tokenIdsMaxLength == 0) {
            return tokenIds;
        }
        // We need to call `explicitOwnershipOf(start)`,
        // because the slot at `start` may not be initialized.
        TokenOwnership memory ownership = explicitOwnershipOf(start);
        address currOwnershipAddr;
        // If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
        // `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
        if (!ownership.burned) {
            currOwnershipAddr = ownership.addr;
        }
        for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
            ownership = _ownershipAt(i);
            if (ownership.burned) {
                continue;
            }
            if (ownership.addr != address(0)) {
                currOwnershipAddr = ownership.addr;
            }
            if (currOwnershipAddr == owner) {
                tokenIds[tokenIdsIdx++] = i;
            }
        }
        // Downsize the array to fit.
        assembly {
            mstore(tokenIds, tokenIdsIdx)
        }
        return tokenIds;
    }
    }

    /**
     * @dev Returns an array of token IDs owned by `owner`.
     *
     * This function scans the ownership mapping and is O(`totalSupply`) in complexity.
     * It is meant to be called off-chain.
     *
     * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
     * multiple smaller scans if the collection is large enough to cause
     * an out-of-gas error (10K collections should be fine).
     */
    function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) {
    unchecked {
        uint256 tokenIdsIdx;
        address currOwnershipAddr;
        uint256 tokenIdsLength = balanceOf(owner);
        uint256[] memory tokenIds = new uint256[](tokenIdsLength);
        TokenOwnership memory ownership;
        for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
            ownership = _ownershipAt(i);
            if (ownership.burned) {
                continue;
            }
            if (ownership.addr != address(0)) {
                currOwnershipAddr = ownership.addr;
            }
            if (currOwnershipAddr == owner) {
                tokenIds[tokenIdsIdx++] = i;
            }
        }
        return tokenIds;
    }
    }
}


/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

contract AstroLama is ERC721AQueryable, Ownable {
    string public constant collectionName = "Astro Lama";
    string public constant collectionSymbol = "LAMA";
    uint256 public constant maxQuantityForMint = 5;
    uint256 public mintPrice = 0.036 ether;
    uint256 public mintWLPrice = 0.015 ether;
    uint256 public maxTotalSupply = 10_000;
    uint256 public mintStartAt = 0;
    uint256 public mintWlStartAt = 0;

    mapping(address => bool) public whitelist;
    mapping(uint256 => uint256) private randomId;

    string public baseTokenURI;
    string public hiddenBaseTokenURI;
    string public _contractURI;
    string public baseExtension = ".json";

    event Mint(address indexed to, uint256 quantity, uint256 _nextId, string _tokenUri);

    constructor() ERC721A(collectionName, collectionSymbol) {}

    modifier callerIsUser() {
        require(tx.origin == msg.sender, "The caller is another contract");
        _;
    }

    function gift(address to, uint256 quantity) external onlyOwner {
        if (to != owner()) {
            require(_numberMinted(to) + quantity <= maxQuantityForMint, "Gift quantity limit 5 per address");
        }
        require(totalSupply() + quantity <= maxTotalSupply, "Total supply would be exceeded");
        uint256 _nextId = randomizeTokens(quantity);
        _safeMint(to, quantity);

        emit Mint(to, quantity, _nextId, baseTokenURI);
    }

    function mint(uint256 quantity) external payable callerIsUser {
        uint256 currentPrice = quantity * mintPrice;

        require(block.timestamp >= mintStartAt, "Mint not started");
        require(quantity <= maxQuantityForMint, "Mint quantity limit 5");
        require(_numberMinted(_msgSenderERC721A()) + quantity <= maxQuantityForMint, "Mint quantity limit 5 per address");
        require(msg.value >= currentPrice, "Not enough payed");
        require(totalSupply() + quantity <= maxTotalSupply, "Total supply would be exceeded");

        uint256 _nextId = randomizeTokens(quantity);
        _safeMint(_msgSenderERC721A(), quantity);

        refundIfOver(currentPrice);

        emit Mint(_msgSenderERC721A(), quantity, _nextId, baseTokenURI);
    }

    function mintPrivate(uint256 quantity) external payable callerIsUser {
        uint256 currentPrice = quantity * mintWLPrice;

        require(block.timestamp >= mintWlStartAt, "Mint not started");
        require(whitelist[_msgSenderERC721A()], "Not in white list");
        require(_numberMinted(_msgSenderERC721A()) + quantity <= maxQuantityForMint, "Mint quantity limit 5 per address");
        require(quantity <= maxQuantityForMint, "Mint quantity limit 5");
        require(msg.value >= currentPrice, "Not enough payed");
        require(totalSupply() + quantity <= maxTotalSupply, "Total supply would be exceeded");

        uint256 _nextId = randomizeTokens(quantity);
        _safeMint(_msgSenderERC721A(), quantity);

        refundIfOver(currentPrice);

        emit Mint(_msgSenderERC721A(), quantity, _nextId, baseTokenURI);
    }

    function refundIfOver(uint256 price) private {
        require(msg.value >= price, "Need to send more ETH.");
        if (msg.value > price) {
            payable(msg.sender).transfer(msg.value - price);
        }
    }

    function setBaseURI(string calldata baseURI) public onlyOwner {
        baseTokenURI = baseURI;
    }

    function setHiddenBaseURI(string calldata hiddenBaseURI) public onlyOwner {
        hiddenBaseTokenURI = hiddenBaseURI;
    }

    function setContractURI(string calldata contractURI_) public onlyOwner {
        _contractURI = contractURI_;
    }

    function setBaseExtension(string calldata extension) public onlyOwner {
        baseExtension = extension;
    }

    function changeMintPrice(uint256 newPrice) public onlyOwner {
        mintPrice = newPrice;
    }

    function changeMintStartDate(uint256 timestamp) public onlyOwner {
        mintStartAt = timestamp;
    }

    function changeMintWLStartDate(uint256 timestamp) public onlyOwner {
        mintWlStartAt = timestamp;
    }

    function changeTotalSupply(uint256 newSupply) public onlyOwner {
        maxTotalSupply = newSupply;
    }

    function getMintPrice() public view returns (uint256) {
        return mintPrice;
    }

    function numberMinted(address owner) public view returns (uint256) {
        return _numberMinted(owner);
    }

    function _baseURI() internal override view virtual returns (string memory) {
        return baseTokenURI;
    }

    function _hiddenBaseURI() internal view virtual returns (string memory) {
        return hiddenBaseTokenURI;
    }

    function _startTokenId() internal override view virtual returns (uint256) {
        return 1;
    }