// File: /contracts/artblocks/VerisartArtblocksIntegration.sol



// SPDX-License-Identifier: MIT

import "./IArtblocksCore.sol";
import "./IAdminACLV1.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

pragma solidity ^0.8.9;

contract VerisartArtblocksIntegration {
    bytes32 private constant _DOMAIN_TYPEHASH =
        keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
        );

    bytes32 private _eip712DomainSeparator =
        keccak256(
            abi.encode(
                _DOMAIN_TYPEHASH,
                keccak256("Verisart"),
                keccak256("1"),
                block.chainid,
                address(this),
                0xf84c063feaae44fa2f4a846cf2dadc08b50b6a5b0b04bed3d70ed9fa1a199edc // Verisart's EIP712 salt
            )
        );

    bytes32 private constant _MINT_SIGNED_TYPEHASH =
        keccak256(
            "MintNFT(address sender,address to,uint256 projectId,address core,bytes32 tokenNonce)"
        );

    /**
     * @dev Allows minting via signed mint (an off-chain signature is still required).
     *      By default, this is enabled for all projects/cores.
     *      This can be disabled by the artist/admin via `disableSignedMinting`
     */
    mapping(bytes32 => bool) private _disableSignedMinting;

    mapping(bytes32 => bool) private _signedMints;

    /**
     * @dev Permissions set at the project level.
     */
    mapping(bytes32 => bool) private _mintingPermissionsProjectLevel;

    /**
     * @dev Permissions set at the contract level.
     */
    mapping(bytes32 => bool) private _mintingPermissionsContractLevel;

    event PermissionGrantedContract(
        address indexed core,
        address indexed to,
        address by
    );

    event PermissionRevokedContract(
        address indexed core,
        address indexed to,
        address by
    );

    event PermissionGrantedProject(
        address indexed core,
        uint256 indexed projectId,
        address indexed to,
        address by
    );
    event PermissionRevokedProject(
        address indexed core,
        uint256 indexed projectId,
        address indexed to,
        address by
    );

    function mintSigned(
        address to,
        uint256 projectId,
        address core,
        bytes32 tokenNonce,
        bytes calldata signature
    ) external onlyProjectCorrectlyConfigured(core, projectId) {
        bytes memory args = abi.encode(
            _MINT_SIGNED_TYPEHASH,
            msg.sender,
            to,
            projectId,
            core,
            tokenNonce
        );
        address recoveredAddress = _checkSigned(
            args,
            tokenNonce,
            signature,
            core,
            projectId
        );
        _checkAddressCanMint(core, projectId, recoveredAddress);
        _mintFromNoPermission(core, projectId, to, msg.sender);
    }

    function mint(
        address core,
        uint256 projectId,
        address to
    ) public onlyProjectCorrectlyConfigured(core, projectId) {
        _checkAddressCanMint(core, projectId, msg.sender);
        _mintFromNoPermission(core, projectId, to, msg.sender);
    }

    function _mintFromNoPermission(
        address core,
        uint256 projectId,
        address to,
        address from
    ) private {
        IArtblocksCore artblocksCore = IArtblocksCore(core);
        artblocksCore.mint_Ecf(to, projectId, from);
    }

    function hasMintingPermission(
        address core,
        uint256 projectId,
        address sender
    ) public view returns (bool) {
        IArtblocksCore artblocksCore = IArtblocksCore(core);

        if (
            _mintingPermissionsContractLevel[
                keccak256(abi.encodePacked(core, sender))
            ]
        ) {
            return true;
        }
        if (
            _mintingPermissionsProjectLevel[
                keccak256(abi.encodePacked(core, projectId, sender))
            ]
        ) {
            return true;
        }
        return artblocksCore.projectIdToArtistAddress(projectId) == sender;
    }

    function grantContractPermission(
        address core,
        address to
    ) public onlyAdmin(core, this.grantContractPermission.selector) {
        bytes32 permissionHash = keccak256(abi.encodePacked(core, to));
        _mintingPermissionsContractLevel[permissionHash] = true;
        emit PermissionGrantedContract(core, to, msg.sender);
    }

    function revokeContractPermission(
        address core,
        address to
    ) public onlyAdmin(core, this.revokeContractPermission.selector) {
        bytes32 permissionHash = keccak256(abi.encodePacked(core, to));
        delete _mintingPermissionsContractLevel[permissionHash];
        emit PermissionRevokedContract(core, to, msg.sender);
    }

    function grantProjectPermission(
        address core,
        uint256 projectId,
        address to
    )
        public
        onlyAdminOrArtist(core, projectId, this.grantProjectPermission.selector)
        onlyProjectCorrectlyConfigured(core, projectId)
    {
        bytes32 permissionHash = keccak256(
            abi.encodePacked(core, projectId, to)
        );
        _mintingPermissionsProjectLevel[permissionHash] = true;
        emit PermissionGrantedProject(core, projectId, to, msg.sender);
    }

    function revokeProjectPermission(
        address core,
        uint256 projectId,
        address to
    )
        public
        onlyAdminOrArtist(
            core,
            projectId,
            this.revokeProjectPermission.selector
        )
        onlyProjectCorrectlyConfigured(core, projectId)
    {
        bytes32 permissionHash = keccak256(
            abi.encodePacked(core, projectId, to)
        );
        delete _mintingPermissionsProjectLevel[permissionHash];
        emit PermissionRevokedProject(core, projectId, to, msg.sender);
    }

    modifier onlyAdmin(address core, bytes4 _selector) {
        IArtblocksCore artblocksCore = IArtblocksCore(core);
        require(
            artblocksCore.adminACLAllowed(msg.sender, address(this), _selector),
            "Only admin"
        );
        _;
    }

    modifier onlyAdminOrArtist(
        address core,
        uint256 projectId,
        bytes4 _selector
    ) {
        IArtblocksCore artblocksCore = IArtblocksCore(core);
        require(
            artblocksCore.projectIdToArtistAddress(projectId) == msg.sender ||
                artblocksCore.adminACLAllowed(
                    msg.sender,
                    address(this),
                    _selector
                ),
            "Only artist or admin"
        );
        _;
    }

    /**
     * Checks if the project is correctly configured - a sanity check.
     * 1. The project must have an artist address set - This confirms the project exists
     * 2. The project must have this contract set as the minter - Otherwise we can't mint
     */
    function projectCorrectlyConfigured(
        address _core,
        uint256 _projectId
    ) public view returns (bool) {
        IArtblocksCore artblocksCore = IArtblocksCore(_core);
        if (artblocksCore.projectIdToArtistAddress(_projectId) == address(0))
            return false;
        return artblocksCore.minterContract() == address(this);
    }

    modifier onlyProjectCorrectlyConfigured(address _core, uint256 _projectId) {
        require(
            projectCorrectlyConfigured(_core, _projectId),
            "Project not correctly configured"
        );
        _;
    }

    function allowSignedMinting(
        address core,
        uint256 projectId
    )
        public
        view
        onlyProjectCorrectlyConfigured(core, projectId)
        returns (bool)
    {
        return
            !_disableSignedMinting[
                keccak256(abi.encodePacked(core, projectId))
            ];
    }

    function enableSignedMinting(
        address core,
        uint256 projectId
    )
        external
        onlyAdminOrArtist(core, projectId, this.enableSignedMinting.selector)
        onlyProjectCorrectlyConfigured(core, projectId)
    {
        _disableSignedMinting[
            keccak256(abi.encodePacked(core, projectId))
        ] = false;
    }

    function disableSignedMinting(
        address core,
        uint256 projectId
    )
        external
        onlyAdminOrArtist(core, projectId, this.disableSignedMinting.selector)
        onlyProjectCorrectlyConfigured(core, projectId)
    {
        _disableSignedMinting[
            keccak256(abi.encodePacked(core, projectId))
        ] = true;
    }

    function _checkAddressCanMint(
        address core,
        uint256 projectId,
        address sender
    ) private view {
        require(
            hasMintingPermission(core, projectId, sender),
            "Not authorized to mint"
        );
    }

    function minterType() external pure returns (string memory) {
        return "VerisartArtblocksIntegrationMinter";
    }

    function _checkSigned(
        bytes memory args,
        bytes32 tokenNonce,
        bytes memory signature,
        address core,
        uint256 projectId
    ) private returns (address) {
        require(
            allowSignedMinting(core, projectId),
            "Signed minting not allowed"
        );

        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                _eip712DomainSeparator,
                keccak256(args)
            )
        );
        require(
            _signedMints[tokenNonce] == false,
            "Signed mint already redeemed"
        );
        _signedMints[tokenNonce] = true;
        return ECDSA.recover(digest, signature);
    }
}

// File: /contracts/artblocks/IArtblocksCore.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

abstract contract IArtblocksCore {
    address public minterContract;

    function projectIdToArtistAddress(
        uint256 _projectId
    ) external view virtual returns (address payable);

    function adminACLAllowed(
        address _sender,
        address _contract,
        bytes4 _selector
    ) public virtual returns (bool);

    // solhint-disable-next-line
    function mint_Ecf(
        address _to,
        uint256 _projectId,
        address _by
    ) external virtual returns (uint256 _tokenId);
}

// File: /contracts/artblocks/IAdminACLV1.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

abstract contract IAdminACLV1 {
    function allowed(
        address _sender,
        address /*_contract*/,
        bytes4 _selector
    ) external view virtual returns (bool);
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.3) (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) {
        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.
            /// @solidity memory-safe-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 {
            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/Strings.sol



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

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

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

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}