// Contract: grom
// Target function: function _beforeTokenTransfer(
 sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    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) {
                // Hash(current computed hash + current element of the proof)
                computedHash = _efficientHash(computedHash, proofElement);
            } else {
                // Hash(current element of the proof + current computed hash)
                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)
        }
    }
}




/** 
 *  
*/
            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}




/** 
 *  
*/
            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol)

pragma solidity ^0.8.0;

////import "../token/ERC20/utils/SafeERC20.sol";
////import "../utils/Address.sol";
////import "../utils/Context.sol";

/**
 * @title PaymentSplitter
 * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
 * that the Ether will be split in this way, since it is handled transparently by the contract.
 *
 * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
 * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
 * an amount proportional to the percentage of total shares they were assigned.
 *
 * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
 * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
 * function.
 *
 * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
 * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
 * to run tests before sending real value to this contract.
 */
contract PaymentSplitter is Context {
    event PayeeAdded(address account, uint256 shares);
    event PaymentReleased(address to, uint256 amount);
    event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
    event PaymentReceived(address from, uint256 amount);

    uint256 private _totalShares;
    uint256 private _totalReleased;

    mapping(address => uint256) private _shares;
    mapping(address => uint256) private _released;
    address[] private _payees;

    mapping(IERC20 => uint256) private _erc20TotalReleased;
    mapping(IERC20 => mapping(address => uint256)) private _erc20Released;

    /**
     * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
     * the matching position in the `shares` array.
     *
     * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
     * duplicates in `payees`.
     */
    constructor(address[] memory payees, uint256[] memory shares_) payable {
        require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
        require(payees.length > 0, "PaymentSplitter: no payees");

        for (uint256 i = 0; i < payees.length; i++) {
            _addPayee(payees[i], shares_[i]);
        }
    }

    /**
     * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
     * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
     * reliability of the events, and not the actual splitting of Ether.
     *
     * To learn more about this see the Solidity documentation for
     * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
     * functions].
     */
    receive() external payable virtual {
        emit PaymentReceived(_msgSender(), msg.value);
    }

    /**
     * @dev Getter for the total shares held by payees.
     */
    function totalShares() public view returns (uint256) {
        return _totalShares;
    }

    /**
     * @dev Getter for the total amount of Ether already released.
     */
    function totalReleased() public view returns (uint256) {
        return _totalReleased;
    }

    /**
     * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
     * contract.
     */
    function totalReleased(IERC20 token) public view returns (uint256) {
        return _erc20TotalReleased[token];
    }

    /**
     * @dev Getter for the amount of shares held by an account.
     */
    function shares(address account) public view returns (uint256) {
        return _shares[account];
    }

    /**
     * @dev Getter for the amount of Ether already released to a payee.
     */
    function released(address account) public view returns (uint256) {
        return _released[account];
    }

    /**
     * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
     * IERC20 contract.
     */
    function released(IERC20 token, address account) public view returns (uint256) {
        return _erc20Released[token][account];
    }

    /**
     * @dev Getter for the address of the payee number `index`.
     */
    function payee(uint256 index) public view returns (address) {
        return _payees[index];
    }

    /**
     * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
     * total shares and their previous withdrawals.
     */
    function release(address payable account) public virtual {
        require(_shares[account] > 0, "PaymentSplitter: account has no shares");

        uint256 totalReceived = address(this).balance + totalReleased();
        uint256 payment = _pendingPayment(account, totalReceived, released(account));

        require(payment != 0, "PaymentSplitter: account is not due payment");

        _released[account] += payment;
        _totalReleased += payment;

        Address.sendValue(account, payment);
        emit PaymentReleased(account, payment);
    }

    /**
     * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
     * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
     * contract.
     */
    function release(IERC20 token, address account) public virtual {
        require(_shares[account] > 0, "PaymentSplitter: account has no shares");

        uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
        uint256 payment = _pendingPayment(account, totalReceived, released(token, account));

        require(payment != 0, "PaymentSplitter: account is not due payment");

        _erc20Released[token][account] += payment;
        _erc20TotalReleased[token] += payment;

        SafeERC20.safeTransfer(token, account, payment);
        emit ERC20PaymentReleased(token, account, payment);
    }

    /**
     * @dev internal logic for computing the pending payment of an `account` given the token historical balances and
     * already released amounts.
     */
    function _pendingPayment(
        address account,
        uint256 totalReceived,
        uint256 alreadyReleased
    ) private view returns (uint256) {
        return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
    }

    /**
     * @dev Add a new payee to the contract.
     * @param account The address of the payee to add.
     * @param shares_ The number of shares owned by the payee.
     */
    function _addPayee(address account, uint256 shares_) private {
        require(account != address(0), "PaymentSplitter: account is the zero address");
        require(shares_ > 0, "PaymentSplitter: shares are 0");
        require(_shares[account] == 0, "PaymentSplitter: account already has shares");

        _payees.push(account);
        _shares[account] = shares_;
        _totalShares = _totalShares + shares_;
        emit PayeeAdded(account, shares_);
    }
}


/** 
 *  
*/

////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT

pragma solidity ^0.8.7;

////import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
////import "@openzeppelin/contracts/utils/Strings.sol";
////import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
////import "./Delegated.sol";
////import "./ERC721EnumerableB.sol";

/****************************************
 * @author: Squeebo                     *
 * @team:   X-11                        *
 ****************************************
 *   Blimpie-ERC721 provides low-gas    *
 *           mints + transfers          *
 ****************************************/

contract grom is Delegated, ERC721EnumerableB, PaymentSplitter {
	using Strings for uint;

	bytes32 public merkleRoot;

	uint public MAX_SUPPLY = 1000;
	uint public WL_SUPPLY  = 500;

	bool public isActive   = false;
	bool public isActiveWL = false;
	uint public maxOrder   = 5;
	uint public price	   = 0.0169 ether;

	string private _baseTokenURI = '';
	string private _tokenURISuffix = '';

	mapping(address => uint[]) private _balances;

	address[] private addressList = [
		0x7aa4720178a05654D48182aCF853b4eC1fe5f7E5,
		0xD932B57C2A2A019C5b5924b86134FaF51280F956
	];
	uint[] private shareList = [
		50,
		50
	];

	constructor()
		Delegated()
		ERC721B("grom", "GROM")
		PaymentSplitter(addressList, shareList)  {
	}

	//external
	fallback() external payable {}

	function mint( uint quantity ) external payable {
		require( isActive,        				"Sale is not active"		);
		require( quantity <= maxOrder,          "Order too big"             );
		require( msg.value >= price * quantity, "Ether sent is not correct" );

		uint256 supply = totalSupply();
		require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" );
		for(uint i = 0; i < quantity; ++i){
			_safeMint( msg.sender, supply++, "" );
		}
	}

	function whitelistMint( bytes32[] calldata proof, uint quantity ) external payable {
		require( isActiveWL,        			   "Whitelist sale is not active");
		require( quantity <= maxOrder,            "Order too big"               );

		bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
		require( MerkleProof.verify(proof, merkleRoot, leaf), "Not whitelisted");

		uint256 supply = totalSupply();
		require( supply + quantity <= WL_SUPPLY,  "Mint/order exceeds whitelist supply" );
		require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" );
		
		for(uint i = 0; i < quantity; ++i){
			_safeMint( msg.sender, supply++, "" );
		}  
	}

	//external delegated
	function gift(uint[] calldata quantity, address[] calldata recipient) external onlyDelegates{
		require(quantity.length == recipient.length, "Must provide equal quantities and recipients" );

		uint totalQuantity = 0;
		uint256 supply = totalSupply();
		for(uint i = 0; i < quantity.length; ++i){
			totalQuantity += quantity[i];
		}
		require( supply + totalQuantity <= MAX_SUPPLY, "Mint/order exceeds supply" );
		delete totalQuantity;

		for(uint i = 0; i < recipient.length; ++i){
			for(uint j = 0; j < quantity[i]; ++j){
				_safeMint( recipient[i], supply++, "Sent with love" );
			}
		}
	}

	function setWhitelistActive(bool isActiveWL_) external onlyDelegates {
		if( isActiveWL != isActiveWL_ ) 
			isActiveWL = isActiveWL_;
	}

	function setActive(bool isActive_) external onlyDelegates{
		if( isActive != isActive_ )
			isActive = isActive_;
	}

	function setMaxOrder(uint maxOrder_) external onlyDelegates{
		if( maxOrder != maxOrder_ )
			maxOrder = maxOrder_;
	}

	function setPrice(uint price_) external onlyDelegates{
		if( price != price_ )
			price = price_;
	}

	function setMerkleRoot(bytes32 root) external onlyDelegates {
		merkleRoot = root;
	}

	function setBaseURI(string calldata _newBaseURI, string calldata _newSuffix) external onlyDelegates{
		_baseTokenURI = _newBaseURI;
		_tokenURISuffix = _newSuffix;
	}

	//external owner
	function setMaxSupply(uint maxSupply) external onlyOwner{
		if( MAX_SUPPLY != maxSupply ){
			require(maxSupply >= totalSupply(), "Specified supply is lower than current balance" );
			MAX_SUPPLY = maxSupply;
		}
	}

	//public
	function balanceOf(address owner) public view virtual override(ERC721B) returns (uint256) {
		require(owner != address(0), "ERC721: balance query for the zero address");
		return _balances[owner].length;
	}

	function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
		require(index < ERC721B.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
		return _balances[owner][index];
	}

	function tokenURI(uint tokenId) external view virtual override returns (string memory) {
		require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
		return string(abi.encodePacked(_baseTokenURI, tokenId.toString(), _tokenURISuffix));
	}