// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

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

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

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

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

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

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// File: @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/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: @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/foundation/canvas/Canvas1.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "../reserve/IReserve.sol";
import "./Encoding1.sol";
import "./SVG1.sol";

struct Image1 {
    string title;
    string credit;
    string script;
    string webUrl;
    string dataUrl;
    string imageUrl;
    string mediaUrl;
    bytes svgData;
}

contract Canvas1 is SVG1, NoteArt {
    using Strings for uint;
    using Strings for uint8;
    using Strings for uint64;

    SVG1 private _svg;
    IReserve private _reserve;
    mapping(uint => Image1) private _images;

    event Print(
        uint indexed tokenId,
        address indexed from,
        string title,
        string credit,
        string webUrl,
        string dataUrl,
        string imageUrl,
        uint timestamp
    );

    event Update(
        uint indexed tokenId,
        address indexed from,
        string title,
        string credit,
        string webUrl,
        string dataUrl,
        string imageUrl,
        uint timestamp
    );

    function reserve() external view returns (IReserve) {
        return _reserve;
    }

    function svg() external view returns (SVG1) {
        return _svg;
    }

    function getImage(uint tokenId) external view returns (Image1 memory) {
        return _images[tokenId];
    }

    function print(
        Image1 calldata image,
        NoteParams calldata note
    ) external payable returns (uint) {
        uint tokenId = _reserve.print{value: msg.value}(note);

        _images[tokenId] = image;

        emit Print(
            tokenId,
            msg.sender,
            image.title,
            image.credit,
            image.webUrl,
            image.dataUrl,
            image.imageUrl,
            block.timestamp
        );

        return tokenId;
    }

    function update(
        uint tokenId,
        Image1 calldata image
    ) external payable returns (uint) {
        _images[tokenId] = image;

        emit Update(
            tokenId,
            msg.sender,
            image.title,
            image.credit,
            image.webUrl,
            image.dataUrl,
            image.imageUrl,
            block.timestamp
        );

        return tokenId;
    }

    function tokenData(Note memory note) external view returns (string memory) {
        return string(_encodeData(note));
    }

    function tokenURI(Note memory note) external view returns (string memory) {
        return
            string(
                abi.encodePacked(
                    "data:application/json;base64,",
                    Base64.encode(_encodeData(note))
                )
            );
    }

    function tokenImage(
        Note memory note
    ) external view returns (string memory) {
        Image1 memory img = _images[note.art];
        return
            img.svgData.length > 0
                ? string(_svg.encodeSVG(img.svgData))
                : img.imageUrl;
    }

    function tokenImageURI(
        Note memory note
    ) external view returns (string memory) {
        Image1 memory img = _images[note.art];
        return
            img.svgData.length > 0
                ? string(_svg.encodeSVGURI(img.svgData))
                : img.imageUrl;
    }

    function _encodeData(
        Note memory note
    ) internal view virtual returns (bytes memory) {
        Image1 memory img = _images[note.art];
        return
            abi.encodePacked(
                '{"id":',
                note.id.toString(),
                _encodeArt1(img),
                _encodeNote1(note),
                _encodeNote2(note),
                _encodeImage1(img),
                _encodeImage2(img),
                '"}'
            );
    }

    function _encodeNote1(
        Note memory note
    ) internal view virtual returns (bytes memory) {
        return
            abi.encodePacked(
                '","art":',
                note.art.toString(),
                ',"duration":',
                note.duration.toString(),
                ',"createdAt":',
                note.createdAt.toString(),
                ',"collectedAt":',
                note.collectedAt.toString()
            );
    }

    function _encodeNote2(
        Note memory note
    ) internal view virtual returns (bytes memory) {
        uint released = _reserve.getReleased(note.id);
        uint reward = _reserve.getReward(note.id);
        NoteArt encoder = _reserve.getEncoder(note.id);

        return
            abi.encodePacked(
                ',"assigned":',
                Encoding1.encodeAddress(address(encoder)),
                ',"encoder":',
                Encoding1.encodeAddress(address(note.encoder)),
                ',"delegate":',
                Encoding1.encodeAddress(note.delegate),
                ',"payee":',
                Encoding1.encodeAddress(note.payee),
                ',"released":',
                Encoding1.encodeDecimals(released),
                ',"reward":',
                Encoding1.encodeDecimals(reward),
                ',"amount":',
                Encoding1.encodeDecimals(note.amount),
                ',"rate":',
                note.rate.toString()
            );
    }

    function _encodeImage1(
        Image1 memory img
    ) internal view virtual returns (bytes memory) {
        return
            abi.encodePacked(
                ',"image":"',
                img.svgData.length > 0
                    ? string(_svg.encodeSVGURI(img.svgData))
                    : img.imageUrl
            );
    }

    function _encodeImage2(
        Image1 memory img
    ) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                '","webUrl":"',
                img.webUrl,
                '","dataUrl":"',
                img.dataUrl,
                '","imageUrl":"',
                img.imageUrl,
                '","mediaUrl":"',
                img.mediaUrl,
                '","external_url":"',
                img.webUrl,
                '","animation_url":"',
                img.mediaUrl
            );
    }

    function _encodeArt1(
        Image1 memory img
    ) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                ',"title":"',
                img.title,
                '","credit":"',
                img.credit,
                '","script":"',
                img.script,
                '","description":"',
                img.script
            );
    }

    constructor(IReserve reserve_) {
        _reserve = reserve_;
        _svg = new SVG1();
    }
}

// File: contracts/foundation/canvas/Encoding1.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";

library Encoding1 {
    using Strings for uint;

    function encodeDecimals(uint num) internal pure returns (bytes memory) {
        bytes memory decimals = bytes((num % 1e18).toString());
        uint length = decimals.length;

        for (uint i = length; i < 18; i += 1) {
            decimals = abi.encodePacked("0", decimals);
        }

        return abi.encodePacked((num / 1e18).toString(), ".", decimals);
    }

    function encodeAddress(address addr) internal pure returns (bytes memory) {
        if (addr == address(0)) return "null";
        return abi.encodePacked('"', uint(uint160(addr)).toHexString(), '"');
    }
}

// File: contracts/foundation/canvas/SVG1.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "./Encoding1.sol";

contract SVG1 {
    using Strings for uint;
    using Strings for uint8;
    using Strings for uint16;
    using Strings for uint64;

    function encodeSVG(bytes calldata svg) public pure returns (string memory) {
        return string(_encodeSVG(svg));
    }

    function encodeSVGURI(
        bytes calldata svg
    ) public pure virtual returns (string memory) {
        return
            string(
                abi.encodePacked(
                    "data:image/svg+xml;base64,",
                    Base64.encode(_encodeSVG(svg))
                )
            );
    }

    function _encodeSVG(bytes calldata svg) public pure returns (bytes memory) {
        return
            abi.encodePacked(
                '<svg width="512" height="512" viewBox="0 0 255 255" xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges">',
                string(_encodeSVGShapes(svg)),
                "</svg>"
            );
    }

    function _encodeRectangle(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                '<rect width="',
                uint8(svg[0]).toString(),
                '" height="',
                uint8(svg[1]).toString(),
                '" x="',
                uint8(svg[2]).toString(),
                '" y="',
                uint8(svg[3]).toString()
            );
    }

    function _encodeEllipse(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                '<ellipse cx="',
                uint8(svg[0]).toString(),
                '" cy="',
                uint8(svg[1]).toString(),
                '" rx="',
                uint8(svg[2]).toString(),
                '" ry="',
                uint8(svg[3]).toString()
            );
    }

    function _encodeLine(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                '<line x1="',
                uint8(svg[0]).toString(),
                '" y1="',
                uint8(svg[1]).toString(),
                '" x2="',
                uint8(svg[2]).toString(),
                '" y2="',
                uint8(svg[3]).toString()
            );
    }

    function _encodeRotate(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                '" transform="rotate(',
                uint16(bytes2(svg[0:2])).toString(),
                ", ",
                uint8(svg[2]).toString(),
                ", ",
                uint8(svg[3]).toString(),
                ")"
            );
    }

    function _encodeStroke(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        return
            abi.encodePacked(
                '" stroke="',
                _encodeColor(svg),
                '" stroke-linecap="round" stroke-width="',
                uint8(svg[4]).toString()
            );
    }

    function _encodeFill(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        return abi.encodePacked('" fill="', _encodeColor(svg));
    }

    function _encodeColor(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        uint8 alpha = uint8(svg[3]);
        bytes memory channel;

        if (alpha >= 100) channel = "1";
        else channel = abi.encodePacked("0.", alpha.toString());

        return
            abi.encodePacked(
                "rgba(",
                uint8(svg[0]).toString(),
                ",",
                uint8(svg[1]).toString(),
                ",",
                uint8(svg[2]).toString(),
                ",",
                channel,
                ")"
            );
    }

    function _encodeSVGShapes(
        bytes calldata svg
    ) internal pure returns (bytes memory) {
        bytes memory out;

        uint8 code = uint8(svg[0]);
        uint8 shape = code / 8;
        uint8 mode = code % 8;

        if (shape == 0) {
            out = _encodeEllipse(svg[1:]);
        }
        if (shape == 1) {
            out = _encodeRectangle(svg[1:]);
        }
        if (shape == 2) {
            out = _encodeLine(svg[1:]);
        }

        uint256 next = 5;

        if (mode < 4) {
            out = abi.encodePacked(out, _encodeFill(svg[next:]));
            next += 4;

            if (mode % 2 == 1) {
                out = abi.encodePacked(out, _encodeStroke(svg[next:]));
                next += 5;
            }

            if (mode > 1) {
                out = abi.encodePacked(out, _encodeRotate(svg[next:]));
                next += 4;
            }
        } else {
            out = abi.encodePacked(out, _encodeStroke(svg[next:]));
            next += 5;

            if (mode == 5) {
                out = abi.encodePacked(out, _encodeRotate(svg[next:]));
                next += 4;
            }
        }

        out = abi.encodePacked(out, '"/>');

        if (svg.length > next) {
            return abi.encodePacked(out, _encodeSVGShapes(svg[next:]));
        }

        return out;
    }
}

// File: contracts/foundation/reserve/ICash.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

struct CashConfig {
    string name;
    string symbol;
    address delegate;
}

interface ICash is IERC20 {
    event Mint(
        address indexed from,
        address indexed to,
        uint256 amount,
        uint256 value,
        uint256 timestamp
    );

    event Burn(
        address indexed from,
        address indexed to,
        uint256 amount,
        uint256 value,
        uint256 timestamp
    );

    event Inflate(
        address indexed from,
        address indexed to,
        uint256 amount,
        uint256 timestamp
    );

    event Deflate(address indexed from, uint256 amount, uint256 timestamp);

    event Configure(
        address indexed from,
        string name,
        string indexed symbol,
        address indexed delegate,
        uint256 timestamp
    );

    event Collect(
        address indexed from,
        address indexed to,
        uint256 amount,
        uint256 timestamp
    );

    function found() external view returns (uint256);

    function reserve() external view returns (address);

    function config() external view returns (CashConfig memory);

    function rate(uint256 cash) external view returns (uint256);

    function mint(address to) external payable returns (uint256);

    function burn(address to, uint256 amount) external;

    function inflate(address to, uint256 amount) external;

    function deflate(uint256 amount) external;

    function collect(address to, uint256 amount) external;

    function configure(CashConfig calldata config) external;
}

// File: contracts/foundation/reserve/IReserve.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./ICash.sol";

struct ReserveConfig {
    string name;
    string symbol;
    address reserve;
    uint32 maxDuration;
    uint32 maxCollection;
    uint32 minCollection;
    uint16 timeDilation;
    uint16 commission;
    uint16 bonus;
}

struct Note {
    NoteArt encoder;
    uint256 id;
    uint256 art;
    uint256 rate;
    uint256 amount;
    uint256 duration;
    uint256 createdAt;
    uint256 collectedAt;
    address delegate;
    address payee;
}

struct NoteParams {
    NoteArt encoder;
    address from;
    address to;
    address delegate;
    address payee;
    uint256 amount;
    uint256 duration;
    uint256 target;
}

struct SecureParams {
    uint256 id;
    address delegate;
    address payee;
    NoteArt encoder;
}

struct RollParams {
    uint256 id;
    address noteTo;
    address interestTo;
    address delegate;
    address payee;
    uint256 target;
    NoteArt encoder;
}

struct CollectParams {
    uint256 id;
    address interestTo;
    address principalTo;
}

struct WithdrawParams {
    uint256 id;
    uint256 limit;
    address to;
}

interface IArt {
    function tokenURI(uint256 tokenId) external view returns (string memory);

    function tokenData(uint256 tokenId) external view returns (string memory);

    function tokenImage(uint256 tokenId) external view returns (string memory);

    function tokenImageURI(
        uint256 tokenId
    ) external view returns (string memory);
}

interface NoteArt {
    function tokenURI(Note memory note) external view returns (string memory);

    function tokenData(Note memory note) external view returns (string memory);

    function tokenImage(Note memory note) external view returns (string memory);

    function tokenImageURI(
        Note memory note
    ) external view returns (string memory);
}

interface IReserve is IArt, IERC721 {
    event Stake(
        uint256 indexed tokenId,
        address indexed from,
        address indexed to,
        uint256 artId,
        uint256 rate,
        uint256 amount,
        uint256 value,
        uint256 duration,
        address payee,
        address delegate,
        NoteArt encoder,
        uint256 timestamp
    );

    event Secure(
        uint256 indexed tokenId,
        address indexed from,
        NoteArt indexed encoder,
        address delegate,
        address payee,
        uint256 timestamp
    );

    event Withdraw(
        uint256 indexed tokenId,
        address indexed from,
        address indexed to,
        uint256 interest,
        uint256 released,
        uint256 timestamp
    );

    event Collect(
        uint256 indexed tokenId,
        address indexed from,
        address indexed principalTo,
        address interestTo,
        uint256 amount,
        uint256 released,
        uint256 interest,
        uint256 penalty,
        uint256 captured,
        uint256 timestamp
    );

    event Rollover(
        uint256 indexed tokenId,
        uint256 indexed newTokenId,
        address indexed from,
        address noteTo,
        address interestTo,
        uint256 principal,
        uint256 interest,
        uint256 penalty,
        uint256 captured,
        uint256 timestamp
    );

    event Capture(
        uint256 indexed tokenId,
        address indexed from,
        uint256 penalty,
        uint256 captured,
        uint256 timestamp
    );

    event Assign(
        address indexed from,
        uint256 indexed tokenId,
        NoteArt indexed encoder,
        uint256 timestamp
    );

    event Configure(
        address indexed from,
        string name,
        string symbol,
        address reserve,
        uint32 maxDuration,
        uint32 maxCollection,
        uint32 minCollection,
        uint16 timeDilation,
        uint16 commission,
        uint16 bonus,
        uint256 timestamp
    );

    function cash() external view returns (ICash);

    function config() external view returns (ReserveConfig memory);

    function pause() external;

    function unpause() external;

    function configure(ReserveConfig calldata config_) external;

    function tokenCount() external view returns (uint256);

    function tokenImage(uint256 tokenId) external view returns (string memory);

    function tokenImageURI(
        uint256 tokenId
    ) external view returns (string memory);

    function tokenData(uint256 tokenId) external view returns (string memory);

    function getNote(uint256 tokenId) external view returns (Note memory);

    function getEncoder(uint256 tokenId) external view returns (NoteArt);

    function getReward(uint256 tokenId) external view returns (uint256);

    function getReleased(uint256 tokenId) external view returns (uint256);

    function getCaptured(uint256 tokenId) external view returns (uint256);

    function interestRate() external view returns (uint256);

    function print(NoteParams calldata note) external payable returns (uint256);

    function stake(
        uint256 artId,
        NoteParams calldata note
    ) external payable returns (uint256);

    function secure(SecureParams calldata params) external;

    function assign(uint256[] calldata tokenIds, NoteArt encoder) external;

    function withdraw(
        WithdrawParams calldata params
    ) external returns (uint256);

    function collect(CollectParams calldata params) external;

    function rollover(RollParams calldata params) external returns (uint256);

    function capture(uint256 tokenId) external returns (uint256);

    function captureMany(uint256[] memory tokenIds) external returns (uint256);

    function calculateInterest(
        uint256 rate,
        uint256 amount,
        uint256 duration,
        uint256 time
    ) external view returns (uint256);

    function calculatePenalty(
        uint256 amount,
        uint256 duration,
        uint256 time
    ) external view returns (uint256);

    function calculateValue(
        uint256 rate,
        uint256 amount,
        uint256 duration,
        uint256 time
    ) external view returns (uint256 interest, uint256 penalty);

    function calculateCollectionWindow(
        uint256 duration
    ) external view returns (uint256);

    function calculateMaximumInterest(
        uint256 rate,
        uint256 amount,
        uint256 duration,
        uint256 time
    ) external view returns (uint256);

    function calculateEarlyInterest(
        uint256 rate,
        uint256 amount,
        uint256 duration,
        uint256 time
    ) external view returns (uint256);

    function calculateLateInterest(
        uint256 rate,
        uint256 amount,
        uint256 duration,
        uint256 remaining
    ) external view returns (uint256);

    function calculateEarlyPenalty(
        uint256 amount,
        uint256 duration,
        uint256 time
    ) external pure returns (uint256);

    function calculateLatePenalty(
        uint256 amount,
        uint256 duration,
        uint256 late
    ) external view returns (uint256);
}