// Contract: SocietyOfTheHourglass
// Target function: function isApprovedForAll(address _owner, address _operator) public view virtual override returns (bool)
    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}


// Dependency file: @openzeppelin/contracts/utils/math/SafeMath.sol


// pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}


// Dependency file: contracts/Hashku.sol

// pragma solidity 0.8.9;

/*
*
* Hashku Contract
* 
* Contract by Matt Casanova [Twitter: @DevGuyThings]
* 
* To be used as base contract for ERC721 when minting on Hashku
*
*/

// import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// import "@openzeppelin/contracts/interfaces/IERC2981.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
// import "@openzeppelin/contracts/utils/Strings.sol";
// import "@openzeppelin/contracts/utils/Context.sol";
// import "@openzeppelin/contracts/utils/Counters.sol";
// import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";

contract Hashku is Context, Ownable, ERC721, IERC2981 {
    using Address for address;
    using Strings for uint256;
    using Counters for Counters.Counter;
    using ECDSA for bytes32;

    Counters.Counter private tokenIdTracker;

    string public baseTokenURI;
    string public key = "SHOP";
    string public group = "init";
    uint256 public maxMintPerAddress;
    uint256 public maxMintPerTransaction;
    uint256 public maxTokens;
    uint256 public price;
    bool public isPublic;
    bool public isClosed;
    mapping(address => uint256) public tokensMinted;
    address public withdrawalAddress;
    address public verifySigner;
    uint256 public royaltyPercent;
    address public proxyRegistryAddress;

    event ContractUpdated(string _type);

    modifier onlyWithdrawer() {
        require(withdrawalAddress != address(0), "no_withdrawals");
        require(withdrawalAddress == _msgSender(), "not_allowed");
        _;
    }

    constructor(
        string memory _name, 
        string memory _symbol, 
        string memory _baseTokenURI,
        string memory _key,
        uint256 _maxTokens, 
        uint256 _maxMintPerAddress,
        uint256 _maxMintPerTransaction,
        uint256 _price,
        uint256 _royaltyPercent,
        address _withdrawalAddress
    ) ERC721(_name, _symbol) {
        baseTokenURI = _baseTokenURI;
        key = _key;
        maxTokens = _maxTokens;
        maxMintPerAddress = _maxMintPerAddress;
        maxMintPerTransaction = _maxMintPerTransaction;
        price = _price;
        royaltyPercent = _royaltyPercent;
        withdrawalAddress = _withdrawalAddress;
        verifySigner = _msgSender();
    }

    // support IERC2981
    function supportsInterface(bytes4 _interfaceId) public view virtual override (ERC721, IERC165) returns (bool) {
        return _interfaceId == type(IERC2981).interfaceId || super.supportsInterface(_interfaceId);
    }

    // return the token URI for a specific token
    function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
        require(_exists(_tokenId), "no_token");

        return bytes(baseTokenURI).length > 0 ? string(abi.encodePacked(baseTokenURI, _tokenId.toString())) : "";
    }

    // internal mint function, incrementing token
    function mint(address _to) internal {
        _safeMint(_to, tokenIdTracker.current());
        tokenIdTracker.increment();
    }

    // owner sends NFTs to addresses
    function send(address[] calldata _addresses, uint256[] calldata _amounts) external virtual onlyOwner {
        require(_addresses.length == _amounts.length, "amount_mismatch");

        uint256 total;
        for (uint256 t = 0; t < _amounts.length; t++) {
            total += _amounts[t];
        }

        require(nextToken() + total <= maxTokens, "not_enough_tokens");

        delete total;

        for (uint256 i = 0; i < _addresses.length; i++) {
            for (uint256 a = 0; a < _amounts[i]; a++) {
                mint(_addresses[i]);
            }
        }
    }

    // buy NFTs - version without signature required for public mint
    function shop(uint256 _amount) external virtual payable {}

    // buy NFTs
    function shop(uint256 _amount, bytes memory _signature) external virtual payable {}

    // return the id for the next token that will be minted
    function nextToken() public view returns (uint256) {
        return tokenIdTracker.current();
    }

    // check if a msg sender is eligible to shop
    function eligible() public view virtual returns (bool) {
        if (isClosed) {
            return false;
        }

        return isPublic;
    }

    // owner can ONLY decrease the total number of available tokens
    function decreaseMaxTokens(uint256 _amount) external virtual onlyOwner {
        require(_amount < maxTokens, "only_decrease");
        maxTokens = _amount;
    }

    // owner set the contract to public mode
    function setIsPublic(bool _public) external virtual onlyOwner {
        isPublic = _public;
        emit ContractUpdated("isPublic");
    }

    // owner set the contract to closed
    function setIsClosed(bool _closed) external virtual onlyOwner {
        isClosed = _closed;
        emit ContractUpdated("isClosed");
    }

    // owner set the price of minting
    function setPrice(uint256 _price) external virtual onlyOwner {
        price = _price;
    }

    // set the maximum amount an address may mint
    function setMaxMintPerAddress(uint256 _amount) external virtual onlyOwner {
        maxMintPerAddress = _amount;
    }

    // set the maximum amount an address may mint
    function setMaxMintPerTransaction(uint256 _amount) external virtual onlyOwner {
        maxMintPerTransaction = _amount;
    }

    // owner set the contract key for signature verification
    function setKey(string calldata _key) external virtual onlyOwner {
        key = _key;
    }

    // set the current contract group for signature verification
    function setGroup(string memory _group) external virtual onlyOwner {
        group = _group;
        emit ContractUpdated("group");
    }

    // owner set a new base token URI
    function setBaseUri(string calldata _baseTokenURI) external virtual onlyOwner {
        baseTokenURI = _baseTokenURI;
    }

    // owner set a new address for signature verification
    function setVerifySigner(address _verifySigner) external virtual onlyOwner {
        verifySigner = _verifySigner;
    }

    // verify signature based on contract key, contract group, token amount, and the msg sender
    function verifySignature(
        bytes memory _signature
    ) internal view virtual returns (bool) {
        bytes32 _messageHash = keccak256(abi.encodePacked(key, group, _msgSender()));

        return _messageHash.toEthSignedMessageHash().recover(_signature) == verifySigner;
    }

    // set the royalty percent
    function setRoyaltyPercent(uint256 _amount) external virtual onlyOwner {
        royaltyPercent = _amount;
    }

    // EIP-2981 royaltyInfo
    function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address receiver, uint256 royaltyAmount) {
        require(_exists(_tokenId), "no_token");

        return (address(this), SafeMath.div(SafeMath.mul(_salePrice, royaltyPercent), 100));
    }

    // withdrawal address convenience method for pulling balance of contract
    function seeBalance() external view virtual onlyWithdrawer returns (uint256) {
        return address(this).balance;
    }

    // withdrawal address send an amount to an address
    function withdraw(address payable _to, uint256 _amount) external virtual onlyWithdrawer returns (bool) {
        require(_amount <= address(this).balance, "insufficient_funds");
        _to.transfer(_amount);
        return true;
    }

    // withdrawal address set a new withdrawal address
    function setWithdrawalAddress(address _address) external virtual onlyWithdrawer {
        withdrawalAddress = _address;
        // emit ContractUpdated("withdrawalAddress");
    }

    // owner can set the proxy registry access after deploy
    function setProxyRegistryAddress(address _proxy) external virtual onlyOwner {
        // OpenSea Rinkeby Address = "0xf57b2c51ded3a29e6891aba85459d600256cf317";
        // OpenSea Mainnet Address = "0xa5409ec958c83c3f309868babaca7c86dcb077c1";
        proxyRegistryAddress = _proxy;
    }