// File: @nftculture/nftc-contracts-private/contracts/access/v2/OwnableDeferral.sol



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

/**
 * @title OwnableDeferral
 * @author @NiftyMike | @NFTCulture
 * @dev Implements checks for contract admin operations. Will be Backed by
 * OZ Ownable.
 *
 * This contract is helpful when a contract tree gets complicated,
 * and multiple contracts need to leverage Ownable.
 *
 * Sample Implementation:
 *
 * modifier isOwner() override(...) {
 *     _isOwner();
 *     _;
 * }
 *
 * function _isOwner() internal view override(...) {
 *     _checkOwner();
 * }
 */
abstract contract OwnableDeferral {
    modifier isOwner() virtual;

    function _isOwner() internal view virtual;
}

// File: @nftculture/nftc-contracts-private/contracts/access/v2/OwnableDeferralResolution.sol



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

// OZ Libraries
import '@openzeppelin/contracts/access/Ownable.sol';

// Local References
import './OwnableDeferral.sol';

// Error Codes
error CallerIsNotOwner();

/**
 * @title OwnableDeferralResolution
 * @author @NiftyMike | @NFTCulture
 * @dev Implements checks for contract admin (Owner) operations. Backed by OZ Ownable.
 *
 * Ownership is assigned to contract deployer wallet by default.
 *
 * NOTE: IMPORTANT - This resolution will work great in a simple inheritance situation,
 * however, if multiple inheritance is involved, it might not adequately satisfy
 * override (...) conditions. In those scenarios, this code should be used as a
 * starting point and then adjusted appropriately.
 */
contract OwnableDeferralResolution is Ownable, OwnableDeferral {
    modifier isOwner() override {
        _isOwner();
        _;
    }

    function _isOwner() internal view override {
        // Same as _checkOwner() but using error code instead of a require statement.
        if (owner() != _msgSender()) revert CallerIsNotOwner();
    }
}

// File: @nftculture/nftc-contracts-private/contracts/metadata/v1/CollectionMetadataManager.sol



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

// OZ Libraries
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/Base64.sol';

// Local References
import '../../access/v2/OwnableDeferral.sol';
import './TokenMetadataManager.sol';

/**
 * @title CollectionMetadataManager
 * @author @NiftyMike | @NFTCulture
 * @dev This contract builds on TokenMetadataManager to provide functionality that enables on-chain
 * storage of NFT metadata for an entire NFT collection.
 */
abstract contract CollectionMetadataManager is TokenMetadataManager, OwnableDeferral {
    using Strings for uint256;

    string private _description;
    string private _external_url;

    constructor(string memory __description, string memory __external_url) {
        _description = __description;
        _external_url = __external_url;
    }

    function _getImageFieldValue(uint256 tokenType) internal view virtual returns (string memory);

    function _getAnimationFieldValue(uint256 tokenType) internal view virtual returns (string memory);

    function _convertJsonToEncodedString(string memory metadata) internal pure returns (string memory) {
        return string.concat('data:application/json;base64,', Base64.encode(bytes(metadata)));
    }

    function _getMetadataJson(uint256 tokenId, uint256 tokenType) internal view returns (string memory) {
        return _constructMetadataAsJson(tokenId, tokenType);
    }

    function _constructMetadataAsJson(uint256 tokenId, uint256 tokenType) internal view returns (string memory) {
        DynamicAttributesV1 memory tokenAttributes = _getTokenAttributesDefinition(tokenType);

        // Token types are 1-index based.
        require(tokenAttributes.tokenType > 0, 'Invalid token type');

        string memory imageFieldValue = _getImageFieldValue(tokenType);
        string memory animationFieldValue = _getAnimationFieldValue(tokenType);

        return
            string.concat(
                '{"name":"',
                tokenAttributes.title,
                tokenAttributes.isSerialized ? tokenId.toString() : '',
                '","description":"',
                tokenAttributes.hasTokenDescription ? tokenAttributes.tokenDescription : _description,
                '","image":"',
                imageFieldValue,
                tokenAttributes.isAnimated ? '","animation_url":"' : '',
                tokenAttributes.isAnimated ? animationFieldValue : '',
                '","attributes":',
                _getNftAttributeArray(tokenAttributes),
                ',"external_url":"',
                _external_url,
                '"}'
            );
    }

    function _getNftAttributeArray(DynamicAttributesV1 memory tokenAttributes) internal pure returns (string memory) {
        string memory attributeArrayAsString = '[';

        uint256 tokenAttrIdx;
        for (tokenAttrIdx; tokenAttrIdx < tokenAttributes.attributeNames.length; tokenAttrIdx++) {
            attributeArrayAsString = string.concat(
                attributeArrayAsString,
                tokenAttrIdx == 0 ? '' : ',',
                '{"trait_type":"',
                tokenAttributes.attributeNames[tokenAttrIdx],
                '","value":"',
                tokenAttributes.attributeValues[tokenAttrIdx],
                '"}'
            );
        }

        return string.concat(attributeArrayAsString, ']');
    }

    function modifyCollectionMetadata(string calldata __description, string calldata __external_url) external isOwner {
        if (bytes(__description).length > 0) {
            _description = __description;
        }

        if (bytes(__external_url).length > 0) {
            _external_url = __external_url;
        }
    }
}

// File: @nftculture/nftc-contracts-private/contracts/metadata/v1/interfaces/IChainNativeArtProducer.sol



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

/**
 * @title IChainNativeArtProducer
 * @author @NiftyMike | @NFTCulture
 * @dev Super thin interface definition for a contract that
 * produces art in a chain native way.
 */
interface IChainNativeArtProducer {
    /**
     * Given a token type, return a string that can be directly inserted into an
     * NFT metadata attribute such as image.
     *
     * @param tokenType type of the art piece
     */
    function getArtAsString(uint256 tokenType) external view returns (string memory);

    /**
     * Given a token type, return a string that can be directly inserted into an
     * NFT metadata attribute such as animation_url.
     *
     * @param tokenType type of the art piece
     */
    function getAnimationAsString(uint256 tokenType) external view returns (string memory);
}

// File: @nftculture/nftc-contracts-private/contracts/metadata/v1/interfaces/IChainNativeMetadataProducer.sol



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

/**
 * @title IChainNativeMetadataProducer
 * @author @NiftyMike | @NFTCulture
 * @dev Super thin interface definition for a contract that
 * produces metadata in a chain native way.
 */
interface IChainNativeMetadataProducer {
    function getTokenTypeForToken(uint256 tokenId) external view returns (uint256);

    function getJsonAsString(uint256 tokenId, uint256 tokenType) external view returns (string memory);

    function getJsonAsEncodedString(uint256 tokenId, uint256 tokenType) external view returns (string memory);
}

// File: @nftculture/nftc-contracts-private/contracts/metadata/v1/interfaces/IDynamicAttributes.sol



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

/**
 * @title IDynamicAttributesV1
 * @author @NFTMike | @NFTCulture
 * @dev Interface for defining the structure of DynamicAttributes objects.
 *
 * This interface should capture all of the data relevant to a group of tokens being
 * stored entirely on-chain.
 *
 * The interface is designed to allow the metadata to be modified and updated as needed.
 *
 * Besides the 'isAnimated' attribute, the interface is designed to be decoupled from
 * the artwork scheme implemented for the related tokens. 'isAnimated' is just used
 * as a cleaner and more deliberate approach than checking string length of an animation.
 */
interface IDynamicAttributesV1 {
    struct DynamicAttributesV1 {
        uint256 tokenType;
        bool isSerialized;
        bool isAnimated;
        bool hasTokenDescription;
        string title;
        string tokenDescription;
        string[] attributeNames;
        string[] attributeValues;
    }
}

// File: @nftculture/nftc-contracts-private/contracts/metadata/v1/SimpleChainNativeArtConsumer.sol



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

// Local References
import '../../access/v2/OwnableDeferral.sol';
import './interfaces/IChainNativeArtProducer.sol';

/**
 * @title SimpleChainNativeArtConsumer
 * @author @NiftyMike | @NFTCulture
 * @dev Basic implementation to manage connections to an external source for NFT art.
 */
abstract contract SimpleChainNativeArtConsumer is OwnableDeferral {
    // External contract that manages the collection's art in a chain-native way.
    IChainNativeArtProducer private _artProducer;

    constructor(address __artProducer) {
        _setProducer(__artProducer);
    }

    /**
     * @notice Set the on-chain art producer contract.
     * Can only be called if caller is owner.
     *
     * @param __artProducer address of the producer contract.
     */
    function setProducer(address __artProducer) external isOwner {
        _setProducer(__artProducer);
    }

    function _setProducer(address __artProducer) internal {
        if (__artProducer != address(0)) {
            _artProducer = IChainNativeArtProducer(__artProducer);
        }
    }

    function _getProducer() internal view virtual returns (IChainNativeArtProducer) {
        return _artProducer;
    }
}

// File: @nftculture/nftc-contracts-private/contracts/metadata/v1/TokenMetadataManager.sol



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

// Local References
import './interfaces/IDynamicAttributes.sol';

// Error Codes
error NullTokenType();
error TokenAttributesDefinitionDoesNotExist();
error TokenTypeAlreadyCreated();
error TokenTypeCountExceeded();

/**
 * @title TokenMetadataManager
 * @author @NiftyMike | @NFTCulture
 * @dev This contract manages Non-Fungible Token Metadata fully on-chain and
 * in a generic fashion.
 *
 * All metadata is contained within a map called _tokenAttributesDefinitions.
 *
 * In its basic implementation, the TokenMetadataManager does not allow for
 * expansion of the token types. However, this could be added on by a subclass
 * of this contract.
 */
abstract contract TokenMetadataManager is IDynamicAttributesV1 {
    // Storage for Token Attribute Definitions
    mapping(uint256 => DynamicAttributesV1) private _tokenAttributesDefinitions;
    uint64[] private _tokenTypeIds;

    uint256 private immutable _maxNumberOfTypes;

    constructor(uint256 __maxNumberOfTypes) {
        _maxNumberOfTypes = __maxNumberOfTypes;

        _injectDefinitions(_getInitialDefinitions());
    }

    function _injectDefinitions(DynamicAttributesV1[] memory __tokenAttributesDefinition) internal virtual {
        uint256 idx;
        for (idx; idx < __tokenAttributesDefinition.length; ) {
            DynamicAttributesV1 memory current = __tokenAttributesDefinition[idx];
            _createTokenType(current);

            unchecked {
                ++idx;
            }
        }
    }

    function _getInitialDefinitions() internal virtual returns (DynamicAttributesV1[] memory);

    function getTokenAttributesDefinition(uint256 tokenType) external view returns (DynamicAttributesV1 memory) {
        return _getTokenAttributesDefinition(tokenType);
    }

    function _getTokenAttributesDefinition(uint256 tokenType) internal view returns (DynamicAttributesV1 memory) {
        return _tokenAttributesDefinitions[tokenType];
    }

    function getTokenTypeIds() external view returns (uint64[] memory) {
        return _getTokenTypeIds();
    }

    function _getTokenTypeIds() internal view returns (uint64[] memory) {
        return _tokenTypeIds;
    }

    function _createTokenType(DynamicAttributesV1 memory tokenAttributes) internal {
        uint256 tokenType = tokenAttributes.tokenType;

        if (tokenType == 0) revert NullTokenType();
        if (_tokenAttributesDefinitions[tokenType].tokenType > 0) revert TokenTypeAlreadyCreated();
        if (_maxNumberOfTypes > 0 && _tokenTypeIds.length + 1 > _maxNumberOfTypes) revert TokenTypeCountExceeded();

        _tokenAttributesDefinitions[tokenType] = tokenAttributes;
        _tokenTypeIds.push(uint64(tokenType));
    }

    function _updateTokenType(DynamicAttributesV1 memory tokenAttributes) internal {
        if (_tokenAttributesDefinitions[tokenAttributes.tokenType].tokenType == 0)
            revert TokenAttributesDefinitionDoesNotExist();

        _tokenAttributesDefinitions[tokenAttributes.tokenType] = tokenAttributes;
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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/Base64.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Provides a set of functions to operate with Base64 strings.
 *
 * _Available since v4.5._
 */
library Base64 {
    /**
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        /// @solidity memory-safe-assembly
        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

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

            // Run over the input, 3 bytes at a time
            for {
                let dataPtr := data
                let endPtr := add(data, mload(data))
            } lt(dataPtr, endPtr) {

            } {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 {
                mstore8(sub(resultPtr, 1), 0x3d)
            }
        }

        return result;
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 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 256, 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 << 3) < value ? 1 : 0);
        }
    }
}

// File: @openzeppelin/contracts/utils/math/SignedMath.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

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



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

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.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 `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

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

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// File: contracts/KH87M/PixelPioneerMetadata.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

// Local References
import './PixelPioneerMetadataBase.sol';

/**
 * @title PixelPioneerMetadata.
 *                            .+.
 *             -:       .:    :+.
 *    --      :=.       :+    -=                                         .     ..                     .:-:
 *    .+.    --         :+    =-   .:.                                 :++-.  .++=: ..              :==:-++==:
 *     =-  .=:          :=    +.  -=::.:.               -.        .==..+=-+=  =+:+-.=====:         -+:  =+:.-+.
 *     =-:=-       :.   ==----+  :+   =+:.-+-   ..                 ++..++++:  =++=-+:   -+:      .++=--=++=-++.
 *     -=--==-.    :.   +-::.=-  +- .=-+:=::+. -+=     .:-.        =+.  .+=   :+=.=+:   -+:       +=:::=+..-+:
 *     --    .--       .+.  .+:  ==-=: -+:  ===:.======-::+-       =+.  :+:   =+:-+-   :+=       .+=  .+--+-.
 *     .-              .+.  :+.   :.                      :+.      .-    .    .-=-.    =+.        :==-=+=:.
 *                      +:  .+                            :-                           ..            ..
 *
 *                                                On-Chain Metadata
 */
contract PixelPioneerMetadata is PixelPioneerMetadataBase {
    address private constant COMPANION_ART_CONTRACT = 0x8abC21a84992b8C50c086D5133D6B428b8FC7439; // PixelPioneerArtwork V1
    string private constant GENERIC_TOKEN_DESCRIPTION = 'Pixel Pioneer [Keith Haring Foundation](https://www.haring.com/) | [NFT Usage License](https://www.haring.com/!/nft-ownership-license)';
    string private constant TOKEN_EXTERNAL_URL = 'https://www.haring.com/';
    uint256 private constant NUMBER_OF_TOKEN_TYPES_ALLOWED = 5; // Max of 5 tokens.

    constructor()
        SimpleChainNativeArtConsumer(COMPANION_ART_CONTRACT)
        TokenMetadataManager(NUMBER_OF_TOKEN_TYPES_ALLOWED)
        CollectionMetadataManager(GENERIC_TOKEN_DESCRIPTION, TOKEN_EXTERNAL_URL)
    {
        // Implementation version: v1.0.0
    }

    /**
     *  struct DynamicAttributes {
     *     uint256 tokenType;
     *     bool isSerialized;
     *     bool isAnimated;
     *     bool hasTokenDescription;
     *     string title;
     *     string tokenDescription;
     *     string[] attributeNames;
     *     string[] attributeValues;
     *  }
     */
    function _getInitialDefinitions() internal pure override returns (DynamicAttributesV1[] memory) {
        string[] memory attributeFieldNames = new string[](4);
        attributeFieldNames[0] = 'ARTIST';
        attributeFieldNames[1] = 'LOCATION';
        attributeFieldNames[2] = 'YEAR';
        attributeFieldNames[3] = 'FILE FORMATS';

        string[] memory tokenOneValues = new string[](4);
        tokenOneValues[0] = 'Keith Haring';
        tokenOneValues[1] = 'New York City, New York';
        tokenOneValues[2] = '1987';
        tokenOneValues[3] = 'PICT, PNG, SVG';

        string[] memory tokenTwoValues = new string[](4);
        tokenOneValues[0] = 'Keith Haring';
        tokenOneValues[1] = 'New York City, New York';
        tokenOneValues[2] = '1987';
        tokenOneValues[3] = 'PICT, PNG, SVG';

        string[] memory tokenThreeValues = new string[](4);
        tokenOneValues[0] = 'Keith Haring';
        tokenOneValues[1] = 'New York City, New York';
        tokenOneValues[2] = '1987';
        tokenOneValues[3] = 'PICT, PNG, SVG';

        string[] memory tokenFourValues = new string[](4);
        tokenOneValues[0] = 'Keith Haring';
        tokenOneValues[1] = 'New York City, New York';
        tokenOneValues[2] = '1987';
        tokenOneValues[3] = 'PICT, PNG, SVG';

        string[] memory tokenFiveValues = new string[](4);
        tokenOneValues[0] = 'Keith Haring';
        tokenOneValues[1] = 'New York City, New York';
        tokenOneValues[2] = '1987';
        tokenOneValues[3] = 'PICT, PNG, SVG';

        DynamicAttributesV1[] memory initialAttributesDefinitions = new DynamicAttributesV1[](5);

        initialAttributesDefinitions[0] = DynamicAttributesV1(
            1,
            false,
            false,
            false,
            'Untitled (April 14, 1987)',
            '',
            attributeFieldNames,
            tokenOneValues
        );
        initialAttributesDefinitions[1] = DynamicAttributesV1(
            2,
            false,
            false,
            false,
            'Untitled #1 (April 16, 1987)',
            '',
            attributeFieldNames,
            tokenTwoValues
        );
        initialAttributesDefinitions[2] = DynamicAttributesV1(
            3,
            false,
            false,
            false,
            'Untitled #2 (April 16, 1987)',
            '',
            attributeFieldNames,
            tokenThreeValues
        );
        initialAttributesDefinitions[3] = DynamicAttributesV1(
            4,
            false,
            false,
            false,
            'Untitled (Feb 2, 1987)',
            '',
            attributeFieldNames,
            tokenFourValues
        );
        initialAttributesDefinitions[4] = DynamicAttributesV1(
            5,
            false,
            false,
            false,
            'Untitled (Feb 3, 1987)',
            '',
            attributeFieldNames,
            tokenFiveValues
        );

        return initialAttributesDefinitions;
    }
}

// File: contracts/KH87M/PixelPioneerMetadataBase.sol



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

// NFTC Prerelease Contracts
import '@nftculture/nftc-contracts-private/contracts/access/v2/OwnableDeferralResolution.sol';
import '@nftculture/nftc-contracts-private/contracts/metadata/v1/interfaces/IChainNativeMetadataProducer.sol';
import '@nftculture/nftc-contracts-private/contracts/metadata/v1/SimpleChainNativeArtConsumer.sol';
import '@nftculture/nftc-contracts-private/contracts/metadata/v1/CollectionMetadataManager.sol';

/**
 * @title PixelPioneerMetadataBase
 * @author @NiftyMike | @NFTCulture
 * @dev Basic On-Chain Metadata Implementation.
 */
abstract contract PixelPioneerMetadataBase is
    CollectionMetadataManager,
    SimpleChainNativeArtConsumer,
    IChainNativeMetadataProducer,
    OwnableDeferralResolution
{
    function getTokenTypeForToken(uint256 tokenId) external pure override returns (uint256) {
        return tokenId + 1; // Token types are 1-index based.
    }

    function getJsonAsString(uint256 tokenId, uint256 tokenType) external view override returns (string memory) {
        return _getMetadataJson(tokenId, tokenType);
    }

    function getJsonAsEncodedString(uint256 tokenId, uint256 tokenType) external view override returns (string memory) {
        return _convertJsonToEncodedString(_getMetadataJson(tokenId, tokenType));
    }

    function _getImageFieldValue(uint256 tokenType) internal view override returns (string memory) {
        return _getProducer().getArtAsString(tokenType);
    }

    function _getAnimationFieldValue(uint256 tokenType) internal view override returns (string memory) {
        return _getProducer().getAnimationAsString(tokenType);
    }
}