// 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/cryptography/ECDSA.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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 // Deprecated in v4.8
    }

    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");
        }
    }

    /**
     * @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 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/math/Math.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

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



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

pragma solidity ^0.8.0;

import "./math/Math.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _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) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

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

// File: contracts/Webstela.sol



// SPDX-License-Identifier: NONE

pragma solidity ^0.8.21;

import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

/**
 * @title Webstela
 * @author Kang Myung-hun
 */

contract Base {
    struct Token {
        address owner;
        address royaltyHolder;
        uint256 price;
        bytes32 hashed;    // SHA256
        bytes32 namespace; // UTF-8
        string  uri;
        mapping(bytes32 => bytes32) meta; // custom meta data
    }

    struct MintFeeTable {
        uint256 on;      // permyriad
        uint256 royalty; // permyriad
    }

    struct BuyFeeTable {
        uint256 fee;     // royalty + implicit contract owner commission
        uint256 royalty; // permyriad
    }

    struct Transferring {
        address to;
        uint256 value;
    }

    address internal _contractOwner; // contract owner
    address internal _manager;

    string internal _name;
    string internal _symbol;
    string internal _baseURI;

    uint256 internal _tokenIdCounter;
    MintFeeTable internal _mintFeeTable;
    BuyFeeTable internal _buyFeeTable;

    mapping(uint256 => Token) internal _tokens;
    mapping(bytes32 => uint256) internal _hashedToTokenIds;
    mapping(address => uint256) internal _balances;
    mapping(address => uint256) internal _names;
    
    mapping(uint256 => address) internal _tokenApprovals;
    mapping(address => mapping(address => bool)) internal _operatorApprovals;

    event Symbol(string indexed symbol);
    event ContractOwner(address indexed from, address indexed to);
    event Manager(address indexed from, address indexed to);

    event MintFee(uint256 on, uint256 royalty);
    event BuyFee(uint256 fee, uint256 royalty);

    event TokenURIBase(string uri);

    event AccountName(address indexed owner, bytes32 indexed name);
    event Mint(uint256 indexed tokenId, bytes32 indexed hashed, bytes32 indexed on);
    event Buy(uint256 indexed tokenID, uint256 price);
    event TokenMeta(
        uint256 indexed tokenId,
        bytes32[] keys,
        bytes32[] values
    );
    event TokenNamespace(uint256 indexed tokenId, bytes32 indexed namespace);
    event TokenRoyaltyHolder(uint256 indexed tokenId, address indexed holder);
    event TokenPrice(uint256 indexed tokenId, uint256 to);
    event TokenURI(uint256 indexed tokenId, string uri);


    /* IERC721 */

    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);


    /* Utils */

    function _msgSender() internal view returns (address) {
        return msg.sender;
    }

    function _isContract(address account) internal view returns (bool) {
        return account.code.length > 0;
    }

    function _checkTokenOwner(address owner) internal view {
        require(owner == _msgSender(), "caller is not the token owner");
    }

    function _transferEthers(address to, uint256 value) internal returns (uint256 refund) {
        if (to == address(0) || to == address(this) || to == _contractOwner) return 0;
        if (to == _msgSender()) return value;
        payable(to).transfer(value);
    }

    function _transferEthers(Transferring memory a, Transferring memory b) internal returns (uint256 refund) {
        if (a.to == b.to) {
            return _transferEthers(a.to, a.value + b.value);
        }
        return _transferEthers(a.to, a.value) + _transferEthers(b.to, b.value);
    }

    function _setTokenPrice(uint256 tokenId, Token storage token, uint256 to) internal {
        require(to <= 100_00 * to, "too high price");
        if (token.price == to) return;

        token.price = to;
        emit TokenPrice(tokenId, to);
    }
}

contract Managed is Base {
    function contractOwner() public view returns (address) {
        return _contractOwner;
    }

    function manager() public view returns (address) {
        return _manager;
    }

    function setContractOwner(address to) public onlyContractOwner {
        require(to.balance > 0, "invalid address");
        withdraw();

        address from = _contractOwner;
        _contractOwner = to;
        emit ContractOwner(from, to);
    }

    function setManager(address to) public {
        require(
            _contractOwner == _msgSender() || _manager == _msgSender(),
            "caller is not the contract owner or the manager"
        );
        address from = _manager;
        _manager = to;
        emit Manager(from, to);
    }

    function setTokenURIBase(string calldata baseURI) public onlyManager {
        _baseURI = baseURI;
        emit TokenURIBase(baseURI);
    }

    function setMintFee(uint256 on, uint256 royalty) public onlyManager {
        require(100_00 > on + royalty, "too low commission");

        _mintFeeTable.on = on;
        _mintFeeTable.royalty = royalty;
        // commission = 100_00 - on - royalty;

        emit MintFee(on, royalty);
    }

    function setBuyFee(uint256 fee, uint256 royalty) public onlyManager {
        require(100_00 > fee, "too high fee");
        require(fee > royalty, "too low commission");

        _buyFeeTable.fee = fee;
        _buyFeeTable.royalty = royalty;
        // commission = fee - royalty;

        emit BuyFee(fee, royalty);
    }

    function withdraw() public {
        payable(_contractOwner).transfer(address(this).balance);
    }

    function callFor(
        address to,
        uint256 value,
        uint256 gas,
        bytes calldata data
    ) public payable onlyContractOwner() returns (bool, bytes memory) {
        return to.call{value: value, gas: gas}(data);
    }

    modifier onlyContractOwner() {
        require(_contractOwner == _msgSender(), "caller is not the contract owner");
        _;
    }

    modifier onlyManager() {
        require(_manager == _msgSender(), "caller is not the manager");
        _;
    }
}

contract ERCToken is Managed {
    using Strings for uint256;

    function totalSupply() public view returns (uint256) {
        return _tokenIdCounter - 1;
    }


    /* IERC615 */

    function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
        return
            interfaceId == 0x01ffc9a7 || // ERC165
            interfaceId == 0x80ac58cd || // ERC721
            interfaceId == 0x5b5e139f;   // ERC721Metadata
    }


    /* IERC721Metadata */

    function name() public view returns (string memory) {
        return _name;
    }

    function symbol() public view returns (string memory) {
        return _symbol;
    }

    function tokenURI(uint256 tokenId) public view returns (string memory) {
        string memory uri = _tokens[tokenId].uri;
        if (bytes(uri).length > 0) {
            return uri;
        }
        return string(abi.encodePacked(_baseURI, tokenId.toString()));
    }

    function setSymbol(string calldata to) external onlyManager() {
        _symbol = to;
        emit Symbol(to);
    }

    function setTokenURI(uint256 tokenId, string calldata uri) external {
        Token storage token = _tokens[tokenId];
        _checkTokenOwner(token.owner);

        token.uri = uri;
        emit TokenURI(tokenId, uri);
    }


    /* IERC721 */

    function balanceOf(address owner) public view returns (uint256) {
        require(owner != address(0), "address zero is not a valid owner");

        return _balances[owner];
    }

    function ownerOf(uint256 tokenId) public view returns (address) {
        address owner = _ownerOf(tokenId);

        return owner;
    }

    function approve(address to, uint256 tokenId) public {
        address owner = ownerOf(tokenId);
        require(to != owner, "approval to current owner");
        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "approve caller is not the token owner or the approved for all"
        );

        _approve(to, tokenId);
    }

    function getApproved(uint256 tokenId) public view returns (address) {
        return _tokenApprovals[tokenId];
    }

    function setApprovalForAll(address operator, bool approved) public {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    function isApprovedForAll(address owner, address operator) public view returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not the token owner or the approved");

        _transfer(from, to, tokenId);
        _setTokenPrice(tokenId, _tokens[tokenId], 0);
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) public {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not the token owner or the approved");

        _safeTransfer(from, to, tokenId, data);
        _setTokenPrice(tokenId, _tokens[tokenId], 0);
    }


    /* Internal */

    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "transfer to non ERC721Receiver implementer");
    }

    function _ownerOf(uint256 tokenId) internal view returns (address) {
        return _tokens[tokenId].owner;
    }

    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
        address owner = ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal {
        require(ownerOf(tokenId) == from, "transfer from incorrect owner");
        require(to != address(0), "transfer to the zero address");

        if (_tokenApprovals[tokenId] != address(0)) {
            delete _tokenApprovals[tokenId];
        }

        unchecked {
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _tokens[tokenId].owner = to;

        if (_names[from] == tokenId) {
            delete _names[from];
            emit AccountName(from, "");
        }

        emit Transfer(from, to, tokenId);
    }

    function _approve(address to, uint256 tokenId) internal {
        _tokenApprovals[tokenId] = to;
        emit Approval(ownerOf(tokenId), to, tokenId);
    }

    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal {
        require(owner != operator, "approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal returns (bool) {
        if (_isContract(to)) {
            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("transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }
}

contract HashableToken is ERCToken {
    function tokenIdOf(bytes32 hashed) public view returns (uint256) {
        return _hashedToTokenIds[hashed];
    }

    function ownerOf(bytes32 hashed) public view returns (address) {
        return ownerOf(tokenIdOf(hashed));
    }

    function hashOf(uint256 tokenId) public view returns (bytes32) {
        return _tokens[tokenId].hashed;
    }

    function mintByManager(
        bytes32 hashed,
        bytes32 on,
        address creator,
        address to,
        uint256 price,
        uint256 nextPrice
    ) external payable onlyManager {
        require(to != address(0), "invalid token owner");

        _mint(hashed, on, creator, to, price, nextPrice);
    }

    function mintBatchByManager(
        bytes32[] calldata hashes,
        bytes32 on,
        address creator,
        address to,
        uint256 price,
        uint256[] calldata nextPrices
    ) external payable onlyManager {
        require(to != address(0), "invalid token owner");

        _mintBatch(hashes, on, creator, to, price, nextPrices);
    }

    function mint(
        bytes32 hashed,
        bytes32 on,
        address creator,
        uint256 price,
        uint256 nextPrice,
        uint256 discount,
        uint256 timeout,
        bytes calldata signature
    ) external payable {
        address to = _msgSender();
        bytes32 challenge = sha256(abi.encodePacked(hashed, on, creator, to, price, discount, timeout));
        _validateMinting(
            price,
            discount,
            timeout,
            challenge,
            signature
        );

        _mint(hashed, on, creator, to, price, nextPrice);
    }

    function mintBatch(
        bytes32[] calldata hashes,
        bytes32 on,
        address creator,
        uint256 price,
        uint256[] calldata nextPrices,
        uint256 discount,
        uint256 timeout,
        bytes calldata signature
    ) external payable {
        address to = _msgSender();
        bytes32 challenge = sha256(abi.encodePacked(hashes, on, creator, to, price, discount, timeout));
        _validateMinting(
            price,
            discount,
            timeout,
            challenge,
            signature
        );

        _mintBatch(hashes, on, creator, to, price, nextPrices);
    }

    function _validateMinting(
        uint256 price,
        uint256 discount,
        uint256 timeout,
        bytes32 challenge,
        bytes calldata signature
    ) private {
        require(timeout > block.timestamp, "timed out");
        require(msg.value >= price - discount, "not enough ethers");
        require(manager() == ECDSA.recover(
            keccak256(
                abi.encodePacked("\x19Ethereum Signed Message:\n32", challenge)
            ),
            signature
        ), "invalid signature");
    }

    function _mint(
        bytes32 hashed,
        bytes32 on,
        address creator,
        address to,
        uint256 price,
        uint256 nextPrice
    ) private {
        require(creator != address(0), "invalid token creator");

        uint256 tokenId = _tokenIdCounter;
        _unsafeMint(tokenId, hashed, on, creator, to, price, nextPrice);
        _completeMint(on, creator, to, price, 1);
    }

    function _mintBatch(
        bytes32[] calldata hashes,
        bytes32 on,
        address creator,
        address to,
        uint256 price,
        uint256[] calldata nextPrices
    ) private {
        require(creator != address(0), "invalid token creator");

        uint256 len = hashes.length;
        require(len == nextPrices.length, "invalid next prices");
        for (uint256 i = 0; i < len; i++) {
            _unsafeMint(_tokenIdCounter + i, hashes[i], on, creator, to, price, nextPrices[i]);
        }
        _completeMint(on, creator, to, price, len);
    }

    function _unsafeMint(
        uint256 tokenId,
        bytes32 hashed,
        bytes32 on,
        address creator,
        address to,
        uint256 price,
        uint256 nextPrice
    ) private {
        require(hashed != "", "invalid hashed");
        require(_hashedToTokenIds[hashed] == 0, "already exists");

        emit Mint(tokenId, hashed, on);
        emit TokenRoyaltyHolder(tokenId, creator);
        emit TokenPrice(tokenId, price);

        _hashedToTokenIds[hashed] = tokenId;
        Token storage token = _tokens[tokenId];
        token.owner = to;
        token.hashed = hashed;
        token.royaltyHolder = creator;

        emit Buy(tokenId, price);
        emit Transfer(address(0), to, tokenId);
        _setTokenPrice(tokenId, token, nextPrice);
    }

    function _completeMint(
        bytes32 on,
        address creator,
        address to,
        uint256 price,
        uint256 count
    ) private {
        unchecked {
            _tokenIdCounter += count;
            _balances[to] += count;
        }

        _transferEthers(
            Transferring(creator, price * _mintFeeTable.royalty / 100_00),
            Transferring(ownerOf(on), price * _mintFeeTable.on / 100_00)
        );
    }
}

contract Webstela is HashableToken {
    constructor(address manager) {
        _contractOwner = msg.sender;
        _manager = manager;

        _name = "Webstela";
        _symbol = "WSTLA";
        _baseURI = "https://static.webstela.com/nft/";

        _tokenIdCounter = 1;

        _mintFeeTable.on = 20_00;
        _mintFeeTable.royalty = 70_00;
        // 10% commission

        _buyFeeTable.fee = 10_00;
        _buyFeeTable.royalty = 5_00;
        //  5% commission

        emit Symbol(_symbol);
        emit ContractOwner(address(0), _contractOwner);
        emit Manager(address(0), _manager);

        emit TokenURIBase(_baseURI);
        emit MintFee(
            _mintFeeTable.on,
            _mintFeeTable.royalty
        );
        emit BuyFee(_buyFeeTable.fee, _buyFeeTable.royalty);
    }

    fallback() external payable {}
    receive() external payable {}


    /* Namespace */

    /// @return namespace UTF-8
    function namespaceOf(uint256 tokenId) public view returns (bytes32) {
        return _tokens[tokenId].namespace;
    }

    /// @return namespace UTF-8
    function nameOf(address owner) public view returns (bytes32) {
        return namespaceOf(_names[owner]);
    }

    function setAccountName(uint256 tokenId) external {
        Token storage token = _tokens[tokenId];
        _checkTokenOwner(token.owner);
        require(token.namespace != "", "invalid namespace");

        _names[token.owner] = tokenId;
        emit AccountName(token.owner, token.namespace);
    }

    /// @param namespace UTF-8
    function setTokenNamespace(uint256 tokenId, bytes calldata namespace) public {
        for (uint i = 0; i < namespace.length; i++) {
            uint8 char = uint8(namespace[i]);
            require(
                (char > 47 && char < 58) ||
                (char > 96 && char < 123), "invalid namespace - only lowercased alphanumeric");
        }
        _unsafeSetTokenNamespace(tokenId, namespace);
    }

    /// @param namespace UTF-8
    function unsafeSetTokenNamespace(uint256 tokenId, bytes calldata namespace) public onlyManager {
        _unsafeSetTokenNamespace(tokenId, namespace);
    }

    function _unsafeSetTokenNamespace(uint256 tokenId, bytes calldata namespace) private {
        Token storage token = _tokens[tokenId];

        require(namespace.length < 33, "invalid namespace length");
        require(token.hashed == sha256(namespace), "invalid namespace hash");

        token.namespace = bytes32(namespace);
        emit TokenNamespace(tokenId, token.namespace);
    }


    /* Meta */

    function valueOf(uint256 tokenId, bytes32 key) public view returns (bytes32) {
        return _tokens[tokenId].meta[key];
    }

    function valueOf(bytes32 hashed, bytes32 key) public view returns (bytes32) {
        return valueOf(tokenIdOf(hashed), key);
    }

    function setTokenMeta(uint256 tokenId, bytes32[] calldata keys, bytes32[] calldata values) external {
        Token storage token = _tokens[tokenId];
        _checkTokenOwner(token.owner);
        require(keys.length == values.length, "invalid key value pairs");

        for (uint256 i = 0; i < keys.length; ++i) {
            token.meta[keys[i]] = values[i];
        }
        emit TokenMeta(tokenId, keys, values);
    }


    /* Account Migration */

    function migrateAccount(address to, uint256[] calldata tokenIds) public {
        address from = _msgSender();
        uint256 balance = 0;
        for (uint256 i = 0; i < tokenIds.length; i++) {
            uint256 tokenId = tokenIds[i];
            Token storage token = _tokens[tokenId];
            if (from == token.royaltyHolder) {
                token.royaltyHolder = to;
                emit TokenRoyaltyHolder(tokenId, to);
            }
            if (from == token.owner) {
                token.owner = to;
                emit Transfer(from, to, tokenId);
                balance += 1;
            }
        }
        if (balance > 0) {
            _balances[from] -= balance;
            _balances[to] += balance;
        }
    }


    /* Market */

    function royaltyHolderOf(uint256 tokenId) public view returns (address) {
        return _tokens[tokenId].royaltyHolder;
    }

    function priceOf(uint256 tokenId) public view returns (uint256) {
        return _tokens[tokenId].price;
    }

    function setTokenRoyaltyHolder(uint256 tokenId, address to) external {
        Token storage token = _tokens[tokenId];
        require(token.royaltyHolder == _msgSender(), "caller is not the royalty holder");

        token.royaltyHolder = to;
        emit TokenRoyaltyHolder(tokenId, to);
    }

    function setTokenPrice(uint256 tokenId, uint256 price) external {
        Token storage token = _tokens[tokenId];
        _checkTokenOwner(token.owner);
        _setTokenPrice(tokenId, token, price);
    }

    function buyFor(uint256 tokenId, uint256 nextPrice, address _for) public payable {
        Token storage token = _tokens[tokenId];

        address from = token.owner;
        uint256 price = token.price;
        require(price > 0, "locked to sell");
        require(msg.value >= price, "not enough ethers");

        uint256 royalty = price * _buyFeeTable.royalty / 100_00;
        uint256 net = price * (100_00 - _buyFeeTable.fee) / 100_00;

        emit Buy(tokenId, price);
        _transfer(from, _for, tokenId);
        _setTokenPrice(tokenId, token, nextPrice);

        uint256 refund;
        if (msg.value > price) {
            refund = msg.value - price;
        }
        refund += _transferEthers(token.royaltyHolder, royalty);
        refund += _transferEthers(from, net);
        if (refund > 0) {
            payable(_msgSender()).transfer(refund);
        }
    }

    function buy(uint256 tokenId, uint256 nextPrice) public payable {
       buyFor(tokenId, nextPrice, _msgSender()); 
    }

    function buyBatch(uint256[] calldata tokenIds, uint256[] calldata nextPrices) public payable {
        require(tokenIds.length == nextPrices.length, "invalid arguments");

        address sender = _msgSender();
        address[] memory addresses = new address[](tokenIds.length * 2);
        uint256[] memory values = new uint256[](tokenIds.length * 2);
        uint256 total;

        for (uint256 i = 0; i < tokenIds.length; ++i) {
            uint256 tokenId = tokenIds[i];

            Token storage token = _tokens[tokenId];
            uint256 price = token.price;
            require(price > 0, "locked to sell");

            uint256 royalty = price * _buyFeeTable.royalty / 100_00;
            uint256 net = price * (100_00 - _buyFeeTable.fee) / 100_00;

            _transferring(addresses, values, token.royaltyHolder, royalty);
            _transferring(addresses, values, token.owner, net);
            total += price;

            emit Buy(tokenId, price);
            _transfer(token.owner, sender, tokenId);
            _setTokenPrice(tokenId, token, nextPrices[i]);
        }

        require(msg.value >= total, "not enough ethers");

        uint256 refund;
        if (msg.value > total) {
            refund = msg.value - total;
        }
        for (uint256 i = 0; i < addresses.length; ++i) {
            address to = addresses[i];
            if (to == address(0)) break;
            refund += _transferEthers(to, values[i]);
        }
        if (refund > 0) {
            payable(_msgSender()).transfer(refund);
        }
    }

    function _transferring(
        address[] memory addresses,
        uint256[] memory values,
        address to,
        uint256 value
    ) private pure {
        uint256 idx;
        for (uint256 i = 0 ; i < addresses.length; i++) {
            if (addresses[i] == to) {
                idx = i;
                break;
            }
            if (addresses[i] == address(0)) {
                addresses[i] = to;
                idx = i;
                break;
            }
        }
        values[idx] += value;
    }
}