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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (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 Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        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/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, "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");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, 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) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, 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) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or 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 {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // 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
            /// @solidity memory-safe-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/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: contracts/Base64.sol



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

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

    /// @notice Encodes some bytes to the base64 representation
    function encode(bytes memory data) internal pure returns (string memory) {
        uint256 len = data.length;
        if (len == 0) return "";

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

        // Add some extra buffer at the end
        bytes memory result = new bytes(encodedLen + 32);

        bytes memory table = TABLE;

        assembly {
            let tablePtr := add(table, 1)
            let resultPtr := add(result, 32)

            for {
                let i := 0
            } lt(i, len) {

            } {
                i := add(i, 3)
                let input := and(mload(add(data, i)), 0xffffff)

                let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
                out := shl(8, out)
                out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
                out := shl(8, out)
                out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
                out := shl(8, out)
                out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
                out := shl(224, out)

                mstore(resultPtr, out)

                resultPtr := add(resultPtr, 4)
            }

            switch mod(len, 3)
            case 1 {
                mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
            }
            case 2 {
                mstore(sub(resultPtr, 1), shl(248, 0x3d))
            }

            mstore(result, encodedLen)
        }

        return string(result);
    }
}
// File: contracts/Ethernals.sol



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

import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Inscription.sol";
import "./Base64.sol";

contract Ethernals is Inscription, Ownable {
    using Counters for Counters.Counter;

    string public constant ETHERNAL_HEAER = "eth";
    uint8 public constant ETHERNAL_VER = 1;

    string private baseURL;
    Counters.Counter private _inscriptionIdTracker;

    constructor(
        string memory _baseURL
    ) Inscription("Ethernal Inscriptions", "INSCRIPTION") {
        baseURL = _baseURL;
        _inscriptionIdTracker.increment(); // default inscription ID 1
    }

    /**
     * @dev inscribe an inscription.
     * The inscribing function solely validates the format of the calldata and does not verify its content. 
     * The correct content data should be prepared.
     * The inscribing function does not check for content duplication.
     *
     * Ethernals are inscribed by sending a transaction to the contract, the calldata must encoded as follows:
     *  - 3 bytes: header, must be "eth"
     *  - 1 byte: version, must be 1
     *  - 1 byte: content type length
     *  - content type bytes with length of content type length
     *  - 4 byte: content length
     *  - content bytes with length of content length
     *
     * @param input the calldata to be inscribed
     * @return bytes inscription ID encoded by abi.encode(uint256)
     */
    fallback(bytes calldata input) external returns (bytes memory) {
        require(msg.sender == tx.origin, "only EOA");
        require(keccak256(abi.encodePacked(string(input[0:3]))) == keccak256(abi.encodePacked(ETHERNAL_HEAER)), "invalid header");
        require(uint8(input[3]) == ETHERNAL_VER, "invalid version");
        uint8 ctlen = uint8(input[4]);
        uint32 clen = uint32(bytes4(input[5+ctlen:9+ctlen]));
        require(ctlen > 0 && clen > 0 && input.length == 9 + ctlen + clen, "invalid calldata length");

        uint256 id = _inscriptionIdTracker.current();
        _inscriptionIdTracker.increment();
        _inscribe(msg.sender, id, new bytes(0));
        return abi.encode(id);
    }

    receive() external payable {
        revert();
    }

    function tokenURI(uint256 inscriptionId) override public view returns (string memory) {
        string[17] memory parts;
        parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 300 300"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="30" class="base">';
        parts[1] = string(abi.encodePacked('Ethernals Protocol'));
        parts[2] = '</text><text x="10" y="60" class="base">';
        parts[3] = string(abi.encodePacked('Inscription #', toString(inscriptionId)));
        parts[4] = '</text><text x="10" y="90" class="base">';
        parts[5] = string(abi.encodePacked(baseURL, '/inscription/', toString(inscriptionId)));
        parts[6] = '</text></svg>';

        string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]));
        
        string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Inscription #', toString(inscriptionId), '", "description": "The Ethernals protocol is a new way of inscribing inscriptions on the Ethereum blockchain. The content of the inscription is immutable, and the data is permanently stored on the Ethereum blockchain. Inscription supports a variety of content formats, including text, images, HTMLs, and videos.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
        output = string(abi.encodePacked('data:application/json;base64,', json));

        return output;
    }

    function inscriptionURL(uint256 inscriptionId) override public view returns (string memory) {
        return string(abi.encodePacked(baseURL, '/preview/', toString(inscriptionId)));
    }

    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT license
        // 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);
    }
}

// File: contracts/Inscription.sol



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

import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";

import "./interfaces/IInscription.sol";
import "./interfaces/IInscriptionMetadata.sol";
import "./interfaces/IInscriptionReceiver.sol";

contract Inscription is Context, ERC165, IInscription, IInscriptionMetadata {
    using Address for address;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

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

    // 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(IInscription).interfaceId ||
            super.supportsInterface(interfaceId);
    }

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

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

    /**
     * @dev Returns the symbol of the inscription.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the URI of the inscription.
     */
    function tokenURI(uint256 inscriptionId) public view virtual override returns (string memory) {
        return "";
    }

    /**
     * @dev Returns the URL of the inscription.
     */
    function inscriptionURL(uint256 inscriptionId) public view virtual override returns (string memory) {
        return "";
    }

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

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

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

    /**
     * @dev Safely transfers `inscriptionId` inscription from `from` to `to`, checking first that contract recipients
     * are aware of the Inscription protocol to prevent inscriptions 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 inscription transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `inscriptionId` inscription must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IInscriptionReceiver-onInscriptionReceived}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 inscriptionId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, inscriptionId);
        require(_checkOnInscriptionReceived(from, to, inscriptionId, _data), "Inscription: transfer to non InscriptionReceiver implementer");
    }

    /**
     * @dev Mints `inscriptionId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `inscriptionId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IInscriptionReceiver-onInscriptionReceived}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _inscribe(
        address to,
        uint256 inscriptionId,
        bytes memory _data
    ) internal virtual {
        require(to != address(0), "Inscription: inscribe to the zero address");
        require(!_exists(inscriptionId), "Inscription: inscription already inscribed");

        _owners[inscriptionId] = to;
        emit Transfer(address(0), to, inscriptionId);

        require(
            _checkOnInscriptionReceived(address(0), to, inscriptionId, _data),
            "Inscription: transfer to non InscriptionReceiver implementer"
        );
    }

    /**
     * @dev Returns whether `inscriptionId` exists.
     *
     * Inscriptions can be managed by their owner or approved accounts via {setApprovalForAll}.
     *
     * Inscriptions start existing when they are inscribed (`_inscribe`).
     */
    function _exists(uint256 inscriptionId) internal view virtual returns (bool) {
        return _owners[inscriptionId] != address(0);
    }

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

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

        _owners[inscriptionId] = to;
        emit Transfer(from, to, inscriptionId);
    }

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

    /**
     * @dev Internal function to invoke {IInscriptionReceiver-onInscriptionReceived} 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 inscription ID
     * @param to target address that will receive the inscriptions
     * @param inscriptionId uint256 ID of the inscription 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 _checkOnInscriptionReceived(
        address from,
        address to,
        uint256 inscriptionId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try IInscriptionReceiver(to).onInscriptionReceived(_msgSender(), from, inscriptionId, _data) returns (bytes4 retval) {
                return retval == IInscriptionReceiver.onInscriptionReceived.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("Inscription: transfer to non InscriptionReceiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

}
// File: contracts/interfaces/IInscription.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an IInscription compliant contract.
 */
interface IInscription is IERC165 {
    /**
     * @dev Emitted when `inscriptionId` inscription is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed inscriptionId);

    /**
     * @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 owner of the `inscriptionId` inscription.
     *
     * Requirements:
     *
     * - `inscriptionId` must exist.
     */
    function ownerOf(uint256 inscriptionId) external view returns (address owner);

    /**
     * @dev Safely transfers `inscriptionId` inscription from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `inscriptionId` inscription must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this inscription by {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IInscriptionReceiver-onInscriptionReceived}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 inscriptionId,
        bytes calldata data
    ) external;


    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {safeTransferFrom} for any inscription owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @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: contracts/interfaces/IInscriptionMetadata.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IInscription.sol";

interface IInscriptionMetadata is IInscription {
    /**
     * @dev Returns the inscription name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `inscriptionId` inscription.
     */
    function tokenURI(uint256 inscriptionId) external view returns (string memory);

    /**
     * @dev Returns the Inscription Uniform Resource Locator (URL) for `inscriptionId` inscription.
     */
    function inscriptionURL(uint256 inscriptionId) external view returns (string memory);
}

// File: contracts/interfaces/IInscriptionReceiver.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title IInscription inscription receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from IInscription asset contracts.
 */
interface IInscriptionReceiver {
    /**
     * @dev Whenever an {IInscription} `inscriptionId` inscription is transferred to this contract via {IInscription-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the inscription 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 `IInscriptionReceiver.onInscriptionReceived.selector`.
     */
    function onInscriptionReceived(
        address operator,
        address from,
        uint256 inscriptionId,
        bytes calldata data
    ) external returns (bytes4);
}