Skip to content
Verified contractExactMIT

NoroshiRenderer

Address0x4609bfdbd7c9531eddb1329a6fe0e283d2b1f676
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,477,731
Creation transaction
0xa32073d001…1c225a81e3

NoroshiRenderer.sol

// Sources flattened with hardhat v2.29.2 https://hardhat.org

// SPDX-License-Identifier: MIT

// File openzeppelin-contracts/utils/[email protected]

// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.6) (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, 0x20)
            let dataPtr := data
            let endPtr := add(data, mload(data))

            // In some cases, the last iteration will read bytes after the end of the data. We cache the value, and
            // set it to zero to make sure no dirty bytes are read in that section.
            let afterPtr := add(endPtr, 0x20)
            let afterCache := mload(afterPtr)
            mstore(afterPtr, 0x00)

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

            } lt(dataPtr, endPtr) {

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

                // To write each character, shift the 3 byte (24 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F to bitmask the least significant 6 bits.
                // Use this as an index into the lookup table, mload an entire word
                // so the desired character is in the least significant byte, and
                // mstore8 this least significant byte into the result and continue.

                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
            }

            // Reset the value that was cached
            mstore(afterPtr, afterCache)

            // 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/math/[email protected]

// Original license: 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/[email protected]

// Original license: 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/[email protected]

// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;


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

// Original license: SPDX_License_Identifier: MIT
pragma solidity 0.8.38;

/*
 *
 *     _   _     ___     ____      ___     ____     _   _    ___
 *    | \ | |   / _ \   |  _ \    / _ \   / ___|   | | | |  |_ _|
 *    |  \| |  | | | |  | |_) |  | | | |  \___ \   | |_| |   | |
 *    | |\  |  | |_| |  |  _ <   | |_| |   ___) |  |  _  |   | |
 *    |_| \_|   \___/   |_| \_\   \___/   |____/   |_| |_|  |___|
 *
 *                      signal fires on ethereum
 *
 */


interface INoroshi {
    function geneOf(uint256 tokenId) external view returns (uint128);

    function revealed() external view returns (bool);
}

interface INoroshiArt {
    function read(bytes32 key) external view returns (bytes memory);
}

interface INoroshiMarkets {
    function live(uint256 market) external view returns (bool, int256, uint256, uint8);

    function scarCount(uint256 market) external view returns (uint256);

    function scarsOf(uint256 market) external view returns (uint256[7] memory);
}

contract NoroshiRenderer {
    using Strings for uint256;

    INoroshi public immutable noroshi;
    INoroshiArt public immutable art;
    INoroshiMarkets public immutable markets;

    // Keys in the art store. The print and the tail of the page are kept in base64 twice over,
    // cut on boundaries where base64 can be joined, so only the few bytes that change are encoded here.
    bytes32 private constant _PAGE_HEAD = keccak256("page.head");
    bytes32 private constant _PAGE_TAIL = keccak256("page.tail");
    bytes32 private constant _PRINT = keccak256("print");

    // Gene layout, one byte per trait.
    uint256 private constant _MARKET = 0;
    uint256 private constant _RANK = 1;
    uint256 private constant _LACQUER = 2;
    uint256 private constant _LACING = 3;
    uint256 private constant _TEETH = 4;
    uint256 private constant _MOUSTACHE = 5;
    uint256 private constant _TUFT = 6;
    uint256 private constant _CREST = 7;
    uint256 private constant _PLACE = 8;
    uint256 private constant _MON = 9;
    uint256 private constant _ALLY = 10;
    uint256 private constant _BANNERS = 11;
    uint256 private constant _LEGEND = 12;

    uint256 private constant _NO_TEETH = 3;

    // Colours, three bytes each. Lacquer: light, mid, dark per finish. Armour: light, dark per finish.
    bytes private constant _LACQUERS =
        hex"5a211b1a14130a0808d8402aa81f185a0f0c8a5a3c5c38262c1a123a302c151211080707"
        hex"e6e8eca9adb55c6068f6d98acf9f3f7c5a1c34303c1210140605082a4fc0122a80081240"
        hex"6fbfa62f7a683a3018";
    bytes private constant _ARMOURS =
        hex"2a2422100d0c8a1a14400b095c38262616102a2422100d0c8a8e96404348a87e2a4a3610"
        hex"24202c0c0a1016287a080e303c6456182c26";
    bytes private constant _FINISHES = hex"020001030405";
    bytes private constant _LACES = hex"a3121c1f2f8a6a236a3f6a2cd8d2c4c9962e141312";
    bytes private constant _TEETH_COLOURS = hex"c9ccd2efe6cfd9ae4a0000002a2422f4f0f6";
    bytes private constant _HAIRS = hex"1613127d7a76e2ddd48a2a14";
    bytes private constant _CLOTHS = hex"a81a14151312e4dccb1c2a80c98a1e";
    bytes private constant _INKS = hex"f2e7d2f2e7d2151312f2e7d2151312";
    bytes private constant _SKIES = hex"2a1208d9701e1a0a08b8321a0b1230c8742a2a30389aa3ad";
    // Sun and eyes per mood: asleep, furious, charged, calm, tense, broken.
    bytes private constant _MOODS =
        hex"cfd8e63a4a6affd27affe08affc864ffb84af0a848f09a3ad8703ae0602a9a1a14ff3a2a";

    constructor(address noroshi_, address art_, address markets_) {
        noroshi = INoroshi(noroshi_);
        art = INoroshiArt(art_);
        markets = INoroshiMarkets(markets_);
    }

    function tokenURI(uint256 tokenId) external view returns (string memory) {
        string memory id = tokenId.toString();
        if (!noroshi.revealed()) {
            bytes memory opening = _join(
                abi.encodePacked(
                    '{"name":"Noroshi #', id,
                    '","description":"A sealed signal fire. The warrior inside is drawn when the whole clan is revealed.",',
                    '"attributes":[{"trait_type":"State","value":"Sealed"}],'
                ),
                '"image":"data:image/svg+xml;base64,'
            );
            return string(
                abi.encodePacked(
                    "data:application/json;base64,",
                    Base64.encode(opening),
                    art.read(_PRINT),
                    Base64.encode(
                        abi.encodePacked(
                            Base64.encode(
                                '</defs><rect width="1000" height="1000" fill="#0f0b09"/><circle cx="500" cy="480" r="270" fill="#b3241a"/>'
                                '<use xlink:href="#kj" transform="translate(396 272) scale(2)" fill="#f2e7d2"/><use xlink:href="#fr"/></svg>'
                            ),
                            '"}'
                        )
                    )
                )
            );
        }

        uint8[16] memory g = _genes(tokenId);
        (bool ok, int256 bps,,) = markets.live(g[_MARKET]);
        uint256 scars = markets.scarCount(g[_MARKET]);

        bytes memory head = abi.encodePacked(
            '{"name":"Noroshi #', id,
            '","description":"A living samurai mask on Ethereum. Its mood follows the last 24 hours of ',
            _pick("Bitcoin|Ether|Solana|BNB|Chainlink|Zcash", g[_MARKET]),
            ', and every fall of 8% or more leaves a scar mended in gold. Image, page and data are generated onchain.",'
        );
        head = _join(
            abi.encodePacked(head, '"attributes":[', _attributes(g, scars), "],"),
            '"image":"data:image/svg+xml;base64,'
        );
        bytes memory middle = _join(
            abi.encodePacked(Base64.encode(_drawing(g, id, ok, bps, scars)), '",'),
            abi.encodePacked('"animation_url":"data:text/html;base64,', Base64.encode(_opening(tokenId, ok, bps, g[_MARKET])))
        );

        return string(
            abi.encodePacked(
                "data:application/json;base64,",
                Base64.encode(head),
                art.read(_PRINT),
                Base64.encode(middle),
                art.read(_PAGE_TAIL),
                Base64.encode('"}')
            )
        );
    }

    // What the page asks for while it is open: market state and the latest scars.
    function stateOf(uint256 tokenId)
        external
        view
        returns (bool ok, int256 bps, uint256 price, uint256[7] memory scars)
    {
        uint256 market = uint8(noroshi.geneOf(tokenId) >> 120);
        (ok, bps, price,) = markets.live(market);
        scars = markets.scarsOf(market);
    }

    // Two pieces with spaces in between, so the whole is a multiple of three bytes.
    function _join(bytes memory left, bytes memory right) private pure returns (bytes memory) {
        uint256 rest = (left.length + right.length) % 3;
        return abi.encodePacked(left, rest == 0 ? "" : rest == 1 ? "  " : " ", right);
    }

    function _genes(uint256 tokenId) private view returns (uint8[16] memory g) {
        uint128 gene = noroshi.geneOf(tokenId);
        for (uint256 i; i < 16; ++i) {
            g[i] = uint8(gene >> (8 * (15 - i)));
        }
    }

    // ---------------------------------------------------------------- page

    // The start of the page: its head and the data of this warrior.
    function _opening(uint256 tokenId, bool ok, int256 bps, uint256 market) private view returns (bytes memory) {
        bytes memory opening = abi.encodePacked(
            art.read(_PAGE_HEAD),
            '{"id":', tokenId.toString(),
            ',"gene":"', uint256(noroshi.geneOf(tokenId)).toHexString(16),
            '","r":"', uint256(uint160(address(this))).toHexString(20)
        );
        return _join(
            abi.encodePacked(opening, '","ok":', ok ? "1" : "0", ',"bps":', _signed(bps), ',"scars":[', _scarList(market), "]}"),
            ""
        );
    }

    // [[-drop, timestamp], ...] as the page reads it.
    function _scarList(uint256 market) private view returns (bytes memory list) {
        uint256[7] memory scars = markets.scarsOf(market);
        for (uint256 i; i < 7; ++i) {
            if (scars[i] == 0) continue;
            list = abi.encodePacked(list, list.length == 0 ? "" : ",", "[-", (scars[i] & 0xffffffff).toString());
            list = abi.encodePacked(list, ",", (scars[i] >> 32).toString(), "]");
        }
    }

    // ---------------------------------------------------------------- print

    // Everything in the print that depends on the warrior; the shapes it uses are stored.
    function _drawing(uint8[16] memory g, string memory id, bool ok, int256 bps, uint256 scars)
        private
        pure
        returns (bytes memory drawing)
    {
        uint256 finish = _finish(g);
        uint256 mood = _mood(ok, bps);
        drawing = abi.encodePacked(
            _paints(g, finish, mood), _mon("m", g[_MON]), _mon("n", g[_ALLY]), "</defs>", _parts(g, finish, mood, scars)
        );
        drawing = abi.encodePacked(
            drawing,
            '<text x="52" y="948" font-family="Georgia,serif" font-size="30" letter-spacing="5" fill="#f2e7d2" fill-opacity=".85">',
            _pick("BTC|ETH|SOL|BNB|LINK|ZEC", g[_MARKET]), " #", id, "</text></svg>"
        );
    }

    function _finish(uint8[16] memory g) private pure returns (uint256) {
        if (g[_LEGEND] != 0) return 5 + g[_LEGEND];
        return uint8(_FINISHES[g[_LACQUER]]);
    }

    function _mood(bool ok, int256 bps) private pure returns (uint256) {
        if (!ok) return 0;
        if (bps >= 800) return 1;
        if (bps >= 300) return 2;
        if (bps > -300) return 3;
        if (bps > -800) return 4;
        return 5;
    }

    function _paints(uint8[16] memory g, uint256 finish, uint256 mood) private pure returns (bytes memory) {
        (uint256 first, uint256 second) = _cloths(g[_BANNERS]);

        bytes memory out = abi.encodePacked(
            '<linearGradient id="L" x2="0" y2="1"><stop stop-color="#', _rgb(_LACQUERS, finish * 9),
            '"/><stop offset=".45" stop-color="#', _rgb(_LACQUERS, finish * 9 + 3),
            '"/><stop offset="1" stop-color="#', _rgb(_LACQUERS, finish * 9 + 6),
            '"/></linearGradient><linearGradient id="A" x2="0" y2="1"><stop stop-color="#', _rgb(_ARMOURS, finish * 6),
            '"/><stop offset="1" stop-color="#', _rgb(_ARMOURS, finish * 6 + 3)
        );
        out = abi.encodePacked(
            out,
            '"/></linearGradient><linearGradient id="k" x2="0" y2="1"><stop stop-color="#', _rgb(_SKIES, uint256(g[_PLACE]) * 6),
            '"/><stop offset=".6" stop-color="#', _rgb(_SKIES, uint256(g[_PLACE]) * 6 + 3),
            '"/></linearGradient>'
        );
        out = abi.encodePacked(
            out,
            _solid("l", _LACES, uint256(g[_LACING]) * 3),
            _solid("t", _TEETH_COLOURS, uint256(g[_TEETH]) * 3),
            _solid("h", _HAIRS, uint256(g[_MOUSTACHE]) * 3),
            _solid("s", _MOODS, mood * 6),
            _solid("e", _MOODS, mood * 6 + 3)
        );
        return abi.encodePacked(
            out,
            _solid("p", _CLOTHS, first * 3),
            _solid("q", _CLOTHS, second * 3),
            _solid("i", _INKS, first * 3),
            _solid("j", _INKS, second * 3)
        );
    }

    function _solid(string memory id, bytes memory table, uint256 offset) private pure returns (bytes memory) {
        return abi.encodePacked(
            '<linearGradient id="', id, '"><stop stop-color="#', _rgb(table, offset), '"/></linearGradient>'
        );
    }

    // A family crest: petals or rays around a heart, sometimes haloed, sometimes ringed.
    function _mon(string memory id, uint256 index) private pure returns (bytes memory out) {
        (uint256 count, bool rays, bool ring, bool open) = _monShape(index);
        string memory piece = string.concat(rays ? "r" : open ? "q" : "p", count.toString());

        out = abi.encodePacked('<g id="', id, '">');
        for (uint256 i; i < count; ++i) {
            out = abi.encodePacked(
                out, '<use xlink:href="#', piece, '" transform="rotate(', ((360 * i) / count).toString(), ')"/>'
            );
        }
        out = abi.encodePacked(
            out, '<circle r="15"/>', open ? _use("ri") : "", ring ? _use("ro") : "", "</g>"
        );
    }

    function _monShape(uint256 index) private pure returns (uint256 count, bool rays, bool ring, bool open) {
        uint256 variant;
        if (index < 8) {
            count = 3 + index / 4;
            variant = index % 4;
        } else {
            count = 5 + (index - 8) / 8;
            variant = (index - 8) % 8;
            rays = variant >= 4;
            variant %= 4;
        }
        ring = variant >= 2;
        open = variant % 2 == 1;
    }

    function _parts(uint8[16] memory g, uint256 finish, uint256 mood, uint256 scars)
        private
        pure
        returns (bytes memory out)
    {
        out = abi.encodePacked(
            _use(string.concat("b", uint256(g[_PLACE]).toString())), _use("su"), _use("bn"), _use("bo"), _use("he")
        );
        out = abi.encodePacked(out, _use(string.concat("c", uint256(g[_CREST]).toString())), _use("la"), _use("ma"));
        // Red shu and russet iron are plain; gold leaf shares the seams of silver, ruri the gold dust.
        if (finish != 1 && finish != 2) {
            uint256 overlay = finish == 5 ? 4 : finish == 7 ? 3 : finish;
            out = abi.encodePacked(out, _use(string.concat("o", overlay.toString())));
        }
        out = abi.encodePacked(
            out, _use("mo"), g[_TEETH] == _NO_TEETH ? "" : _use("te"), _use("mu"), g[_TUFT] == 0 ? "" : _use("tu")
        );
        if (scars > 7) scars = 7;
        for (uint256 i; i < scars; ++i) {
            out = abi.encodePacked(out, _use(string.concat("x", i.toString())));
        }
        out = abi.encodePacked(out, mood == 0 ? "" : _use("ey"), _use("fr"));
    }

    function _use(string memory id) private pure returns (string memory) {
        return string.concat('<use xlink:href="#', id, '"/>');
    }

    // ---------------------------------------------------------------- traits

    function _attributes(uint8[16] memory g, uint256 scars) private pure returns (bytes memory out) {
        out = abi.encodePacked(
            _trait("Market", _pick("Bitcoin|Ether|Solana|BNB|Chainlink|Zcash", g[_MARKET])),
            _trait("Rank", _pick("Ashigaru|Samurai|Hatamoto|Daimyo|Shogun|Legend", g[_RANK])),
            _trait("Lacquer", _lacquerName(g))
        );
        out = abi.encodePacked(
            out,
            _trait("Lacing", _pick("Crimson|Indigo|Purple|Moss green|White|Gold|Black", g[_LACING])),
            _trait("Teeth", _pick("Silver|Ivory|Gold|None|Black|Pearl", g[_TEETH])),
            _trait("Moustache", _pick("Black|Grey|White|Red", g[_MOUSTACHE]))
        );
        out = abi.encodePacked(
            out,
            _trait("Chin tuft", g[_TUFT] == 0 ? "No" : "Yes"),
            _trait("Crest", _pick("Golden horns|Crescent moon|Sun disc|Antlers|Flame", g[_CREST])),
            _trait("Place", _pick("Hills at sunset|A castle under siege|A battle at sea|Snow", g[_PLACE]))
        );
        out = abi.encodePacked(
            out,
            _trait("Clan mon", _monName(g[_MON])),
            _trait("Allied mon", _monName(g[_ALLY])),
            _trait("Banners", _bannerName(g[_BANNERS])),
            '{"trait_type":"Scars","value":', scars.toString(), "}"
        );
    }

    function _lacquerName(uint8[16] memory g) private pure returns (string memory) {
        if (g[_LEGEND] != 0) {
            return _pick("Raden (one of one)|Ruri (one of one)|Seido (one of one)", g[_LEGEND] - 1);
        }
        return _pick(
            "Russet iron|Black worn to red|Red shu|Black with gold flakes|Silver leaf|Gold leaf", g[_LACQUER]
        );
    }

    function _bannerName(uint256 index) private pure returns (string memory) {
        (uint256 first, uint256 second) = _cloths(index);
        string memory cloths = "Red|Black|White|Indigo|Ochre";
        return string.concat(_pick(cloths, first), " and ", _pick(cloths, second));
    }

    // Two different cloths out of five, in order.
    function _cloths(uint256 index) private pure returns (uint256 first, uint256 second) {
        first = index / 4;
        second = index % 4;
        if (second >= first) ++second;
    }

    function _trait(string memory name, string memory value) private pure returns (bytes memory) {
        return abi.encodePacked('{"trait_type":"', name, '","value":"', value, '"},');
    }

    function _monName(uint256 index) private pure returns (string memory) {
        (uint256 count, bool rays, bool ring, bool open) = _monShape(index);
        return string.concat(
            _pick("Three|Four|Five|Six|Seven|Eight", count - 3),
            rays ? (open ? " haloed rays" : " rays") : (open ? " open petals" : " petals"),
            ring ? " in a ring" : ""
        );
    }

    // ---------------------------------------------------------------- text

    // The `index`-th entry of a list separated by "|".
    function _pick(string memory list, uint256 index) private pure returns (string memory) {
        bytes memory source = bytes(list);
        uint256 start;
        uint256 end = source.length;
        uint256 seen;
        for (uint256 i; i < source.length; ++i) {
            if (source[i] != "|") continue;
            if (seen == index) {
                end = i;
                break;
            }
            ++seen;
            start = i + 1;
        }

        bytes memory out = new bytes(end - start);
        for (uint256 i; i < out.length; ++i) {
            out[i] = source[start + i];
        }
        return string(out);
    }

    function _rgb(bytes memory table, uint256 offset) private pure returns (bytes memory out) {
        bytes16 digits = "0123456789abcdef";
        out = new bytes(6);
        for (uint256 i; i < 3; ++i) {
            uint8 value = uint8(table[offset + i]);
            out[2 * i] = digits[value >> 4];
            out[2 * i + 1] = digits[value & 15];
        }
    }

    function _signed(int256 value) private pure returns (string memory) {
        return value < 0 ? string.concat("-", uint256(-value).toString()) : uint256(value).toString();
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.