// Contract: Collection
// Target function: function getETHUSDDecimals() internal view returns (uint256)
        override
        returns (address)
    {
        require(
            _exists(tokenId),
            "ERC721A: approved query for nonexistent token"
        );

        return _tokenApprovals[tokenId];
    }
    function setApprovalForAll(address operator, bool approved)
        public
        override
    {
        require(operator != _msgSender(), "ERC721A: approve to caller");

        _operatorApprovals[_msgSender()][operator] = approved;
        emit ApprovalForAll(_msgSender(), operator, approved);
    }
    function isApprovedForAll(address owner, address operator)
        public
        view
        virtual
        override
        returns (bool)
    {
        return _operatorApprovals[owner][operator];
    }
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public override {
        _transfer(from, to, tokenId);
    }
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public override {
        safeTransferFrom(from, to, tokenId, "");
    }
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public override {
        _transfer(from, to, tokenId);
        require(
            _checkOnERC721Received(from, to, tokenId, _data),
            "ERC721A: transfer to non ERC721Receiver implementer"
        );
    }
    function _exists(uint256 tokenId) internal view returns (bool) {
        return tokenId < currentIndex;
    }

    function _safeMint(address to, uint256 quantity) internal {
        _safeMint(to, quantity, "");
    }
    function _safeMint(
        address to,
        uint256 quantity,
        bytes memory _data
    ) internal {
        uint256 startTokenId = currentIndex;
        require(to != address(0), "ERC721A: mint to the zero address");
        require(!_exists(startTokenId), "ERC721A: token already minted");
        require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");

        _beforeTokenTransfers(address(0), to, startTokenId, quantity);

        AddressData memory addressData = _addressData[to];
        _addressData[to] = AddressData(
            addressData.balance + uint128(quantity),
            addressData.numberMinted + uint128(quantity)
        );
        _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));

        uint256 updatedIndex = startTokenId;

        for (uint256 i = 0; i < quantity; i++) {
            emit Transfer(address(0), to, updatedIndex);
            require(
                _checkOnERC721Received(address(0), to, updatedIndex, _data),
                "ERC721A: transfer to non ERC721Receiver implementer"
            );
            updatedIndex++;
        }

        currentIndex = updatedIndex;
        _afterTokenTransfers(address(0), to, startTokenId, quantity);
    }
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) private {
        TokenOwnership memory prevOwnership = ownershipOf(tokenId);

        bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
            getApproved(tokenId) == _msgSender() ||
            isApprovedForAll(prevOwnership.addr, _msgSender()));

        require(
            isApprovedOrOwner,
            "ERC721A: transfer caller is not owner nor approved"
        );

        require(
            prevOwnership.addr == from,
            "ERC721A: transfer from incorrect owner"
        );
        require(to != address(0), "ERC721A: transfer to the zero address");

        _beforeTokenTransfers(from, to, tokenId, 1);
        _approve(address(0), tokenId, prevOwnership.addr);

        _addressData[from].balance -= 1;
        _addressData[to].balance += 1;
        _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
        // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
        uint256 nextTokenId = tokenId + 1;
        if (_ownerships[nextTokenId].addr == address(0)) {
            if (_exists(nextTokenId)) {
                _ownerships[nextTokenId] = TokenOwnership(
                    prevOwnership.addr,
                    prevOwnership.startTimestamp
                );
            }
        }

        emit Transfer(from, to, tokenId);
        _afterTokenTransfers(from, to, tokenId, 1);
    }
    function _approve(
        address to,
        uint256 tokenId,
        address owner
    ) private {
        _tokenApprovals[tokenId] = to;
        emit Approval(owner, to, tokenId);
    }

    uint256 public nextOwnerToExplicitlySet = 0;
    function _setOwnersExplicit(uint256 quantity) internal {
        uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
        require(quantity > 0, "quantity must be nonzero");
        uint256 endIndex = oldNextOwnerToSet + quantity - 1;
        if (endIndex > collectionSize - 1) {
            endIndex = collectionSize - 1;
        }
        require(_exists(endIndex), "not enough minted yet for this cleanup");
        for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
            if (_ownerships[i].addr == address(0)) {
                TokenOwnership memory ownership = ownershipOf(i);
                _ownerships[i] = TokenOwnership(
                    ownership.addr,
                    ownership.startTimestamp
                );
            }
        }
        nextOwnerToExplicitlySet = endIndex + 1;
    }
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try
                IERC721Receiver(to).onERC721Received(
                    _msgSender(),
                    from,
                    tokenId,
                    _data
                )
            returns (bytes4 retval) {
                return retval == IERC721Receiver(to).onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert(
                        "ERC721A: transfer to non ERC721Receiver implementer"
                    );
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }
    function _beforeTokenTransfers(
        address from,
        address to,
        uint256 startTokenId,
        uint256 quantity
    ) internal virtual {}
    function _afterTokenTransfers(
        address from,
        address to,
        uint256 startTokenId,
        uint256 quantity
    ) internal virtual {}
}

library MerkleProof {
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }
    function processProof(bytes32[] memory proof, bytes32 leaf)
        internal
        pure
        returns (bytes32)
    {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            bytes32 proofElement = proof[i];
            if (computedHash <= proofElement) {
                computedHash = _efficientHash(computedHash, proofElement);
            } else {
                computedHash = _efficientHash(proofElement, computedHash);
            }
        }
        return computedHash;
    }

    function _efficientHash(bytes32 a, bytes32 b)
        private
        pure
        returns (bytes32 value)
    {
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// Collection contract is licensed under the GPLv3 license.

contract Collection is Ownable, ERC721A {

    using Strings for uint256;

    struct Tier {
        uint256 maxTokens;
        uint256 price;
    }

    uint256 constant private _weiUnit = 1000000000000000000;

    Tier[] private _tiers;

    mapping(uint256 => string) private _tokenURIs;
    bool public isPublicSaleOpen = false;

    string public baseURI = "";
    string public _extension = ".json";
    string public constant collectionName = "GreenInvest: Massms Collection";
    string public constant collectionSymbol = "GRI";
    
    uint256 internal _USDThreshold = 2;

    address public ETHUSDAddress = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // ETH/USD price feeder contract address
    
    AggregatorV3Interface internal priceFeed;

    mapping(address => bool) public preSaleList;

    constructor() ERC721A(collectionName, collectionSymbol, 1000, 10000) {
        _tiers.push(Tier(5000, 220));
        _tiers.push(Tier(8000, 440));
        _tiers.push(Tier(10000, 880));

        priceFeed = AggregatorV3Interface(ETHUSDAddress);
    }
    
    /**
     *  Mint a given number of tokens.
     */
    function mint(uint256 quantity) public payable {
        if(!isPublicSaleOpen){
            require(isWhitelisted(msg.sender), "Public sale is not open yet");
        }

        require(totalSupply() + quantity <= maxSupply(), "Reaching max supply");
        uint256 price = getPriceByQuantity(quantity);

        require(almostEqual(msg.value, price, weiThreshold() * quantity), "Invalid wei amount");

        _safeMint(msg.sender, quantity);
    }


    function weiThreshold() private view returns (uint256) {
        return _USDThreshold * 10 ** getETHUSDDecimals() * _weiUnit / getETHUSDRatio();
    }

    /**
     *  Get the maximum number of tokens that can be minted
     */
    function maxSupply() public view returns (uint256) {
        return _tiers[_tiers.length - 1].maxTokens;
    }

    /**
     *  Add wallet address to the pre-sale whitelist
     */
    function addToPreSaleList(address[] memory _wallets) public onlyOwner {
        for(uint i = 0; i < _wallets.length; i++) {
            preSaleList[_wallets[i]] = true;
        }
    }
    
    /**
     *  Check if a given address is whilelisted for pre-sale
     */
    function isWhitelisted(address _sender) public view returns(bool) {
        return preSaleList[_sender];
    }


    /**
     *  Gift tokens to multiple wallets
     *  @param quantity Quantity of tokens for each wallet
     *  @param _wallets Array of addresses to gift tokens to
     */
    function sendGifts(uint256 quantity, address[] memory _wallets) external onlyOwner {
        require(totalSupply() + _wallets.length * quantity <= maxSupply(), "Reaching max supply");
        for(uint i = 0; i < _wallets.length; i++) {
            _safeMint(_wallets[i], quantity);
        }
    }

    /**
     *  Gift tokens to a single address
     */
    function sendGiftsToWallet(address _wallet, uint256 _num) external onlyOwner {
        require(totalSupply() + _num <= maxSupply(), "Reaching max supply");
        _safeMint(_wallet, _num);
    }

    /**
     *  Get price of a given quantity of tokens
     */
    function getPriceByQuantity(uint256 _quantity) public view returns(uint256) {
        uint256 price = 0;
        uint256 totalAccumulated = 0;

        for(uint i = 0; i < _tiers.length; i++) {
            if(_tiers[i].maxTokens - totalSupply() <= 0) {
                continue;
            }
            uint256 currentTierQuantity = clamp(_quantity, 0, totalSupply() - totalAccumulated);
            totalAccumulated += currentTierQuantity;
            price += currentTierQuantity * _tiers[i].price;
            _quantity -= currentTierQuantity;
            if(_quantity == 0) {
                break;
            }
        }

        return 10 ** getETHUSDDecimals() * price * _weiUnit / getETHUSDRatio();
    }

    /**
     *  Get URI of metadata for a given token
     */
    function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
        require(
            _exists(_tokenId),
            "ERC721Metadata: URI set of nonexistent token"
        );

        return string(abi.encodePacked(baseURI, _tokenId.toString(), _extension));
    }

    /**
     *  Update token price of a tier
     */
    function updateTierPrice(uint tierNumber, uint256 price) onlyOwner public {
        require(0 < tierNumber && tierNumber <= _tiers.length, "Invalid tier number");
        _tiers[tierNumber - 1].price = price;
    }
    
    /**
     *  Update max spply of a tier
     */
    function updateTierMaxSupply(uint tierNumber, uint256 maxTokens) onlyOwner public {
        require(0 < tierNumber && tierNumber <= _tiers.length, "Invalid tier number");
        _tiers[tierNumber - 1].maxTokens = maxTokens;
    }

    /**
     *  Update metadata base URI
     */
    function updateBaseURI(string memory _newBaseURI) onlyOwner public {
        baseURI = _newBaseURI;
    }

    /**
     *  Update metadata file extension
     */
    function updateExtension(string memory _temp) onlyOwner public {
        _extension = _temp;
    }
    
    /**
     *  Update ETH/USD contract address
     */
    function updateETHUSDAddress(address _temp) onlyOwner external {
        ETHUSDAddress = _temp;
        priceFeed = AggregatorV3Interface(ETHUSDAddress);
    }

    /**
     *  Get the base URI of the collection
     */
    function getBaseURI() external view returns(string memory) {
        return baseURI;
    }

    /**
     *  Toggle public sale status
     */
    function toggleSale() public onlyOwner() {
        isPublicSaleOpen = !isPublicSaleOpen;
    }

    /**
     *  Get the amount of tokens in a given wallet
     */
    function getMintedCount(address temp) public view returns (uint256) {
    return _numberMinted(temp);
  }

    /**
     *  Withdraws the funds from the contract to the contract owner's wallet
     */
    function withdraw() external onlyOwner {
        uint _balance = address(this).balance;
        payable(owner()).transfer(_balance);
    }

    /**
     *  Get the owner of a given token
     */
    function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) {
        return ownershipOf(tokenId);
    }

    /**
     *  Get the ETH/USD ratio
     */
    function getETHUSDRatio() internal view returns (uint256) {
        (
            ,
            int256 price,
            ,
            ,
        ) = priceFeed.latestRoundData();

        return uint256(price);
    }