// File: @helix-foundation/eco-id/contracts/Base64.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

/// @title Base64
/// @author Brecht Devos - <brecht@loopring.org>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
    string internal constant TABLE =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    function encode(bytes memory data) internal pure returns (string memory) {
        if (data.length == 0) return "";

        // load the table into memory
        string memory table = TABLE;

        // multiply by 4/3 rounded up
        uint256 encodedLen = 4 * ((data.length + 2) / 3);

        // add some extra buffer at the end required for the writing
        string memory result = new string(encodedLen + 32);

        assembly {
            // set the actual output length
            mstore(result, encodedLen)

            // prepare the lookup table
            let tablePtr := add(table, 1)

            // input ptr
            let dataPtr := data
            let endPtr := add(dataPtr, mload(data))

            // result ptr, jump over length
            let resultPtr := add(result, 32)

            // run over the input, 3 bytes at a time
            for {

            } lt(dataPtr, endPtr) {

            } {
                dataPtr := add(dataPtr, 3)

                // read 3 bytes
                let input := mload(dataPtr)

                // write 4 characters
                mstore(
                    resultPtr,
                    shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                )
                resultPtr := add(resultPtr, 1)
                mstore(
                    resultPtr,
                    shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                )
                resultPtr := add(resultPtr, 1)
                mstore(
                    resultPtr,
                    shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                )
                resultPtr := add(resultPtr, 1)
                mstore(
                    resultPtr,
                    shl(248, mload(add(tablePtr, and(input, 0x3F))))
                )
                resultPtr := add(resultPtr, 1)
            }

            // padding with '='
            switch mod(mload(data), 3)
            case 1 {
                mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
            }
            case 2 {
                mstore(sub(resultPtr, 1), shl(248, 0x3d))
            }
        }

        return result;
    }
}

// File: @helix-foundation/eco-id/contracts/EcoID.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./Base64.sol";

/**
 * This is the EcoNFT for verifying an arbitraty claim.
 */
contract EcoID is ERC721("EcoID", "EcoID"), EIP712("EcoID", "1") {
    /**
     * Use for signarture recovery and verification on minting of EcoID
     */
    using ECDSA for bytes32;

    /**
     * Use for tracking the nonces on signatures
     */
    using Counters for Counters.Counter;

    /**
     * The static web url for the nft
     */
    string public constant NFT_EXTERNAL_URL = "https://eco.org/eco-id";

    /**
     * The static description for the nft
     */
    string public constant NFT_DESCRIPTION =
        "Eco IDs are fully decentralized and permissionless identity primitives designed to be simple, versatile and immutable. They are intended to serve as a basic foundation to bootstrap increasingly-complex and custom reputation and governance systems.";

    /**
     * The static image url for all the nft's
     */
    string public constant NFT_IMAGE_URL =
        "https://ipfs.io/ipfs/QmWZFvb88KDos7BYyf52btxPuEEifZN7i5CA2YfC3azS8J";

    /**
     * The static url for contract-level metadata
     */
    string public constant CONTRACT_LEVEL_METADATA_URL =
        "https://ipfs.io/ipfs/QmZ7vpY34jdmDyn8otBMzvX7omn6NWTfdxVFr8RMuAAVPZ";

    /**
     * The default pagination limit for the tokenURI meta that reads from the claim verifiers array
     */
    uint256 public constant META_LIMIT = 50;

    /**
     * The length of a substring for the name field of an nft
     */
    uint256 public constant SUB_NAME_LENGTH = 10;

    /**
     * The hash of the register function signature for the recipient
     */
    bytes32 private constant REGISTER_APPROVE_TYPEHASH =
        keccak256(
            "Register(string claim,uint256 feeAmount,bool revocable,address recipient,address verifier,uint256 deadline,uint256 nonce)"
        );

    /**
     * The hash of the register function signature for the verifier
     */
    bytes32 private constant REGISTER_VERIFIER_TYPEHASH =
        keccak256(
            "Register(string claim,uint256 feeAmount,bool revocable,address recipient,uint256 deadline,uint256 nonce)"
        );

    /**
     * The hash of the register function signature
     */
    bytes32 private constant UNREGISTER_TYPEHASH =
        keccak256(
            "Unregister(string claim,address recipient,address verifier,uint256 deadline,uint256 nonce)"
        );

    /**
     * Event for when the constructor has finished
     */
    event InitializeEcoID();

    /**
     * Event for when a claim is verified for a recipient
     */
    event RegisterClaim(
        string claim,
        uint256 feeAmount,
        bool revocable,
        address indexed recipient,
        address indexed verifier
    );

    /**
     * Event for when a claim is unregistered by the verifier
     */
    event UnregisterClaim(
        string claim,
        address indexed recipient,
        address indexed verifier
    );

    /**
     * Event for when an EcoNFT is minted
     */
    event Mint(address indexed recipient, string claim, uint256 tokenID);

    /**
     * Error for when the deadline for a signature has passed
     */
    error DeadlineExpired();

    /**
     * Error for when the approval signature during registration is invalid
     */
    error InvalidRegistrationApproveSignature();

    /**
     * Error for when the verifier signature during registration is invalid
     */
    error InvalidRegistrationVerifierSignature();

    /**
     * Error for when a registration with the same verifier is attempted on a claim a second time
     */
    error DuplicateVerifier(address verifier);

    /**
     * Error for when a claim has not been verified or doesn't exist for a user
     */
    error UnverifiedClaim();

    /**
     * Error for when trying to deregister a claim that is not revocable
     */
    error UnrevocableClaim();

    /**
     * Error for when trying to deregister and the verifier signature is invalid
     */
    error InvalidVerifierSignature();

    /**
     * Error for when a user trys to mint an NFT for a claim that already has a minted NFT
     */
    error NftAlreadyMinted(uint256 tokenID);

    /**
     * Error for when trying to reference an NFT token that doesn't exist
     */
    error NonExistantToken();

    /**
     * Error for when the fee payment for registration fails
     */
    error FeePaymentFailed();

    /**
     * Error for when trying to register an empty claim
     */
    error EmptyClaim();

    /**
     * Structure for storing a verified claim
     */
    struct VerifiedClaim {
        string claim;
        uint256 tokenID;
        VerifierRecord[] verifiers;
        mapping(address => bool) verifierMap;
    }

    /**
     * Structure for the verifier record
     */
    struct VerifierRecord {
        address verifier;
        bool revocable;
    }

    /**
     * Structure for storing the relation between a tokenID and the address and claim
     * that they are linked to
     */
    struct TokenClaim {
        address recipient;
        string claim;
    }

    /**
     * Stores the last token index minted
     */
    uint256 public _tokenIDIndex = 1;

    /**
     * Mapping the user address with all claims they have
     */
    mapping(address => mapping(string => VerifiedClaim)) public _verifiedClaims;

    /**
     * Mapping the tokenID of minted tokens with the claim they represent. Necessary as we can't fetch the claim
     * directly from the _verifiedClaims for a given tokenID
     */
    mapping(uint256 => TokenClaim) public _tokenClaimIDs;

    /**
     * The mapping that store the current nonce for claim
     */
    mapping(string => Counters.Counter) private _nonces;

    /**
     * The token contract that is used for fee payments to the minter address
     */
    ERC20 public immutable _token;

    /**
     * Constructor that sets the ERC20 and emits an initialization event
     *
     * @param token the erc20 that is used to pay for registrations
     */
    constructor(ERC20 token) {
        _token = token;

        emit InitializeEcoID();
    }

    /**
     * Check if the claim has been verified by the given verifier for the given address
     *
     * @param recipient the address of the associated claim
     * @param claim the claim that should be verified
     * @param verifier the address of the verifier for the claim on the recipient address
     *
     * @return true if the claim is verified, false otherwise
     */
    function isClaimVerified(
        address recipient,
        string calldata claim,
        address verifier
    ) external view returns (bool) {
        return _verifiedClaims[recipient][claim].verifierMap[verifier];
    }

    /**
     * Registers a claim by an approved verifier to the recipient of that claim.
     *
     * @param claim the claim that is beign verified
     * @param feeAmount the fee the recipient is paying the verifier for the verification
     * @param revocable true if the verifier can revoke their verification of the claim in the future
     * @param recipient the address of the recipient of the registered claim
     * @param verifier the address that is verifying the claim
     * @param approveSig signature that proves that the recipient has approved the verifier to register a claim
     * @param verifySig signature that we are validating comes from the verifier address
     */
    function register(
        string calldata claim,
        uint256 feeAmount,
        bool revocable,
        address recipient,
        address verifier,
        uint256 deadline,
        bytes calldata approveSig,
        bytes calldata verifySig
    ) external _validClaim(claim) {
        if (deadline < block.timestamp) {
            revert DeadlineExpired();
        }
        uint256 nonce = _useNonce(claim);
        if (
            !_verifyRegistrationApprove(
                claim,
                feeAmount,
                revocable,
                recipient,
                verifier,
                deadline,
                nonce,
                approveSig
            )
        ) {
            revert InvalidRegistrationApproveSignature();
        }

        if (
            !_verifyRegistrationVerify(
                claim,
                feeAmount,
                revocable,
                recipient,
                verifier,
                deadline,
                nonce,
                verifySig
            )
        ) {
            revert InvalidRegistrationVerifierSignature();
        }

        VerifiedClaim storage vclaim = _verifiedClaims[recipient][claim];
        if (vclaim.verifierMap[verifier]) {
            revert DuplicateVerifier({verifier: verifier});
        }
        vclaim.claim = claim;
        vclaim.verifiers.push(VerifierRecord(verifier, revocable));
        vclaim.verifierMap[verifier] = true;

        if (feeAmount > 0) {
            if (!_token.transferFrom(recipient, verifier, feeAmount)) {
                revert FeePaymentFailed();
            }
        }

        emit RegisterClaim(claim, feeAmount, revocable, recipient, verifier);
    }

    /**
     * Revokes a claim that has been made by the verifier if it was revocable
     *
     * @param claim the claim that was verified
     * @param recipient the address of the recipient of the registered claim
     * @param verifier the address that had verified the claim
     * @param deadline the deadline in milliseconds from epoch that the signature expires
     * @param verifySig signature that we are validating comes from the verifier address
     */
    function unregister(
        string calldata claim,
        address recipient,
        address verifier,
        uint256 deadline,
        bytes calldata verifySig
    ) external _validClaim(claim) {
        if (deadline < block.timestamp) {
            revert DeadlineExpired();
        }
        VerifiedClaim storage vclaim = _verifiedClaims[recipient][claim];
        if (!vclaim.verifierMap[verifier]) {
            revert UnverifiedClaim();
        }

        VerifierRecord storage record = _getVerifierRecord(
            verifier,
            vclaim.verifiers
        );

        if (!record.revocable) {
            revert UnrevocableClaim();
        }

        if (
            !_verifyUnregistration(
                claim,
                recipient,
                verifier,
                deadline,
                _useNonce(claim),
                verifySig
            )
        ) {
            revert InvalidVerifierSignature();
        }

        vclaim.verifierMap[verifier] = false;
        _removeVerifierRecord(verifier, vclaim.verifiers);

        emit UnregisterClaim(claim, recipient, verifier);
    }

    /**
     * Mints the nft token for the claim
     *
     * @param recipient the address of the recipient for the nft
     * @param claim the claim that is being associated to the nft
     *
     * @return tokenID the ID of the nft
     */
    function mintNFT(address recipient, string memory claim)
        external
        returns (uint256 tokenID)
    {
        VerifiedClaim storage vclaim = _verifiedClaims[recipient][claim];
        if (vclaim.verifiers.length == 0) {
            revert UnverifiedClaim();
        }

        if (vclaim.tokenID != 0) {
            revert NftAlreadyMinted({tokenID: vclaim.tokenID});
        }

        tokenID = _tokenIDIndex++;

        vclaim.tokenID = tokenID;
        _tokenClaimIDs[tokenID] = TokenClaim(recipient, claim);
        _safeMint(recipient, tokenID);

        emit Mint(recipient, claim, tokenID);
    }

    /**
     * Constructs and returns the ERC-721 schema metadata as a json object.
     * Calls a pagination for the verifier array that limits to 50.
     * See tokenURICursor if you need to paginate the metadata past that number
     *
     * @param tokenID the id of the nft
     *
     * @return the metadata as a json object
     */
    function tokenURI(uint256 tokenID)
        public
        view
        override
        returns (string memory)
    {
        return tokenURICursor(tokenID, 0, META_LIMIT);
    }

    /**
     * Returns the current nonce for a given claim
     *
     * @param claim the claim to fetch the nonce for
     *
     * @return the nonce
     */
    function nonces(string memory claim) public view returns (uint256) {
        return _nonces[claim].current();
    }

    /**
     * Makes the _domainSeparatorV4() function externally callable for signature generation
     */
    function DOMAIN_SEPARATOR() external view returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * Constructs and returns the metadata ERC-721 schema json for the NFT.
     * Uses regular cursor pagination in case the verifiers array for the claim is large.
     *
     * @param tokenID the id of the nft
     * @param cursor the pagination cursor for the verifiers array
     * @param limit  the pagination limit for the verifiers array
     *
     * @return meta the metadata as a json array
     */
    function tokenURICursor(
        uint256 tokenID,
        uint256 cursor,
        uint256 limit
    ) public view virtual returns (string memory meta) {
        if (!_exists(tokenID)) {
            revert NonExistantToken();
        }

        TokenClaim storage tokenClaim = _tokenClaimIDs[tokenID];
        VerifiedClaim storage vclaim = _verifiedClaims[tokenClaim.recipient][
            tokenClaim.claim
        ];

        string memory claim = vclaim.claim;
        string memory nameFrag = _getStringSize(claim) > SUB_NAME_LENGTH
            ? string.concat(_substring(claim, 0, SUB_NAME_LENGTH), "...")
            : claim;
        bool hasVerifiers = vclaim.verifiers.length > 0;
        string memory metadataName = string.concat("Eco ID - ", nameFrag);

        meta = _metaPrefix(vclaim.claim, metadataName, hasVerifiers);
        string memory closing = hasVerifiers ? '"}]}' : "]}";
        meta = string.concat(
            meta,
            _metaVerifierArray(vclaim.verifiers, cursor, limit),
            closing
        );

        string memory base = "data:application/json;base64,";
        string memory base64EncodedMeta = Base64.encode(
            bytes(string(abi.encodePacked(meta)))
        );

        meta = string(abi.encodePacked(base, base64EncodedMeta));
    }

    /**
     * Constructs the first portion of the nft metadata
     *
     * @param claim the claim
     * @param name the name of the nft
     * @param hasVerifiers whether the nft has any verifiers
     * @return meta the partially constructed json
     */
    function _metaPrefix(
        string storage claim,
        string memory name,
        bool hasVerifiers
    ) internal pure returns (string memory meta) {
        meta = "{";
        meta = string.concat(
            meta,
            '"description":',
            '"',
            NFT_DESCRIPTION,
            '",'
        );
        meta = string.concat(
            meta,
            '"external_url":',
            '"',
            NFT_EXTERNAL_URL,
            '",'
        );
        meta = string.concat(meta, '"image":', '"', NFT_IMAGE_URL, '",');
        meta = string.concat(meta, '"name":"', name, '",');
        string memory closing = hasVerifiers ? '"},' : '"}';
        meta = string.concat(
            meta,
            '"attributes":[{"trait_type":"Data","value":"',
            claim,
            closing
        );
    }

    /**
     * Constructs the verifier address array portion of the nft metadata
     *
     * @param verifiers the claim being verified
     * @param cursor the pagination cursor for the verifiers array
     * @param limit  the pagination limit for the verifiers array
     *
     * @return meta the partially constructed json
     */
    function _metaVerifierArray(
        VerifierRecord[] storage verifiers,
        uint256 cursor,
        uint256 limit
    ) internal view returns (string memory meta) {
        if (verifiers.length == 0) {
            return meta;
        }
        //get the ending position
        uint256 readEnd = cursor + limit;
        uint256 vl = verifiers.length;
        uint256 end = vl <= readEnd ? vl : readEnd;

        uint256 lastPoint = end - 1;
        for (uint256 i = cursor; i < end; i++) {
            string memory addr = Strings.toHexString(
                uint256(uint160(verifiers[i].verifier)),
                20
            );
            string memory revocable = verifiers[i].revocable ? "true" : "false";

            if (i < lastPoint) {
                meta = string.concat(
                    meta,
                    '{"trait_type":"Verifier","value":"',
                    addr,
                    '","revocable":"',
                    revocable,
                    '"},'
                );
            } else {
                meta = string.concat(
                    meta,
                    '{"trait_type":"Verifier","value": "',
                    addr,
                    '","revocable":"',
                    revocable
                );
            }
        }
    }

    /**
     * Verifies the signature supplied grants the verifier approval by the recipient to modify their claim
     *
     * @param claim the claim being verified
     * @param feeAmount the cost paid to the verifier by the recipient
     * @param revocable true if the verifier can revoke their verification of the claim in the future
     * @param recipient the address of the recipient of a registration
     * @param verifier  the address of the verifying agent
     * @param deadline the deadline in milliseconds from epoch that the signature expires
     * @param approveSig signature that we are validating grants the verifier permission to register the claim to the recipient
     *
     * @return true if the signature is valid, false otherwise
     */
    function _verifyRegistrationApprove(
        string calldata claim,
        uint256 feeAmount,
        bool revocable,
        address recipient,
        address verifier,
        uint256 deadline,
        uint256 nonce,
        bytes calldata approveSig
    ) internal view returns (bool) {
        bytes32 hash = _getApproveHash(
            claim,
            feeAmount,
            revocable,
            recipient,
            verifier,
            deadline,
            nonce
        );
        return hash.recover(approveSig) == recipient;
    }

    /**
     * Verifies the signature supplied belongs to the verifier for a certain claim.
     *
     * @param claim the claim being verified
     * @param feeAmount the cost paid to the verifier by the recipient
     * @param revocable true if the verifier can revoke their verification of the claim in the future
     * @param recipient the address of the recipient of a registration
     * @param verifier  the address of the verifying agent
     * @param deadline the deadline in milliseconds from epoch that the signature expires
     * @param verifierSig signature that we are validating comes from the verifier
     *
     * @return true if the signature is valid, false otherwise
     */
    function _verifyRegistrationVerify(
        string calldata claim,
        uint256 feeAmount,
        bool revocable,
        address recipient,
        address verifier,
        uint256 deadline,
        uint256 nonce,
        bytes calldata verifierSig
    ) internal view returns (bool) {
        bytes32 hash = _getVerificationHash(
            claim,
            feeAmount,
            revocable,
            recipient,
            deadline,
            nonce
        );
        return hash.recover(verifierSig) == verifier;
    }

    /**
     * Verifies the signature supplied belongs to the verifier for the claim.
     *
     * @param claim the claim that was verified
     * @param recipient  the address of the recipient
     * @param verifier  the address of the verifying agent
     * @param deadline the deadline in milliseconds from epoch that the signature expires
     * @param nonce the nonce for the signatures for this claim registration
     * @param signature signature that we are validating comes from the verifier
     * @return true if the signature is valid, false otherwise
     */
    function _verifyUnregistration(
        string calldata claim,
        address recipient,
        address verifier,
        uint256 deadline,
        uint256 nonce,
        bytes calldata signature
    ) internal view returns (bool) {
        bytes32 hash = _getUnregistrationHash(
            claim,
            recipient,
            verifier,
            deadline,
            nonce
        );
        return hash.recover(signature) == verifier;
    }

    /**
     * @dev Disables the transferFrom and safeTransferFrom calls in the parent contract bounding this token to
     * the original address that it was minted for
     */
    function _isApprovedOrOwner(address, uint256)
        internal
        pure
        override
        returns (bool)
    {
        return false;
    }

    /**
     * Hashes the input parameters for the approval signature verification
     *
     * @param claim the claim being attested to
     * @param feeAmount the cost paid to the verifier by the recipient
     * @param revocable true if the verifier can revoke their verification of the claim in the future
     * @param recipient the address of the user that is having a claim registered
     * @param verifier the address of the verifier of the claim
     * @param deadline the deadline in milliseconds from epoch that the signature expires
     * @param nonce the nonce for the signatures for this claim registration
     */
    function _getApproveHash(
        string calldata claim,
        uint256 feeAmount,
        bool revocable,
        address recipient,
        address verifier,
        uint256 deadline,
        uint256 nonce
    ) private view returns (bytes32) {
        return
            _hashTypedDataV4(
                keccak256(
                    abi.encode(
                        REGISTER_APPROVE_TYPEHASH,
                        keccak256(bytes(claim)),
                        feeAmount,
                        revocable,
                        recipient,
                        verifier,
                        deadline,
                        nonce
                    )
                )
            );
    }

    /**
     * Hashes the input parameters for the registration signature verification
     *
     * @param claim the claim being attested to
     * @param feeAmount the cost to register the claim the recipient is willing to pay
     * @param revocable true if the verifier can revoke their verification of the claim in the future
     * @param recipient the address of the user that is having a claim registered
     * @param deadline the deadline in milliseconds from epoch that the signature expires
     * @param nonce the nonce for the signatures for this claim registration
     */
    function _getVerificationHash(
        string calldata claim,
        uint256 feeAmount,
        bool revocable,
        address recipient,
        uint256 deadline,
        uint256 nonce
    ) private view returns (bytes32) {
        return
            _hashTypedDataV4(
                keccak256(
                    abi.encode(
                        REGISTER_VERIFIER_TYPEHASH,
                        keccak256(bytes(claim)),
                        feeAmount,
                        revocable,
                        recipient,
                        deadline,
                        nonce
                    )
                )
            );
    }

    /**
     * Hashes the input parameters for the unregistration signature verification
     *
     * @param claim the claim that was verified
     * @param recipient the address of the user that owns that claim
     * @param verifier  the address of the verifying agent
     * @param deadline the deadline in milliseconds from epoch that the signature expires
     * @param nonce the nonce for the signatures for this claim registration
     */
    function _getUnregistrationHash(
        string calldata claim,
        address recipient,
        address verifier,
        uint256 deadline,
        uint256 nonce
    ) private view returns (bytes32) {
        return
            _hashTypedDataV4(
                keccak256(
                    abi.encode(
                        UNREGISTER_TYPEHASH,
                        keccak256(bytes(claim)),
                        recipient,
                        verifier,
                        deadline,
                        nonce
                    )
                )
            );
    }

    /**
     * Checks that the claim is not empty
     *
     * @param claim the claim to check
     */
    modifier _validClaim(string memory claim) {
        if (bytes(claim).length == 0) {
            revert EmptyClaim();
        }
        _;
    }

    /**
     * Finds the verifier record in the array and returns it, or reverts
     *
     * @param verifier the verified address to search for
     * @param verifierRecords the verifier records array
     */
    function _getVerifierRecord(
        address verifier,
        VerifierRecord[] storage verifierRecords
    ) internal view returns (VerifierRecord storage) {
        for (uint256 i = 0; i < verifierRecords.length; i++) {
            if (verifierRecords[i].verifier == verifier) {
                return verifierRecords[i];
            }
        }
        //should never get here
        revert("invalid verifier");
    }

    /**
     * Removes a verifier from the verifiers array, does not preserve order
     *
     * @param verifier the verifier to remove from the array
     * @param verifierRecords the verifier records array
     */
    function _removeVerifierRecord(
        address verifier,
        VerifierRecord[] storage verifierRecords
    ) internal {
        for (uint256 i = 0; i < verifierRecords.length; i++) {
            if (verifierRecords[i].verifier == verifier) {
                verifierRecords[i] = verifierRecords[
                    verifierRecords.length - 1
                ];
                verifierRecords.pop();
                return;
            }
        }
    }

    /**
     * Returns a substring of the input argument
     */
    function _substring(
        string memory str,
        uint256 startIndex,
        uint256 endIndex
    ) private pure returns (string memory) {
        bytes memory strBytes = bytes(str);
        bytes memory result = new bytes(endIndex - startIndex);
        for (uint256 i = startIndex; i < endIndex; i++) {
            result[i - startIndex] = strBytes[i];
        }
        return string(result);
    }

    /**
     * Returns the size of a string in bytes
     *
     * @param str string to check
     */
    function _getStringSize(string memory str) internal pure returns (uint256) {
        return bytes(str).length;
    }

    /**
     * Returns the current nonce for a claim and automatically increament it
     *
     * @param claim the claim to get and increment the nonce for
     *
     * @return current current nonce before incrementing
     */
    function _useNonce(string memory claim) internal returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[claim];
        current = nonce.current();
        nonce.increment();
    }

    /**
     * Function for reading NFT-level metadata
     *
     * Designed to match the OpenSea specification
     */
    function contractURI() public pure returns (string memory) {
        return CONTRACT_LEVEL_METADATA_URL;
    }
}

// File: @helix-foundation/eco-id/contracts/interfaces/IECO.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * Helper interface for the eco currency
 */
interface IECO is IERC20 {
    function getPastLinearInflation(uint256 blockNumber)
        external
        view
        returns (uint256);
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @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 Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        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);
    }
}

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @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 `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, 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 `from` to `to` 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 from,
        address to,
        uint256 amount
    ) external returns (bool);
}

// File: @openzeppelin/contracts/token/ERC721/ERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @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.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits a {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    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.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}
}

// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @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);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @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`.
     *
     * 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 approved 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 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
    ) external;

    /**
     * @dev Transfers `tokenId` token 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);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: @openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @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;
    }
}

// File: @openzeppelin/contracts/utils/Counters.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

// File: @openzeppelin/contracts/utils/cryptography/draft-EIP712.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    address private immutable _CACHED_THIS;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _CACHED_THIS = address(this);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @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 Message, created from `s`. 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(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @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));
    }
}

// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Trees proofs.
 *
 * The proofs can be generated using the JavaScript library
 * https://github.com/miguelmota/merkletreejs[merkletreejs].
 * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
 *
 * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * 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)
        }
    }
}

// File: @openzeppelin/contracts/utils/introspection/ERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: @openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: 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);
    }
}

// File: contracts/EcoClaim.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@helix-foundation/eco-id/contracts/EcoID.sol";
import "@helix-foundation/eco-id/contracts/interfaces/IECO.sol";

contract EcoClaim is Ownable, EIP712("EcoClaim", "1") {
    /**
     * Use for validating merkel proof of claims for tokens
     */
    using MerkleProof for bytes32[];

    /**
     * Use for signarture recovery and verification on token claiming
     */
    using ECDSA for bytes32;

    /**
     * Use for tracking the nonces on signatures
     */
    using Counters for Counters.Counter;

    /**
     * Event for when the constructor has finished
     */
    event InitializeEcoClaim();

    /**
     * Event for when a claim is made
     */
    event Claim(
        string socialID,
        address indexed addr,
        uint256 eco,
        uint256 ecox
    );

    /**
     * Event for vesting release
     */
    event ReleaseVesting(
        address indexed addr,
        address indexed gasPayer,
        uint256 ecoBalance,
        uint256 vestedEcoXBalance,
        uint256 feeAmount
    );

    /**
     * Error for when the a signature has expired
     */
    error SignatureExpired();

    /**
     * Error for when the signature is invalid
     */
    error InvalidSignature();

    /**
     * Error for when the first claim is called after the claim period
     */
    error ClaimDeadlineExpired();

    /**
     * Error for when a claim has not been verified in the EcoID by the trusted verifier
     */
    error UnverifiedClaim();

    /**
     * Error for when the submitted proof fails to be validated against the merkle root
     */
    error InvalidProof();

    /**
     * Error for when the submitted proof is not the same depth as the merkle tree
     */
    error InvalidProofDepth();

    /**
     * Error for when the fee amount is greater than the available eco balance
     */
    error InvalidFee();

    /**
     * Error for when the user tries to claim with no points in their balance
     */
    error InvalidPoints();

    /**
     * Error for when the the caller of the release tokens is not the same as that stored in _claimBalances
     */
    error InvalidReleaseCaller();

    /**
     * Error for when the recipient is trying to release an empty balance
     */
    error EmptyVestingBalance();

    /**
     * Error for when the cliff date has not been reached yet and the user tries to release tokens
     */
    error CliffNotMet();

    /**
     * Error for when a user tries to claim tokens for a given social id, that have already been claimed
     */
    error TokensAlreadyClaimed();

    /**
     * Struct for holding the claim fields for a user
     */
    struct ClaimBalance {
        address recipient; //user's addres to send funds to
        uint256 points; //user's initial point balance
        uint256 claimTime; //timestamp of initial claim
    }

    /**
     * The hash of the register function signature for the recipient
     */
    bytes32 private constant CLAIM_TYPEHASH =
        keccak256(
            "Claim(string socialID,address recipient,uint256 feeAmount,uint256 deadline,uint256 nonce)"
        );

    /**
     * The hash of the register function signature for the recipient
     */
    bytes32 private constant RELEASE_TYPEHASH =
        keccak256(
            "Release(string socialID,address recipient,uint256 feeAmount,uint256 deadline,uint256 nonce)"
        );

    /**
     * The period that we use to determine how much the user has vested in ECOx
     */
    uint256 public constant VESTING_PERIOD = 30 days;

    /**
     * The period that a user can claim any tokens
     */
    uint256 public constant CLAIMABLE_PERIOD = 356 days;

    /**
     * The merkel root for the data that maps social ids to their points distribution
     */
    bytes32 public immutable _pointsMerkleRoot;

    /**
     * The depth of the merkel tree from root to leaf. We use this to verify the length of the
     * proofs submitted for verifiaction
     */
    uint256 public immutable _proofDepth;

    /**
     * The mapping that stores the claim status for an account
     */
    mapping(string => bool) public _claimedBalances;

    /**
     * The mapping that stores the claim status for a social id
     */
    mapping(string => ClaimBalance) public _claimBalances;

    /**
     * The mapping that store the current nonce for a social id
     */
    mapping(string => Counters.Counter) private _nonces;

    /**
     * The eco ERC20 contract
     */
    IECO public immutable _eco;

    /**
     * The ecoX ERC20 contract
     */
    ERC20 public immutable _ecoX;

    /**
     * The EcoID contract
     */
    EcoID public immutable _ecoID;

    /**
     * The vesting multiples that users generate over time
     * 0.5x ECOx + 5x ECO at 30 days after initial claim
     * 1.5x ECOx + 5x ECO at 6 mos / 180 days after initial claim
     * 2.5x ECOx + 5x ECO at 18 mos / 540 days after initial claim
     * 3.5x ECOx + 5x ECO at 24 mos / 720 days after initial claim
     */
    uint256[24] public _vestedMultiples = [
        5,
        5,
        5,
        5,
        5,
        15,
        15,
        15,
        15,
        15,
        15,
        15,
        15,
        15,
        15,
        15,
        15,
        25,
        25,
        25,
        25,
        25,
        25,
        35
    ];

    /**
     * The divider for calculating the ECOx vesting returns
     */
    uint256 public constant VESTING_DIVIDER = 10;

    /**
     * The multiplier for points to eco conversion
     */
    uint256 public constant POINTS_MULTIPLIER = 5;

    /**
     * The time that the contract is deployed
     */
    uint256 public immutable _deployTimestamp = block.timestamp;

    /**
     * The time that a user can claim their eco
     */
    uint256 public immutable _claimableEndTime =
        block.timestamp + CLAIMABLE_PERIOD;

    /**
     * The conversion coefficient for when we calculate how much ecox a participant is entitled to for every eco during the initial claim.
     * 2 means points * 1/2 = ecox
     */
    uint256 public constant POINTS_TO_ECOX_RATIO = 2;

    /**
     * The trusted verifier for the socialIDs in the EcoID contract
     */
    address public immutable _trustedVerifier;

    /**
     * The inflation multiplier for eco at deploy, used to calculate payouts
     */
    uint256 public immutable _initialInflationMultiplier;

    /**
     * Constructor that sets the initial conditions and emits an initialization event
     *
     * @param eco the address of the eco contract
     * @param ecoX the address of the ecox contract
     * @param ecoID the address of the EcoID we use to check verifiation
     * @param trustedVerifier the address of the trusted verifier for claims in the EcoID
     * @param merkelRoot the root of the merkle tree used to verify socialId and point distribution
     */
    constructor(
        IECO eco,
        ERC20 ecoX,
        EcoID ecoID,
        address trustedVerifier,
        bytes32 merkelRoot,
        uint256 proofDepth
    ) {
        _eco = eco;
        _ecoX = ecoX;
        _ecoID = ecoID;
        _trustedVerifier = trustedVerifier;
        _pointsMerkleRoot = merkelRoot;
        _proofDepth = proofDepth;
        _initialInflationMultiplier = _eco.getPastLinearInflation(block.number);

        emit InitializeEcoClaim();
    }

    /**
     * Claims tokens that the caller is owned. The caller needs to present the merkel proof
     * for their token allocation. The leaf is generated as the hash of the socialID and
     * points, in that order.
     *
     * @param proof The merkel proof that the socialID and points are correct
     * @param socialID the socialID of the recipient
     * @param points the amount of points the user can claim, must be same as in the merkel tree and not an arbitrary amount
     */
    function claimTokens(
        bytes32[] memory proof,
        string calldata socialID,
        uint256 points
    ) external {
        _claimTokens(proof, socialID, points, msg.sender, 0);
    }

    /**
     * Claims tokens on behalf of a recipient. The recipient has agreed to let another account make the on-chain tx for them, and
     * has agreed to pay them a fee in eco for the service. The caller needs to present the merkel proof for their token allocation.
     * The leaf is generated as the hash of the socialID and points, in that order.
     *
     * @param proof The merkel proof that the socialID and points are correct
     * @param socialID the socialID of the recipient
     * @param points the amount of points the user can claim, must be same as in the merkel tree and not an arbitrary amount
     * @param recipient the recipient of the tokens
     * @param feeAmount the fee in eco the payer is granted from the recipient
     * @param deadline the time at which the signature is no longer valid
     * @param recipientSig the signature signed by the recipient
     */
    function claimTokensOnBehalf(
        bytes32[] memory proof,
        string calldata socialID,
        uint256 points,
        address recipient,
        uint256 feeAmount,
        uint256 deadline,
        bytes calldata recipientSig
    ) external {
        //the claim signature is being called within its valid period
        if (block.timestamp > deadline) {
            revert SignatureExpired();
        }

        //the signature is properly signed
        if (
            !_verifyClaimSigature(
                socialID,
                recipient,
                feeAmount,
                deadline,
                _useNonce(socialID),
                recipientSig
            )
        ) {
            revert InvalidSignature();
        }

        _claimTokens(proof, socialID, points, recipient, feeAmount);
    }

    /**
     * Releases the vested tokens if its passed the initial cliff date. The further from the initial cliff this
     * method is called, the greater a multiple the recipients tokens generate.
     */
    function releaseTokens(string calldata socialID) external {
        _releaseTokens(socialID, msg.sender, 0);
    }

    /**
     * Releases the vested tokens if its passed the initial cliff date. The recipient is paying the caller of this contract
     * and reward them in ecoX. The caller has to present a valid signature to release the funds
     *
     * @param socialID the socialID of the recipient
     * @param recipient the recipient of the tokens
     * @param feeAmount the fee in eco the payer is granted from the recipient
     * @param deadline the time at which the signature is no longer valid
     * @param recipientSig the signature signed by the recipient
     */
    function releaseTokensOnBehalf(
        string calldata socialID,
        address recipient,
        uint256 feeAmount,
        uint256 deadline,
        bytes calldata recipientSig
    ) external {
        //the release signature is being called within its valid period
        if (block.timestamp > deadline) {
            revert SignatureExpired();
        }

        //the signature is properly signed
        if (
            !_verifyReleaseSigature(
                socialID,
                recipient,
                feeAmount,
                deadline,
                _useNonce(socialID),
                recipientSig
            )
        ) {
            revert InvalidSignature();
        }

        _releaseTokens(socialID, recipient, feeAmount);
    }

    /**
     * Makes the _domainSeparatorV4() function externally callable for signature generation
     */
    function DOMAIN_SEPARATOR() external view returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * Claim the tokens. The caller needs to present the merkel proof for their token allocation.
     * The leaf is generated as the hash of the socialID and points, in that order.
     *
     * @param proof The merkel proof that the socialID and points are correct
     * @param socialID the socialID of the recipient
     * @param points the amount of points the user can claim, must be same as in the merkel tree and not an arbitrary amount
     * @param recipient the recipient of the tokens
     * @param feeAmount the fee in eco the payer is granted from the recipient
     */
    function _claimTokens(
        bytes32[] memory proof,
        string calldata socialID,
        uint256 points,
        address recipient,
        uint256 feeAmount
    ) internal {
        //Checks that the social id has not claimed its tokens
        if (_claimedBalances[socialID]) {
            revert TokensAlreadyClaimed();
        }

        //the claim is submitted in the claimable window since contract deploy
        if (block.timestamp > _claimableEndTime) {
            revert ClaimDeadlineExpired();
        }

        //require that the proof length is the same as the merkel tree depth
        if (proof.length != _proofDepth) {
            revert InvalidProofDepth();
        }

        //require that there are points to claim
        if (points == 0) {
            revert InvalidPoints();
        }

        //require that the fee is below the token amount
        if (feeAmount > points * POINTS_MULTIPLIER) {
            revert InvalidFee();
        }

        //eco tokens exist and have not been claimed yet
        if (!_ecoID.isClaimVerified(recipient, socialID, _trustedVerifier)) {
            revert UnverifiedClaim();
        }

        //verift merkle proof from input args
        bytes32 leaf = _getLeaf(socialID, points);
        if (!proof.verify(_pointsMerkleRoot, leaf)) {
            revert InvalidProof();
        }

        //set claimed for social id
        _claimedBalances[socialID] = true;

        //move the tokens
        _executeClaim(socialID, recipient, points, feeAmount);
    }

    /**
     * Performs the calculations and token transfers for a claim. It will send the eco tokens
     * to the recipient and any fee to the payer, also in eco, if there is one. The ecox will
     * also be calculated and transfered to the recipient
     *
     * @param socialID the socialID of the recipient
     * @param recipient the recipient of the tokens
     * @param points the amount of points the user can claim, must be same as in the merkel tree and not an arbitrary amount
     * @param feeAmount the fee in eco the payer is granted from the recipient
     */
    function _executeClaim(
        string calldata socialID,
        address recipient,
        uint256 points,
        uint256 feeAmount
    ) internal {
        uint256 ecoBalance = points * POINTS_MULTIPLIER;
        uint256 ecoXBalance = points / POINTS_TO_ECOX_RATIO;
        //store the eco balance and time of the recipient so we can calculate vesting later
        ClaimBalance storage cb = _claimBalances[socialID];
        cb.recipient = recipient;
        cb.points = points;
        cb.claimTime = block.timestamp;

        //the fee is below the token amount
        if (feeAmount > ecoBalance) {
            revert InvalidFee();
        }

        //transfer ecox
        _ecoX.transfer(recipient, ecoXBalance);

        uint256 currentInflationMult = _eco.getPastLinearInflation(
            block.number
        );

        //transfer eco to recipient and payer
        if (feeAmount != 0) {
            //if there is a payer executing this tx, pay them out
            _eco.transfer(
                msg.sender,
                _applyInflationMultiplier(feeAmount, currentInflationMult)
            );
            _eco.transfer(
                recipient,
                _applyInflationMultiplier(
                    ecoBalance - feeAmount,
                    currentInflationMult
                )
            );
        } else {
            _eco.transfer(
                recipient,
                _applyInflationMultiplier(ecoBalance, currentInflationMult)
            );
        }

        //emit event for succesfull claim
        emit Claim(
            socialID,
            recipient,
            _applyInflationMultiplier(ecoBalance, currentInflationMult),
            ecoXBalance
        );
    }

    /**
     * Releases the vested tokens if its passed the initial cliff date. The recipient can pay a payer for calling this contract
     * and reward them in ecoX
     *
     * @param socialID the social ID of the claim
     * @param recipient the recipient of the tokens
     * @param feeAmount the fee in ecoX the payer is granted from the recipient
     */
    function _releaseTokens(
        string calldata socialID,
        address recipient,
        uint256 feeAmount
    ) internal {
        uint256 currentTime = block.timestamp;
        ClaimBalance storage cb = _claimBalances[socialID];
        if (cb.recipient != recipient) {
            revert InvalidReleaseCaller();
        }
        uint256 points = cb.points;
        uint256 ecoBalance = points * POINTS_MULTIPLIER;

        //the recipient has a balance
        if (ecoBalance == 0) {
            revert EmptyVestingBalance();
        }

        //the cliff time has been passed
        if (cb.claimTime + VESTING_PERIOD > currentTime) {
            revert CliffNotMet();
        }

        //calculating balances
        uint256 currentInflationMult = _eco.getPastLinearInflation(
            block.number
        );
        uint256 vestedBalance;

        //find the vesting period the call is made in and distribute the funds
        for (uint256 i = _vestedMultiples.length; i > 0; i--) {
            if (currentTime > cb.claimTime + VESTING_PERIOD * i) {
                vestedBalance =
                    (points * _vestedMultiples[i - 1]) /
                    VESTING_DIVIDER;
                break;
            }
        }

        //clear out recipients balance
        cb.points = 0;
        cb.claimTime = 0;

        //transfer the balances
        //transfer the ecox
        _ecoX.transfer(recipient, vestedBalance);

        //transfer the eco
        if (feeAmount == 0) {
            _eco.transfer(
                recipient,
                _applyInflationMultiplier(ecoBalance, currentInflationMult)
            );
        } else {
            //the fee is below the token amount
            if (feeAmount > ecoBalance) {
                revert InvalidFee();
            }
            _eco.transfer(
                recipient,
                _applyInflationMultiplier(
                    ecoBalance - feeAmount,
                    currentInflationMult
                )
            );
            _eco.transfer(
                msg.sender,
                _applyInflationMultiplier(feeAmount, currentInflationMult)
            );
        }

        emit ReleaseVesting(
            recipient,
            msg.sender,
            _applyInflationMultiplier(
                ecoBalance - feeAmount,
                currentInflationMult
            ),
            vestedBalance,
            feeAmount
        );
    }

    /**
     * Verifies that the recipient signed the message, and that the message is the correct hash of the
     * parameters for determining the payer pay off and the length the signature is valid.
     *
     * @param socialID the socialID of the recipient
     * @param recipient the recipient of the tokens
     * @param feeAmount the fee in eco the payer is granted from the recipient
     * @param deadline the time at which the signature is no longer valid
     * @param nonce the nonce for the signatures for this claim registration
     * @param recipientSig the signature signed by the recipient
     *
     * @return true if the signature is valid, false otherwise
     */
    function _verifyClaimSigature(
        string calldata socialID,
        address recipient,
        uint256 feeAmount,
        uint256 deadline,
        uint256 nonce,
        bytes calldata recipientSig
    ) internal view returns (bool) {
        bytes32 hash = _hashTypedDataV4(
            keccak256(
                abi.encode(
                    CLAIM_TYPEHASH,
                    keccak256(bytes(socialID)),
                    recipient,
                    feeAmount,
                    deadline,
                    nonce
                )
            )
        );
        return hash.recover(recipientSig) == recipient;
    }

    /**
     * Verifies that the recipient signed the message, and that the message is the correct hash of the
     * parameters for determining the payer pay off and the length the signature is valid.
     *
     * @param socialID the socialID of the recipient
     * @param recipient the recipient of the tokens
     * @param feeAmount the fee in eco the payer is granted from the recipient
     * @param deadline the time at which the signature is no longer valid
     * @param nonce the nonce for the signatures for this claim registration
     *
     * @return true if the signature is valid, false otherwise
     */
    function _verifyReleaseSigature(
        string calldata socialID,
        address recipient,
        uint256 feeAmount,
        uint256 deadline,
        uint256 nonce,
        bytes calldata recipientSig
    ) internal view returns (bool) {
        bytes32 hash = _hashTypedDataV4(
            keccak256(
                abi.encode(
                    RELEASE_TYPEHASH,
                    keccak256(bytes(socialID)),
                    recipient,
                    feeAmount,
                    deadline,
                    nonce
                )
            )
        );
        return hash.recover(recipientSig) == recipient;
    }

    /**
     * Returns the current nonce for a given socialID
     *
     * @param socialID the socialID to get and increment the nonce for
     *
     * @return the nonce
     */
    function nonces(string calldata socialID) public view returns (uint256) {
        return _nonces[socialID].current();
    }

    /**
     * Returns the merkle tree leaf hash for the given data
     */
    function _getLeaf(string calldata socialID, uint256 points)
        private
        pure
        returns (bytes32)
    {
        return keccak256(abi.encodePacked(socialID, points));
    }

    /**
     * Applies the inflation multiplier for eco balances before transfers
     */
    function _applyInflationMultiplier(
        uint256 value,
        uint256 currentInflationMultiplier
    ) internal view returns (uint256) {
        return
            (_initialInflationMultiplier * value) / currentInflationMultiplier;
    }

    /**
     * Returns the current nonce for a claim and automatically increament it
     *
     * @param socialID the socialID to get and increment the nonce for
     *
     * @return current current nonce before incrementing
     */
    function _useNonce(string calldata socialID)
        internal
        returns (uint256 current)
    {
        Counters.Counter storage nonce = _nonces[socialID];
        current = nonce.current();
        nonce.increment();
    }
}