ETH Price: $3,157.88 (+2.84%)
 

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Sponsored

Transaction Hash
Method
Block
From
To
Value

There are no matching entries

Please try again later

Latest 1 internal transaction

Parent Transaction Hash Block From To Value
155377782024-06-08 16:41:4334 days ago1717864903  Contract Creation0 ETH

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
HiraethTokenURIV1Component

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
No with 200 runs

Other Settings:
paris EvmVersion
File 1 of 31 : HiraethTokenURIComponentV1.sol.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;
import '@protocol/core/contracts/interfaces/IComponent.sol';
import '@protocol/core/contracts/libraries/bytes/BytesUtils.sol';
import '@protocol/core/contracts/libraries/sstore2/SSTORE2Map.sol';
import '@protocol/core/contracts/utils/OnchainMetadataUtils.sol';
import '@protocol/core/contracts/libraries/bytes/DynamicBuffer.sol';

import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import '@openzeppelin/contracts/utils/Strings.sol';

import './HiraethTokenURIUtils.sol';
import '../nft/Hiraeth.sol';

contract HiraethTokenURIV1Component is IComponent, ERC165 {

  string public externalUrlRoot;
  string public imageUrlRoot;

  HiraethTokenURIUtils public utils;

  constructor(address utils_, string memory externalUrlRoot_, string memory imageUrlRoot_) {
    utils = HiraethTokenURIUtils(utils_);
    externalUrlRoot = externalUrlRoot_;
    imageUrlRoot = imageUrlRoot_;
  }

  function supportsInterface(
    bytes4 interfaceId
  ) public view virtual override(ERC165, IERC165) returns (bool) {
    return
      interfaceId == type(IComponent).interfaceId ||
      super.supportsInterface(interfaceId);
  }

  function render(
    bytes calldata props
  ) public view override returns (bytes memory) {
    (
      address hiraeth,
      uint tokenId,
      bytes32 txnHash,
      address minter
    ) = utils.getParametersFromProps(props);

    uint epoch = Hiraeth(hiraeth).getEpoch(tokenId);

    string memory txnHashStr = Strings.toHexString(uint(txnHash));

    OnchainMetadataUtils.NftAttribute[]
      memory attributes = new OnchainMetadataUtils.NftAttribute[](2);
    attributes[0].traitType = 'Txn%20Hash';
    attributes[0].value = bytes(txnHashStr);
    attributes[0].isValueStringWrapped = true;

    attributes[1].traitType = 'Minter';
    attributes[1].value = bytes(Strings.toHexString(uint(uint160(bytes20(minter)))));
    attributes[1].isValueStringWrapped = true;

    return (
      abi.encodePacked(
        'data:application/json,',
        '%7B%22name%22%3A%22', // {"name":"
        utils.getDefaultName(txnHash),
         '%22%2C%20%22attributes%22%3A%5B', // ", "attributes":[
        OnchainMetadataUtils.getUrlSafeNftAttributes(attributes),
         '%5D%2C%20%22external_url%22%3A%22', // ], "external_url":"
         externalUrlRoot,
         txnHashStr,
         '%22%2C%20' // ",
       '%22image%22%3A%22', //"image":"
        imageUrlRoot,
         txnHashStr,
        '/image?resolution=4&asEpoch=',
        Strings.toString(epoch),
        '%22%2C%20%22description%22%3A%22', // ", "description":"
        utils.getDefaultDescription(txnHash),
        // '%22%2C%20%22animation_url%22%3A%22', // ", "animation_url":"
        // animationUrl,
        '%22%7D' // "}
      )
    );
  }

}

File 2 of 31 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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 3 of 31 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

import {IERC721} from "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

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

File 4 of 31 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../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 address zero.
     *
     * 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 5 of 31 : Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.2) (utils/Base64.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to operate with Base64 strings.
 */
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 6 of 31 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

File 7 of 31 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 8 of 31 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @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 9 of 31 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @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 towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (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 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                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.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 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.

            uint256 twos = denominator & (0 - denominator);
            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 (unsignedRoundsUp(rounding) && 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
     * towards zero.
     *
     * 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

File 10 of 31 : SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

/**
 * @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 11 of 31 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @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), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(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) {
        uint256 localValue = value;
        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] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        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 bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

File 12 of 31 : IComponent.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

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

interface IComponent is IERC165 {
  function render(bytes calldata props) external view returns (bytes memory);
}

File 13 of 31 : IContractScript.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

///////////////////////////////////////////////////////////
// ░██████╗░█████╗░██████╗░██╗██████╗░████████╗██╗░░░██╗ //
// ██╔════╝██╔══██╗██╔══██╗██║██╔══██╗╚══██╔══╝╚██╗░██╔╝ //
// ╚█████╗░██║░░╚═╝██████╔╝██║██████╔╝░░░██║░░░░╚████╔╝░ //
// ░╚═══██╗██║░░██╗██╔══██╗██║██╔═══╝░░░░██║░░░░░╚██╔╝░░ //
// ██████╔╝╚█████╔╝██║░░██║██║██║░░░░░░░░██║░░░░░░██║░░░ //
// ╚═════╝░░╚════╝░╚═╝░░╚═╝╚═╝╚═╝░░░░░░░░╚═╝░░░░░░╚═╝░░░ //
///////////////////////////////////////////////////////////

interface IContractScript {
  // =============================================================
  //                            GETTERS
  // =============================================================

  /**
   * @notice Get the full script
   * @param name - Name given to the script. Eg: threejs.min.js_r148
   * @param data - Arbitrary data to be passed to storage
   * @return script - Full script from merged chunks
   */
  function getScript(
    string calldata name,
    bytes memory data
  ) external view returns (bytes memory script);
}

File 14 of 31 : IDataStorage.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import '@openzeppelin/contracts/access/Ownable.sol';

interface IDataStorage is IERC165 {
  struct InitConfig {
    address writer;
    bytes params;
  }

  function indexToData(uint256 index) external view returns (bytes memory);

  function init(address owner, InitConfig calldata config) external;
}

File 15 of 31 : IScriptyBuilder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

///////////////////////////////////////////////////////////
// ░██████╗░█████╗░██████╗░██╗██████╗░████████╗██╗░░░██╗ //
// ██╔════╝██╔══██╗██╔══██╗██║██╔══██╗╚══██╔══╝╚██╗░██╔╝ //
// ╚█████╗░██║░░╚═╝██████╔╝██║██████╔╝░░░██║░░░░╚████╔╝░ //
// ░╚═══██╗██║░░██╗██╔══██╗██║██╔═══╝░░░░██║░░░░░╚██╔╝░░ //
// ██████╔╝╚█████╔╝██║░░██║██║██║░░░░░░░░██║░░░░░░██║░░░ //
// ╚═════╝░░╚════╝░╚═╝░░╚═╝╚═╝╚═╝░░░░░░░░╚═╝░░░░░░╚═╝░░░ //
///////////////////////////////////////////////////////////

// =============================================================
//                            STRUCTS
// =============================================================

struct WrappedScriptRequest {
  string name;
  address contractAddress;
  bytes contractData;
  uint8 wrapType;
  bytes wrapPrefix;
  bytes wrapSuffix;
  bytes scriptContent;
}

struct InlineScriptRequest {
  string name;
  address contractAddress;
  bytes contractData;
  bytes scriptContent;
}

interface IScriptyBuilder {
  // =============================================================
  //                            ERRORS
  // =============================================================

  /**
   * @notice Error for, Invalid length of requests
   */
  error InvalidRequestsLength();

  // =============================================================
  //                      RAW HTML GETTERS
  // =============================================================

  /**
   * @notice Get requested scripts housed in <body> with custom wrappers
   * @dev Your requested scripts are returned in the following format:
   *      <html>
   *          <head></head>
   *          <body style='margin:0;'>
   *              [wrapPrefix[0]]{request[0]}[wrapSuffix[0]]
   *              [wrapPrefix[1]]{request[1]}[wrapSuffix[1]]
   *              ...
   *              [wrapPrefix[n]]{request[n]}[wrapSuffix[n]]
   *          </body>
   *      </html>
   * @param requests - Array of WrappedScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   * @return Full html wrapped scripts
   */
  function getHTMLWrapped(
    WrappedScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (bytes memory);

  /**
   * @notice Get requested scripts housed in URL Safe wrappers
   * @dev Any wrapper type 0 scripts are converted to base64 and wrapped
   *      with <script src="data:text/javascript;base64,[SCRIPT]"></script>
   *
   *      [WARNING]: Large non-base64 libraries that need base64 encoding
   *      carry a high risk of causing a gas out. Highly advised to use
   *      base64 encoded scripts where possible
   *
   *      Your requested scripts are returned in the following format:
   *      <html>
   *          <head></head>
   *          <body style='margin:0;'>
   *              [wrapPrefix[0]]{request[0]}[wrapSuffix[0]]
   *              [wrapPrefix[1]]{request[1]}[wrapSuffix[1]]
   *              ...
   *              [wrapPrefix[n]]{request[n]}[wrapSuffix[n]]
   *          </body>
   *      </html>
   * @param requests - Array of WrappedScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   * @return Full URL Safe wrapped scripts
   */
  function getHTMLWrappedURLSafe(
    WrappedScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (bytes memory);

  /**
   * @notice Get requested scripts housed in <body> all wrapped in <script></script>
   * @dev Your requested scripts are returned in the following format:
   *      <html>
   *          <head></head>
   *          <body style='margin:0;'>
   *              <script>
   *                  {request[0]}
   *                  {request[1]}
   *                  ...
   *                  {request[n]}
   *              </script>
   *          </body>
   *      </html>
   * @param requests - Array of InlineScriptRequest
   * @param bufferSize - Total buffer size of all requested scripts
   * @return Full html wrapped scripts
   */
  function getHTMLInline(
    InlineScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (bytes memory);

  // =============================================================
  //                      ENCODED HTML GETTERS
  // =============================================================

  /**
   * @notice Get {getHTMLWrapped} and base64 encode it
   * @param requests - Array of WrappedScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   * @return Full html wrapped scripts, base64 encoded
   */
  function getEncodedHTMLWrapped(
    WrappedScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (bytes memory);

  /**
   * @notice Get {getHTMLInline} and base64 encode it
   * @param requests - Array of InlineScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   * @return Full html wrapped scripts, base64 encoded
   */
  function getEncodedHTMLInline(
    InlineScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (bytes memory);

  // =============================================================
  //                      STRING UTILITIES
  // =============================================================

  /**
   * @notice Convert {getHTMLWrapped} output to a string
   * @param requests - Array of WrappedScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   * @return {getHTMLWrapped} as a string
   */
  function getHTMLWrappedString(
    WrappedScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (string memory);

  /**
   * @notice Convert {getHTMLInline} output to a string
   * @param requests - Array of InlineScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   * @return {getHTMLInline} as a string
   */
  function getHTMLInlineString(
    InlineScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (string memory);

  /**
   * @notice Convert {getEncodedHTMLWrapped} output to a string
   * @param requests - Array of WrappedScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   *                     before encoding.
   * @return {getEncodedHTMLWrapped} as a string
   */
  function getEncodedHTMLWrappedString(
    WrappedScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (string memory);

  /**
   * @notice Convert {getEncodedHTMLInline} output to a string
   * @param requests - Array of InlineScriptRequests
   * @param bufferSize - Total buffer size of all requested scripts
   *                     before encoding.
   * @return {getEncodedHTMLInline} as a string
   */
  function getEncodedHTMLInlineString(
    InlineScriptRequest[] calldata requests,
    uint256 bufferSize
  ) external view returns (string memory);

  // =============================================================
  //                      OFF-CHAIN UTILITIES
  // =============================================================

  /**
   * @notice Get the buffer size of a single inline requested code
   * @param request - InlineScriptRequest data for code
   * @return Buffer size as an unit256
   */
  function getInlineScriptSize(
    InlineScriptRequest memory request
  ) external view returns (uint256);

  /**
   * @notice Get the buffer size of a single wrapped requested code
   * @param request - WrappedScriptRequest data for code
   * @return Buffer size as an unit256
   */
  function getWrappedScriptSize(
    WrappedScriptRequest memory request
  ) external view returns (uint256);

  /**
   * @notice Get the buffer size of a single wrapped requested code
   * @dev If the script is of wrapper type 0, we get buffer size for
   *      base64 encoded version.
   * @param request - WrappedScriptRequest data for code
   * @return Buffer size as an unit256
   */
  function getURLSafeWrappedScriptSize(
    WrappedScriptRequest memory request
  ) external view returns (uint256);

  /**
   * @notice Get the buffer size of an array of html wrapped inline scripts
   * @param requests - InlineScriptRequests data for code
   * @return Buffer size as an unit256
   */
  function getBufferSizeForHTMLInline(
    InlineScriptRequest[] calldata requests
  ) external view returns (uint256);

  /**
   * @notice Get the buffer size of an array of html wrapped, wrapped scripts
   * @param requests - WrappedScriptRequests data for code
   * @return Buffer size as an unit256
   */
  function getBufferSizeForHTMLWrapped(
    WrappedScriptRequest[] calldata requests
  ) external view returns (uint256);

  /**
   * @notice Get the buffer size of an array of URL safe html wrapped scripts
   * @param requests - WrappedScriptRequests data for code
   * @return Buffer size as an unit256
   */
  function getBufferSizeForURLSafeHTMLWrapped(
    WrappedScriptRequest[] calldata requests
  ) external view returns (uint256);

  /**
   * @notice Get the buffer size for encoded HTML inline scripts
   * @param requests - InlineScriptRequests data for code
   * @return Buffer size as an unit256
   */
  function getBufferSizeForEncodedHTMLInline(
    InlineScriptRequest[] calldata requests
  ) external view returns (uint256);

  /**
   * @notice Get the buffer size for encoded HTML inline scripts
   * @param requests - InlineScriptRequests data for code
   * @return Buffer size as an unit256
   */
  function getBufferSizeForEncodedHTMLWrapped(
    WrappedScriptRequest[] calldata requests
  ) external view returns (uint256);
}

File 16 of 31 : Bytecode.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

library Bytecode {
  error InvalidCodeAtRange(uint256 _size, uint256 _start, uint256 _end);

  /**
    @notice Generate a creation code that results on a contract with `_code` as bytecode
    @param _code The returning value of the resulting `creationCode`
    @return creationCode (constructor) for new contract
  */
  function creationCodeFor(
    bytes memory _code
  ) internal pure returns (bytes memory) {
    /*
      0x00    0x63         0x63XXXXXX  PUSH4 _code.length  size
      0x01    0x80         0x80        DUP1                size size
      0x02    0x60         0x600e      PUSH1 14            14 size size
      0x03    0x60         0x6000      PUSH1 00            0 14 size size
      0x04    0x39         0x39        CODECOPY            size
      0x05    0x60         0x6000      PUSH1 00            0 size
      0x06    0xf3         0xf3        RETURN
      <CODE>
    */

    return
      abi.encodePacked(
        hex'63',
        uint32(_code.length),
        hex'80_60_0E_60_00_39_60_00_F3',
        _code
      );
  }

  /**
    @notice Returns the size of the code on a given address
    @param _addr Address that may or may not contain code
    @return size of the code on the given `_addr`
  */
  function codeSize(address _addr) internal view returns (uint256 size) {
    assembly {
      size := extcodesize(_addr)
    }
  }

  /**
    @notice Returns the code of a given address
    @dev It will fail if `_end < _start`
    @param _addr Address that may or may not contain code
    @param _start number of bytes of code to skip on read
    @param _end index before which to end extraction
    @return oCode read from `_addr` deployed bytecode
    Forked from: https://gist.github.com/KardanovIR/fe98661df9338c842b4a30306d507fbd
  */
  function codeAt(
    address _addr,
    uint256 _start,
    uint256 _end
  ) internal view returns (bytes memory oCode) {
    uint256 csize = codeSize(_addr);
    if (csize == 0) return bytes('');

    if (_start > csize) return bytes('');
    if (_end < _start) revert InvalidCodeAtRange(csize, _start, _end);

    unchecked {
      uint256 reqSize = _end - _start;
      uint256 maxSize = csize - _start;

      uint256 size = maxSize < reqSize ? maxSize : reqSize;

      assembly {
        // allocate output byte array - this could also be done without assembly
        // by using o_code = new bytes(size)
        oCode := mload(0x40)
        // new "memory end" including padding
        mstore(0x40, add(oCode, and(add(add(size, 0x20), 0x1f), not(0x1f))))
        // store length in memory
        mstore(oCode, size)
        // actually retrieve the code, this needs assembly
        extcodecopy(_addr, add(oCode, 0x20), _start, size)
      }
    }
  }
}

File 17 of 31 : BytesUtils.sol
// SPDX-License-Identifier: MIT
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity ^0.8.4;

library BytesUtils {
  function concat(
    bytes memory _preBytes,
    bytes memory _postBytes
  ) internal pure returns (bytes memory) {
    bytes memory tempBytes;

    assembly {
      // Get a location of some free memory and store it in tempBytes as
      // Solidity does for memory variables.
      tempBytes := mload(0x40)

      // Store the length of the first bytes array at the beginning of
      // the memory for tempBytes.
      let length := mload(_preBytes)
      mstore(tempBytes, length)

      // Maintain a memory counter for the current write location in the
      // temp bytes array by adding the 32 bytes for the array length to
      // the starting location.
      let mc := add(tempBytes, 0x20)
      // Stop copying when the memory counter reaches the length of the
      // first bytes array.
      let end := add(mc, length)

      for {
        // Initialize a copy counter to the start of the _preBytes data,
        // 32 bytes into its memory.
        let cc := add(_preBytes, 0x20)
      } lt(mc, end) {
        // Increase both counters by 32 bytes each iteration.
        mc := add(mc, 0x20)
        cc := add(cc, 0x20)
      } {
        // Write the _preBytes data into the tempBytes memory 32 bytes
        // at a time.
        mstore(mc, mload(cc))
      }

      // Add the length of _postBytes to the current length of tempBytes
      // and store it as the new length in the first 32 bytes of the
      // tempBytes memory.
      length := mload(_postBytes)
      mstore(tempBytes, add(length, mload(tempBytes)))

      // Move the memory counter back from a multiple of 0x20 to the
      // actual end of the _preBytes data.
      mc := end
      // Stop copying when the memory counter reaches the new combined
      // length of the arrays.
      end := add(mc, length)

      for {
        let cc := add(_postBytes, 0x20)
      } lt(mc, end) {
        mc := add(mc, 0x20)
        cc := add(cc, 0x20)
      } {
        mstore(mc, mload(cc))
      }

      // Update the free-memory pointer by padding our last write location
      // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
      // next 32 byte block, then round down to the nearest multiple of
      // 32. If the sum of the length of the two arrays is zero then add
      // one before rounding down to leave a blank 32 bytes (the length block with 0).
      mstore(
        0x40,
        and(
          add(add(end, iszero(add(length, mload(_preBytes)))), 31),
          not(31) // Round down to the nearest 32 bytes.
        )
      )
    }

    return tempBytes;
  }

  function concatStorage(
    bytes storage _preBytes,
    bytes memory _postBytes
  ) internal {
    assembly {
      // Read the first 32 bytes of _preBytes storage, which is the length
      // of the array. (We don't need to use the offset into the slot
      // because arrays use the entire slot.)
      let fslot := sload(_preBytes.slot)
      // Arrays of 31 bytes or less have an even value in their slot,
      // while longer arrays have an odd value. The actual length is
      // the slot divided by two for odd values, and the lowest order
      // byte divided by two for even values.
      // If the slot is even, bitwise and the slot with 255 and divide by
      // two to get the length. If the slot is odd, bitwise and the slot
      // with -1 and divide by two.
      let slength := div(
        and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)),
        2
      )
      let mlength := mload(_postBytes)
      let newlength := add(slength, mlength)
      // slength can contain both the length and contents of the array
      // if length < 32 bytes so let's prepare for that
      // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
      switch add(lt(slength, 32), lt(newlength, 32))
      case 2 {
        // Since the new array still fits in the slot, we just need to
        // update the contents of the slot.
        // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
        sstore(
          _preBytes.slot,
          // all the modifications to the slot are inside this
          // next block
          add(
            // we can just add to the slot contents because the
            // bytes we want to change are the LSBs
            fslot,
            add(
              mul(
                div(
                  // load the bytes from memory
                  mload(add(_postBytes, 0x20)),
                  // zero all bytes to the right
                  exp(0x100, sub(32, mlength))
                ),
                // and now shift left the number of bytes to
                // leave space for the length in the slot
                exp(0x100, sub(32, newlength))
              ),
              // increase length by the double of the memory
              // bytes length
              mul(mlength, 2)
            )
          )
        )
      }
      case 1 {
        // The stored value fits in the slot, but the combined value
        // will exceed it.
        // get the keccak hash to get the contents of the array
        mstore(0x0, _preBytes.slot)
        let sc := add(keccak256(0x0, 0x20), div(slength, 32))

        // save new length
        sstore(_preBytes.slot, add(mul(newlength, 2), 1))

        // The contents of the _postBytes array start 32 bytes into
        // the structure. Our first read should obtain the `submod`
        // bytes that can fit into the unused space in the last word
        // of the stored array. To get this, we read 32 bytes starting
        // from `submod`, so the data we read overlaps with the array
        // contents by `submod` bytes. Masking the lowest-order
        // `submod` bytes allows us to add that value directly to the
        // stored value.

        let submod := sub(32, slength)
        let mc := add(_postBytes, submod)
        let end := add(_postBytes, mlength)
        let mask := sub(exp(0x100, submod), 1)

        sstore(
          sc,
          add(
            and(
              fslot,
              0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
            ),
            and(mload(mc), mask)
          )
        )

        for {
          mc := add(mc, 0x20)
          sc := add(sc, 1)
        } lt(mc, end) {
          sc := add(sc, 1)
          mc := add(mc, 0x20)
        } {
          sstore(sc, mload(mc))
        }

        mask := exp(0x100, sub(mc, end))

        sstore(sc, mul(div(mload(mc), mask), mask))
      }
      default {
        // get the keccak hash to get the contents of the array
        mstore(0x0, _preBytes.slot)
        // Start copying to the last used word of the stored array.
        let sc := add(keccak256(0x0, 0x20), div(slength, 32))

        // save new length
        sstore(_preBytes.slot, add(mul(newlength, 2), 1))

        // Copy over the first `submod` bytes of the new data as in
        // case 1 above.
        let slengthmod := mod(slength, 32)
        let mlengthmod := mod(mlength, 32)
        let submod := sub(32, slengthmod)
        let mc := add(_postBytes, submod)
        let end := add(_postBytes, mlength)
        let mask := sub(exp(0x100, submod), 1)

        sstore(sc, add(sload(sc), and(mload(mc), mask)))

        for {
          sc := add(sc, 1)
          mc := add(mc, 0x20)
        } lt(mc, end) {
          sc := add(sc, 1)
          mc := add(mc, 0x20)
        } {
          sstore(sc, mload(mc))
        }

        mask := exp(0x100, sub(mc, end))

        sstore(sc, mul(div(mload(mc), mask), mask))
      }
    }
  }

  function slice(
    bytes memory _bytes,
    uint256 _start,
    uint256 _length
  ) internal pure returns (bytes memory) {
    require(_length + 31 >= _length, 'slice_overflow');
    require(_bytes.length >= _start + _length, 'slice_outOfBounds');

    bytes memory tempBytes;

    assembly {
      switch iszero(_length)
      case 0 {
        // Get a location of some free memory and store it in tempBytes as
        // Solidity does for memory variables.
        tempBytes := mload(0x40)

        // The first word of the slice result is potentially a partial
        // word read from the original array. To read it, we calculate
        // the length of that partial word and start copying that many
        // bytes into the array. The first word we copy will start with
        // data we don't care about, but the last `lengthmod` bytes will
        // land at the beginning of the contents of the new array. When
        // we're done copying, we overwrite the full first word with
        // the actual length of the slice.
        let lengthmod := and(_length, 31)

        // The multiplication in the next line is necessary
        // because when slicing multiples of 32 bytes (lengthmod == 0)
        // the following copy loop was copying the origin's length
        // and then ending prematurely not copying everything it should.
        let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
        let end := add(mc, _length)

        for {
          // The multiplication in the next line has the same exact purpose
          // as the one above.
          let cc := add(
            add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))),
            _start
          )
        } lt(mc, end) {
          mc := add(mc, 0x20)
          cc := add(cc, 0x20)
        } {
          mstore(mc, mload(cc))
        }

        mstore(tempBytes, _length)

        //update free-memory pointer
        //allocating the array padded to 32 bytes like the compiler does now
        mstore(0x40, and(add(mc, 31), not(31)))
      }
      //if we want a zero-length slice let's just return a zero-length array
      default {
        tempBytes := mload(0x40)
        //zero out the 32 bytes slice we are about to return
        //we need to do it because Solidity does not garbage collect
        mstore(tempBytes, 0)

        mstore(0x40, add(tempBytes, 0x20))
      }
    }

    return tempBytes;
  }

  function toAddress(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (address) {
    require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
    address tempAddress;

    assembly {
      tempAddress := div(
        mload(add(add(_bytes, 0x20), _start)),
        0x1000000000000000000000000
      )
    }

    return tempAddress;
  }

  function toUint8(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (uint8) {
    require(_bytes.length >= _start + 1, 'toUint8_outOfBounds');
    uint8 tempUint;

    assembly {
      tempUint := mload(add(add(_bytes, 0x1), _start))
    }

    return tempUint;
  }

  function toUint16(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (uint16) {
    require(_bytes.length >= _start + 2, 'toUint16_outOfBounds');
    uint16 tempUint;

    assembly {
      tempUint := mload(add(add(_bytes, 0x2), _start))
    }

    return tempUint;
  }

  function toUint32(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (uint32) {
    require(_bytes.length >= _start + 4, 'toUint32_outOfBounds');
    uint32 tempUint;

    assembly {
      tempUint := mload(add(add(_bytes, 0x4), _start))
    }

    return tempUint;
  }

  function toUint64(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (uint64) {
    require(_bytes.length >= _start + 8, 'toUint64_outOfBounds');
    uint64 tempUint;

    assembly {
      tempUint := mload(add(add(_bytes, 0x8), _start))
    }

    return tempUint;
  }

  function toUint96(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (uint96) {
    require(_bytes.length >= _start + 12, 'toUint96_outOfBounds');
    uint96 tempUint;

    assembly {
      tempUint := mload(add(add(_bytes, 0xc), _start))
    }

    return tempUint;
  }

  function toUint128(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (uint128) {
    require(_bytes.length >= _start + 16, 'toUint128_outOfBounds');
    uint128 tempUint;

    assembly {
      tempUint := mload(add(add(_bytes, 0x10), _start))
    }

    return tempUint;
  }

  function toUint256(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (uint256) {
    require(_bytes.length >= _start + 32, 'toUint256_outOfBounds');
    uint256 tempUint;

    assembly {
      tempUint := mload(add(add(_bytes, 0x20), _start))
    }

    return tempUint;
  }

  function toBytes32(
    bytes memory _bytes,
    uint256 _start
  ) internal pure returns (bytes32) {
    require(_bytes.length >= _start + 32, 'toBytes32_outOfBounds');
    bytes32 tempBytes32;

    assembly {
      tempBytes32 := mload(add(add(_bytes, 0x20), _start))
    }

    return tempBytes32;
  }

  function equal(
    bytes memory _preBytes,
    bytes memory _postBytes
  ) internal pure returns (bool) {
    bool success = true;

    assembly {
      let length := mload(_preBytes)

      // if lengths don't match the arrays are not equal
      switch eq(length, mload(_postBytes))
      case 1 {
        // cb is a circuit breaker in the for loop since there's
        //  no said feature for inline assembly loops
        // cb = 1 - don't breaker
        // cb = 0 - break
        let cb := 1

        let mc := add(_preBytes, 0x20)
        let end := add(mc, length)

        for {
          let cc := add(_postBytes, 0x20)
          // the next line is the loop condition:
          // while(uint256(mc < end) + cb == 2)
        } eq(add(lt(mc, end), cb), 2) {
          mc := add(mc, 0x20)
          cc := add(cc, 0x20)
        } {
          // if any of these checks fails then arrays are not equal
          if iszero(eq(mload(mc), mload(cc))) {
            // unsuccess:
            success := 0
            cb := 0
          }
        }
      }
      default {
        // unsuccess:
        success := 0
      }
    }

    return success;
  }

  function equalStorage(
    bytes storage _preBytes,
    bytes memory _postBytes
  ) internal view returns (bool) {
    bool success = true;

    assembly {
      // we know _preBytes_offset is 0
      let fslot := sload(_preBytes.slot)
      // Decode the length of the stored array like in concatStorage().
      let slength := div(
        and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)),
        2
      )
      let mlength := mload(_postBytes)

      // if lengths don't match the arrays are not equal
      switch eq(slength, mlength)
      case 1 {
        // slength can contain both the length and contents of the array
        // if length < 32 bytes so let's prepare for that
        // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
        if iszero(iszero(slength)) {
          switch lt(slength, 32)
          case 1 {
            // blank the last byte which is the length
            fslot := mul(div(fslot, 0x100), 0x100)

            if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
              // unsuccess:
              success := 0
            }
          }
          default {
            // cb is a circuit breaker in the for loop since there's
            //  no said feature for inline assembly loops
            // cb = 1 - don't breaker
            // cb = 0 - break
            let cb := 1

            // get the keccak hash to get the contents of the array
            mstore(0x0, _preBytes.slot)
            let sc := keccak256(0x0, 0x20)

            let mc := add(_postBytes, 0x20)
            let end := add(mc, mlength)

            // the next line is the loop condition:
            // while(uint256(mc < end) + cb == 2)
            for {

            } eq(add(lt(mc, end), cb), 2) {
              sc := add(sc, 1)
              mc := add(mc, 0x20)
            } {
              if iszero(eq(sload(sc), mload(mc))) {
                // unsuccess:
                success := 0
                cb := 0
              }
            }
          }
        }
      }
      default {
        // unsuccess:
        success := 0
      }
    }

    return success;
  }
}

File 18 of 31 : DynamicBuffer.sol
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)

pragma solidity >=0.8.0;

/// @title DynamicBuffer
/// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also
///         https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer
/// @notice This library is used to allocate a big amount of container memory
//          which will be subsequently filled without needing to reallocate
///         memory.
/// @dev First, allocate memory.
///      Then use `buffer.appendUnchecked(theBytes)` or `appendSafe()` if
///      bounds checking is required.
library DynamicBuffer {
  /// @notice Allocates container space for the DynamicBuffer
  /// @param capacity_ The intended max amount of bytes in the buffer
  /// @return buffer The memory location of the buffer
  /// @dev Allocates `capacity_ + 0x60` bytes of space
  ///      The buffer array starts at the first container data position,
  ///      (i.e. `buffer = container + 0x20`)
  function allocate(
    uint256 capacity_
  ) internal pure returns (bytes memory buffer) {
    assembly {
      // Get next-free memory address
      let container := mload(0x40)

      // Allocate memory by setting a new next-free address
      {
        // Add 2 x 32 bytes in size for the two length fields
        // Add 32 bytes safety space for 32B chunked copy
        let size := add(capacity_, 0x60)
        let newNextFree := add(container, size)
        mstore(0x40, newNextFree)
      }

      // Set the correct container length
      {
        let length := add(capacity_, 0x40)
        mstore(container, length)
      }

      // The buffer starts at idx 1 in the container (0 is length)
      buffer := add(container, 0x20)

      // Init content with length 0
      mstore(buffer, 0)
    }

    return buffer;
  }

  /// @notice Appends data to buffer, and update buffer length
  /// @param buffer the buffer to append the data to
  /// @param data the data to append
  /// @dev Does not perform out-of-bound checks (container capacity)
  ///      for efficiency.
  function appendUnchecked(
    bytes memory buffer,
    bytes memory data
  ) internal pure {
    assembly {
      let length := mload(data)
      for {
        data := add(data, 0x20)
        let dataEnd := add(data, length)
        let copyTo := add(buffer, add(mload(buffer), 0x20))
      } lt(data, dataEnd) {
        data := add(data, 0x20)
        copyTo := add(copyTo, 0x20)
      } {
        // Copy 32B chunks from data to buffer.
        // This may read over data array boundaries and copy invalid
        // bytes, which doesn't matter in the end since we will
        // later set the correct buffer length, and have allocated an
        // additional word to avoid buffer overflow.
        mstore(copyTo, mload(data))
      }

      // Update buffer length
      mstore(buffer, add(mload(buffer), length))
    }
  }

  /// @notice Appends data to buffer, and update buffer length
  /// @param buffer the buffer to append the data to
  /// @param data the data to append
  /// @dev Performs out-of-bound checks and calls `appendUnchecked`.
  function appendSafe(bytes memory buffer, bytes memory data) internal pure {
    checkOverflow(buffer, data.length);
    appendUnchecked(buffer, data);
  }

  /// @notice Appends data encoded as Base64 to buffer.
  /// @param fileSafe  Whether to replace '+' with '-' and '/' with '_'.
  /// @param noPadding Whether to strip away the padding.
  /// @dev Encodes `data` using the base64 encoding described in RFC 4648.
  /// See: https://datatracker.ietf.org/doc/html/rfc4648
  /// Author: Modified from Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)
  /// Author: Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol)
  /// Author: Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos.
  function appendSafeBase64(
    bytes memory buffer,
    bytes memory data,
    bool fileSafe,
    bool noPadding
  ) internal pure {
    uint256 dataLength = data.length;

    if (data.length == 0) {
      return;
    }

    uint256 encodedLength;
    uint256 r;
    assembly {
      // For each 3 bytes block, we will have 4 bytes in the base64
      // encoding: `encodedLength = 4 * divCeil(dataLength, 3)`.
      // The `shl(2, ...)` is equivalent to multiplying by 4.
      encodedLength := shl(2, div(add(dataLength, 2), 3))

      r := mod(dataLength, 3)
      if noPadding {
        // if r == 0 => no modification
        // if r == 1 => encodedLength -= 2
        // if r == 2 => encodedLength -= 1
        encodedLength := sub(encodedLength, add(iszero(iszero(r)), eq(r, 1)))
      }
    }

    checkOverflow(buffer, encodedLength);

    assembly {
      let nextFree := mload(0x40)

      // Store the table into the scratch space.
      // Offsetted by -1 byte so that the `mload` will load the character.
      // We will rewrite the free memory pointer at `0x40` later with
      // the allocated size.
      mstore(0x1f, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef')
      mstore(
        0x3f,
        sub(
          'ghijklmnopqrstuvwxyz0123456789-_',
          // The magic constant 0x0230 will translate "-_" + "+/".
          mul(iszero(fileSafe), 0x0230)
        )
      )

      // Skip the first slot, which stores the length.
      let ptr := add(add(buffer, 0x20), mload(buffer))
      let end := add(data, dataLength)

      // Run over the input, 3 bytes at a time.
      // prettier-ignore
      // solhint-disable-next-line no-empty-blocks
      for {} 1 {} {
                    data := add(data, 3) // Advance 3 bytes.
                    let input := mload(data)

                    // Write 4 bytes. Optimized for fewer stack operations.
                    mstore8(    ptr    , mload(and(shr(18, input), 0x3F)))
                    mstore8(add(ptr, 1), mload(and(shr(12, input), 0x3F)))
                    mstore8(add(ptr, 2), mload(and(shr( 6, input), 0x3F)))
                    mstore8(add(ptr, 3), mload(and(        input , 0x3F)))
                    
                    ptr := add(ptr, 4) // Advance 4 bytes.
                    // prettier-ignore
                    if iszero(lt(data, end)) { break }
                }

      if iszero(noPadding) {
        // Offset `ptr` and pad with '='. We can simply write over the end.
        mstore8(sub(ptr, iszero(iszero(r))), 0x3d) // Pad at `ptr - 1` if `r > 0`.
        mstore8(sub(ptr, shl(1, eq(r, 1))), 0x3d) // Pad at `ptr - 2` if `r == 1`.
      }

      mstore(buffer, add(mload(buffer), encodedLength))
      mstore(0x40, nextFree)
    }
  }

  /// @notice Appends data encoded as Base64 to buffer.
  /// @param fileSafe  Whether to replace '+' with '-' and '/' with '_'.
  /// @param noPadding Whether to strip away the padding.
  /// @dev Encodes `data` using the base64 encoding described in RFC 4648.
  /// See: https://datatracker.ietf.org/doc/html/rfc4648
  /// Author: Modified from Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)
  /// Author: Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol)
  /// Author: Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos.
  function appendUncheckedBase64(
    bytes memory buffer,
    bytes memory data,
    bool fileSafe,
    bool noPadding
  ) internal pure {
    uint256 dataLength = data.length;

    if (data.length == 0) {
      return;
    }

    uint256 encodedLength;
    uint256 r;
    assembly {
      // For each 3 bytes block, we will have 4 bytes in the base64
      // encoding: `encodedLength = 4 * divCeil(dataLength, 3)`.
      // The `shl(2, ...)` is equivalent to multiplying by 4.
      encodedLength := shl(2, div(add(dataLength, 2), 3))

      r := mod(dataLength, 3)
      if noPadding {
        // if r == 0 => no modification
        // if r == 1 => encodedLength -= 2
        // if r == 2 => encodedLength -= 1
        encodedLength := sub(encodedLength, add(iszero(iszero(r)), eq(r, 1)))
      }
    }

    assembly {
      let nextFree := mload(0x40)

      // Store the table into the scratch space.
      // Offsetted by -1 byte so that the `mload` will load the character.
      // We will rewrite the free memory pointer at `0x40` later with
      // the allocated size.
      mstore(0x1f, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef')
      mstore(
        0x3f,
        sub(
          'ghijklmnopqrstuvwxyz0123456789-_',
          // The magic constant 0x0230 will translate "-_" + "+/".
          mul(iszero(fileSafe), 0x0230)
        )
      )

      // Skip the first slot, which stores the length.
      let ptr := add(add(buffer, 0x20), mload(buffer))
      let end := add(data, dataLength)

      // Run over the input, 3 bytes at a time.
      // prettier-ignore
      // solhint-disable-next-line no-empty-blocks
      for {} 1 {} {
                    data := add(data, 3) // Advance 3 bytes.
                    let input := mload(data)

                    // Write 4 bytes. Optimized for fewer stack operations.
                    mstore8(    ptr    , mload(and(shr(18, input), 0x3F)))
                    mstore8(add(ptr, 1), mload(and(shr(12, input), 0x3F)))
                    mstore8(add(ptr, 2), mload(and(shr( 6, input), 0x3F)))
                    mstore8(add(ptr, 3), mload(and(        input , 0x3F)))
                    
                    ptr := add(ptr, 4) // Advance 4 bytes.
                    // prettier-ignore
                    if iszero(lt(data, end)) { break }
                }

      if iszero(noPadding) {
        // Offset `ptr` and pad with '='. We can simply write over the end.
        mstore8(sub(ptr, iszero(iszero(r))), 0x3d) // Pad at `ptr - 1` if `r > 0`.
        mstore8(sub(ptr, shl(1, eq(r, 1))), 0x3d) // Pad at `ptr - 2` if `r == 1`.
      }

      mstore(buffer, add(mload(buffer), encodedLength))
      mstore(0x40, nextFree)
    }
  }

  /// @notice Returns the capacity of a given buffer.
  function capacity(bytes memory buffer) internal pure returns (uint256) {
    uint256 cap;
    assembly {
      cap := sub(mload(sub(buffer, 0x20)), 0x40)
    }
    return cap;
  }

  /// @notice Reverts if the buffer will overflow after appending a given
  /// number of bytes.
  function checkOverflow(
    bytes memory buffer,
    uint256 addedLength
  ) internal pure {
    uint256 cap = capacity(buffer);
    uint256 newLength = buffer.length + addedLength;
    if (cap < newLength) {
      revert('DynamicBuffer: Appending out of bounds.');
    }
  }
}

File 19 of 31 : ComponentUtils.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/Base64.sol';
import './bytes/BytesUtils.sol';

library ComponentUtils {
  // commonly used nft metadata keywords
  string public constant NAME_KEY = 'name';
  string public constant DESCRIPTION_KEY = 'description';
  string public constant ATTRIBUTES_KEY = 'attributes';
  string public constant BACKGROUND_COLOR_KEY = 'background_color';
  string public constant ANIMATION_URL_KEY = 'animation_url';
  string public constant EXTERNAL_URL_KEY = 'external_url';
  string public constant IMAGE_KEY = 'image';
  string public constant IMAGE_DATA_KEY = 'image_data';

  // base64 encoded data prefixes
  string public constant JSON_DATA_BASE_64_PREFIX =
    'data:application/json;base64,';
  string public constant SVG_DATA_BASE_64_PREFIX = 'data:image/svg+xml;base64,';
  string public constant GIF_DATA_BASE_64_PREFIX = 'data:image/gif;base64,';
  string public constant PNG_DATA_BASE_64_PREFIX = 'data:image/png;base64,';
  string public constant JPEG_DATA_BASE_64_PREFIX = 'data:image/jpeg;base64,';

  string constant JSON_DELIMITER = ',';
  string constant VALUE_KEY = 'value';
  string constant TRAIT_TYPE_KEY = 'trait_type';
  string constant MAX_VALUE_KEY = 'max_value';
  string constant DISPLAY_TYPE_KEY = 'display_type';

  string constant BOOST_NUMBER_DISPLAY_TYPE = 'boost_number';
  string constant BOOST_PERCENTAGE_DISPLAY_TYPE = 'boost_percentage';
  string constant NUMBER_DISPLAY_TYPE = 'number';
  string constant DATE_DISPLAY_TYPE = 'date';

  function encodeJson(
    string memory content
  ) public pure returns (string memory) {
    return
      string(
        abi.encodePacked(
          JSON_DATA_BASE_64_PREFIX,
          Base64.encode(bytes(content))
        )
      );
  }

  function object(string[] memory content) public pure returns (string memory) {
    return string(abi.encodePacked('{', delimit(content), '}'));
  }

  function array(string[] memory content) public pure returns (string memory) {
    return string(abi.encodePacked('[', delimit(content), ']'));
  }

  function keyValue(
    string memory key,
    string memory value
  ) public pure returns (string memory) {
    return string(abi.encodePacked('"', key, '":', value));
  }

  function stringWrap(string memory value) public pure returns (string memory) {
    return string(abi.encodePacked('"', value, '"'));
  }

  function delimit(string[] memory values) public pure returns (string memory) {
    bytes memory delimitedValues = '';
    for (uint256 i = 0; i < values.length; ++i) {
      delimitedValues = abi.encodePacked(
        delimitedValues,
        i == 0 ? '' : JSON_DELIMITER,
        values[i]
      );
    }
    return string(delimitedValues);
  }

  function getBaseAttributeObject(
    string memory traitType,
    string memory value,
    string memory extra
  ) public pure returns (string memory) {
    string[] memory components = new string[](3);
    components[0] = keyValue(VALUE_KEY, value);
    components[1] = keyValue(TRAIT_TYPE_KEY, stringWrap(traitType));
    components[2] = extra;

    return object(components);
  }

  function getAttributeObject(
    string memory traitType,
    string memory value
  ) public pure returns (string memory) {
    return getBaseAttributeObject(traitType, value, '');
  }

  function getAttributeObjectWithMaxValue(
    string memory traitType,
    string memory value,
    string memory maxValue
  ) public pure returns (string memory) {
    return
      getBaseAttributeObject(
        traitType,
        value,
        keyValue(MAX_VALUE_KEY, maxValue)
      );
  }

  function getAttributeObjectWithDisplayType(
    string memory traitType,
    string memory value,
    string memory displayType
  ) public pure returns (string memory) {
    return
      getBaseAttributeObject(
        traitType,
        value,
        keyValue(DISPLAY_TYPE_KEY, displayType)
      );
  }

  function getAttributeObjectWithDisplayTypeAndMaxValue(
    string memory traitType,
    string memory value,
    string memory displayType,
    string memory maxValue
  ) public pure returns (string memory) {
    string[] memory components = new string[](2);
    components[0] = keyValue(DISPLAY_TYPE_KEY, stringWrap(displayType));
    components[1] = keyValue(MAX_VALUE_KEY, maxValue);
    return getBaseAttributeObject(traitType, value, delimit(components));
  }
}

File 20 of 31 : Create3.sol
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;

/**
  @title A library for deploying contracts EIP-3171 style.
  @author Agustin Aguilar <[email protected]>
*/
library Create3 {
  error ErrorCreatingProxy();
  error ErrorCreatingContract();
  error TargetAlreadyExists();

  /**
    @notice The bytecode for a contract that proxies the creation of another contract
    @dev If this code is deployed using CREATE2 it can be used to decouple `creationCode` from the child contract address
  0x67363d3d37363d34f03d5260086018f3:
      0x00  0x67  0x67XXXXXXXXXXXXXXXX  PUSH8 bytecode  0x363d3d37363d34f0
      0x01  0x3d  0x3d                  RETURNDATASIZE  0 0x363d3d37363d34f0
      0x02  0x52  0x52                  MSTORE
      0x03  0x60  0x6008                PUSH1 08        8
      0x04  0x60  0x6018                PUSH1 18        24 8
      0x05  0xf3  0xf3                  RETURN
  0x363d3d37363d34f0:
      0x00  0x36  0x36                  CALLDATASIZE    cds
      0x01  0x3d  0x3d                  RETURNDATASIZE  0 cds
      0x02  0x3d  0x3d                  RETURNDATASIZE  0 0 cds
      0x03  0x37  0x37                  CALLDATACOPY
      0x04  0x36  0x36                  CALLDATASIZE    cds
      0x05  0x3d  0x3d                  RETURNDATASIZE  0 cds
      0x06  0x34  0x34                  CALLVALUE       val 0 cds
      0x07  0xf0  0xf0                  CREATE          addr
  */

  bytes internal constant PROXY_CHILD_BYTECODE =
    hex'67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3';

  //                        KECCAK256_PROXY_CHILD_BYTECODE = keccak256(PROXY_CHILD_BYTECODE);
  bytes32 internal constant KECCAK256_PROXY_CHILD_BYTECODE =
    0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;

  /**
    @notice Returns the size of the code on a given address
    @param _addr Address that may or may not contain code
    @return size of the code on the given `_addr`
  */
  function codeSize(address _addr) internal view returns (uint256 size) {
    assembly {
      size := extcodesize(_addr)
    }
  }

  /**
    @notice Creates a new contract with given `_creationCode` and `_salt`
    @param _salt Salt of the contract creation, resulting address will be derivated from this value only
    @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address
    @return addr of the deployed contract, reverts on error
  */
  function create3(
    bytes32 _salt,
    bytes memory _creationCode
  ) internal returns (address addr) {
    return create3(_salt, _creationCode, 0);
  }

  /**
    @notice Creates a new contract with given `_creationCode` and `_salt`
    @param _salt Salt of the contract creation, resulting address will be derivated from this value only
    @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address
    @param _value In WEI of ETH to be forwarded to child contract
    @return addr of the deployed contract, reverts on error
  */
  function create3(
    bytes32 _salt,
    bytes memory _creationCode,
    uint256 _value
  ) internal returns (address addr) {
    // Creation code
    bytes memory creationCode = PROXY_CHILD_BYTECODE;

    // Get target final address
    addr = addressOf(_salt);
    if (codeSize(addr) != 0) revert TargetAlreadyExists();

    // Create CREATE2 proxy
    address proxy;
    assembly {
      proxy := create2(0, add(creationCode, 32), mload(creationCode), _salt)
    }
    if (proxy == address(0)) revert ErrorCreatingProxy();

    // Call proxy with final init code
    (bool success, ) = proxy.call{value: _value}(_creationCode);
    if (!success || codeSize(addr) == 0) revert ErrorCreatingContract();
  }

  /**
    @notice Computes the resulting address of a contract deployed using address(this) and the given `_salt`
    @param _salt Salt of the contract creation, resulting address will be derivated from this value only
    @return addr of the deployed contract, reverts on error
    @dev The address creation formula is: keccak256(rlp([keccak256(0xff ++ address(this) ++ _salt ++ keccak256(childBytecode))[12:], 0x01]))
  */
  function addressOf(bytes32 _salt) internal view returns (address) {
    address proxy = address(
      uint160(
        uint256(
          keccak256(
            abi.encodePacked(
              hex'ff',
              address(this),
              _salt,
              KECCAK256_PROXY_CHILD_BYTECODE
            )
          )
        )
      )
    );

    return
      address(
        uint160(
          uint256(keccak256(abi.encodePacked(hex'd6_94', proxy, hex'01')))
        )
      );
  }
}

File 21 of 31 : SSTORE2Map.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import './Create3.sol';

import '../bytes/Bytecode.sol';

/**
  @title A write-once key-value storage for storing chunks of data with a lower write & read cost.
  @author Agustin Aguilar <[email protected]>
  Readme: https://github.com/0xsequence/sstore2#readme
*/
library SSTORE2Map {
  error WriteError();

  //                                         keccak256(bytes('@0xSequence.SSTORE2Map.slot'))
  bytes32 private constant SLOT_KEY_PREFIX =
    0xd351a9253491dfef66f53115e9e3afda3b5fdef08a1de6937da91188ec553be5;

  function internalKey(bytes32 _key) internal pure returns (bytes32) {
    // Mutate the key so it doesn't collide
    // if the contract is also using CREATE3 for other things
    return keccak256(abi.encode(SLOT_KEY_PREFIX, _key));
  }

  /**
    @notice Stores `_data` and returns `pointer` as key for later retrieval
    @dev The pointer is a contract address with `_data` as code
    @param _data To be written
    @param _key unique string key for accessing the written data (can only be used once)
    @return pointer Pointer to the written `_data`
  */
  function write(
    string memory _key,
    bytes memory _data
  ) internal returns (address pointer) {
    return write(keccak256(bytes(_key)), _data);
  }

  /**
    @notice Stores `_data` and returns `pointer` as key for later retrieval
    @dev The pointer is a contract address with `_data` as code
    @param _data to be written
    @param _key unique bytes32 key for accessing the written data (can only be used once)
    @return pointer Pointer to the written `_data`
  */
  function write(
    bytes32 _key,
    bytes memory _data
  ) internal returns (address pointer) {
    // Append 00 to _data so contract can't be called
    // Build init code
    bytes memory code = Bytecode.creationCodeFor(
      abi.encodePacked(hex'00', _data)
    );

    // Deploy contract using create3
    pointer = Create3.create3(internalKey(_key), code);
  }

  /**
    @notice Reads the contents for a given `_key`, it maps to a contract code as data, skips the first byte
    @dev The function is intended for reading pointers first written by `write`
    @param _key string key that constains the data
    @return data read from contract associated with `_key`
  */
  function read(string memory _key) internal view returns (bytes memory) {
    return read(keccak256(bytes(_key)));
  }

  /**
    @notice Reads the contents for a given `_key`, it maps to a contract code as data, skips the first byte
    @dev The function is intended for reading pointers first written by `write`
    @param _key string key that constains the data
    @param _start number of bytes to skip
    @return data read from contract associated with `_key`
  */
  function read(
    string memory _key,
    uint256 _start
  ) internal view returns (bytes memory) {
    return read(keccak256(bytes(_key)), _start);
  }

  /**
    @notice Reads the contents for a given `_key`, it maps to a contract code as data, skips the first byte
    @dev The function is intended for reading pointers first written by `write`
    @param _key string key that constains the data
    @param _start number of bytes to skip
    @param _end index before which to end extraction
    @return data read from contract associated with `_key`
  */
  function read(
    string memory _key,
    uint256 _start,
    uint256 _end
  ) internal view returns (bytes memory) {
    return read(keccak256(bytes(_key)), _start, _end);
  }

  /**
    @notice Reads the contents for a given `_key`, it maps to a contract code as data, skips the first byte
    @dev The function is intended for reading pointers first written by `write`
    @param _key bytes32 key that constains the data
    @return data read from contract associated with `_key`
  */
  function read(bytes32 _key) internal view returns (bytes memory) {
    return
      Bytecode.codeAt(
        Create3.addressOf(internalKey(_key)),
        1,
        type(uint256).max
      );
  }

  /**
    @notice Reads the contents for a given `_key`, it maps to a contract code as data, skips the first byte
    @dev The function is intended for reading pointers first written by `write`
    @param _key bytes32 key that constains the data
    @param _start number of bytes to skip
    @return data read from contract associated with `_key`
  */
  function read(
    bytes32 _key,
    uint256 _start
  ) internal view returns (bytes memory) {
    return
      Bytecode.codeAt(
        Create3.addressOf(internalKey(_key)),
        _start + 1,
        type(uint256).max
      );
  }

  /**
    @notice Reads the contents for a given `_key`, it maps to a contract code as data, skips the first byte
    @dev The function is intended for reading pointers first written by `write`
    @param _key bytes32 key that constains the data
    @param _start number of bytes to skip
    @param _end index before which to end extraction
    @return data read from contract associated with `_key`
  */
  function read(
    bytes32 _key,
    uint256 _start,
    uint256 _end
  ) internal view returns (bytes memory) {
    return
      Bytecode.codeAt(
        Create3.addressOf(internalKey(_key)),
        _start + 1,
        _end + 1
      );
  }
}

File 22 of 31 : UnicodeUtils.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

import './bytes/DynamicBuffer.sol';

library UnicodeUtils {
  bytes16 private constant _SYMBOLS = '0123456789abcdef';

  // not designed for use in actual txns and for long strings
  function getUrlSafeUnicode(
    bytes memory unicodeStr
  ) public pure returns (bytes memory safeStr) {
    uint size = unicodeStr.length * 3;
    safeStr = new bytes(size);
    for (uint i = 0; i < unicodeStr.length; ++i) {
      uint idx = i * 3;
      safeStr[idx] = '%';
      safeStr[idx + 1] = _SYMBOLS[uint8(unicodeStr[i] >> 4) & 0xf];
      safeStr[idx + 2] = _SYMBOLS[uint8(unicodeStr[i]) & 0xf];
    }
  }
}

File 23 of 31 : OnchainMetadataUtils.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/Base64.sol';
import '../interfaces/IScriptyBuilder.sol';

library OnchainMetadataUtils {
  // commonly used eth fs assets
  string public constant POB_STUDIO_SIGNATURE = 'POB_signature_white-min.png';

  string public constant PREVIEW_SERVICE_URL =
    'https://nft-preview.pob.studio/api?';

  bytes public constant URL_SAFE_SCRIPT_TAG = '%253Cscript%253E'; // <script>
  bytes public constant URL_SAFE_SCRIPT_END_TAG = '%253C%252Fscript%253E'; // </script>

  uint public constant URL_SAFE_BUFFER_SIZE = 96;

  uint public constant URL_SAFE_INLINE_SCRIPT_WRAP_BUFFER_SIZE = 16 + 21;

  uint public constant URL_SAFE_BASE64_SCRIPT_WRAP_BUFFER_SIZE = 73 + 31;

  uint public constant URL_SAFE_POB_SIGNATURE_BUFFER_SIZE = 5436;

  function toHexString(
    bytes memory buffer
  ) public pure returns (string memory) {
    // Fixed buffer size for hexadecimal convertion
    bytes memory converted = new bytes(buffer.length * 2);

    bytes memory _base = '0123456789abcdef';

    for (uint256 i = 0; i < buffer.length; i++) {
      converted[i * 2] = _base[uint8(buffer[i]) / _base.length];
      converted[i * 2 + 1] = _base[uint8(buffer[i]) % _base.length];
    }

    return string(abi.encodePacked('0x', converted));
  }

  function getPreviewImageUrl(
    address component,
    uint chainId,
    bytes memory props,
    uint width,
    uint height
  ) public view returns (string memory url) {
    return
      string(
        abi.encodePacked(
          PREVIEW_SERVICE_URL,
          'component=',
          Strings.toHexString(component),
          '&chainId=',
          Strings.toString(chainId),
          '&props=',
          toHexString(props),
          '&width=',
          Strings.toString(width),
          '&height=',
          Strings.toString(height),
          '&blockNumber=',
          Strings.toString(block.number)
        )
      );
  }

  function getPobStudioSignatureRequest(
    address ethfsStorage
  ) public pure returns (WrappedScriptRequest memory request) {
    request.name = POB_STUDIO_SIGNATURE;
    request.contractAddress = ethfsStorage;
    request
      .wrapPrefix = '%253Cscript%253Evar%2520signature%253D%2522data%253Aimage%252Fpng%253Bbase64%252C';
    request.wrapSuffix = '%2522%253B%253C%252Fscript%253E';
    request.wrapType = 4;
  }

  function sizeForBase64Encoding(uint256 value) public pure returns (uint256) {
    unchecked {
      return 4 * ((value + 2) / 3);
    }
  }

  enum NftAttributeDisplayType {
    NONE,
    NUMBER,
    BOOST_NUMBER,
    DATE,
    BOOST_PERCENTAGE
  }

  struct NftAttribute {
    NftAttributeDisplayType displayType;
    bytes traitType;
    bytes value;
    bool isValueStringWrapped;
  }

  function getUrlSafeNftAttributes(
    NftAttribute[] memory attributes
  ) public pure returns (bytes memory encodedAttributes) {
    for (uint i = 0; i < attributes.length; ++i) {
      NftAttribute memory attr = attributes[i];
      bytes memory prefix = '%7B%22trait_type%22%3A%22';
      if (attr.displayType == NftAttributeDisplayType.NUMBER) {
        prefix = '%7B%22display_type%22%3A%20%22number%22%2C%22trait_type%22%3A%22';
      } else if (attr.displayType == NftAttributeDisplayType.BOOST_NUMBER) {
        prefix = '%7B%22display_type%22%3A%20%22boost_number%22%2C%22trait_type%22%3A%22';
      } else if (attr.displayType == NftAttributeDisplayType.DATE) {
        prefix = '%7B%22display_type%22%3A%20%22date%22%2C%22trait_type%22%3A%22';
      } else if (attr.displayType == NftAttributeDisplayType.BOOST_PERCENTAGE) {
        prefix = '%7B%22display_type%22%3A%20%22boost_percentage%22%2C%22trait_type%22%3A%22';
      }
      encodedAttributes = abi.encodePacked(
        encodedAttributes,
        prefix,
        attr.traitType,
        '%22%2C%22value%22%3A',
        attr.isValueStringWrapped ? '%22' : '',
        attr.value,
        attr.isValueStringWrapped ? '%22' : '',
        '%7D',
        i != attributes.length - 1 ? '%2C' : ''
      );
    }
  }
}

File 24 of 31 : IERC721CLogic.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

interface IERC721CLogic {
  function supportsInterface(bytes4 interfaceId) external view returns (bool);

  function contractURI() external view returns (string memory);

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

File 25 of 31 : MultiRoleAuthority.sol
// SPDX-License-Identifier: CC0-1.0
// Source: https://github.com/tubby-cats/dual-ownership-nft
pragma solidity ^0.8.4;

import '@openzeppelin/contracts/utils/Context.sol';

error CallerNotAdmin();
error CallerNotOwner();

abstract contract MultiRoleAuthorityBase is Context {
  bytes32 public constant MULTI_ROLE_AUTHORITY =
    keccak256('com.pob.MultiRoleAuthority');

  event OwnershipTransferred(
    address indexed previousOwner,
    address indexed newOwner
  );
  event AdminTransferred(
    address indexed previousAdmin,
    address indexed newAdmin
  );

  struct MultiRoleAuthorityStorage {
    address owner;
    address admin;
  }

  function _multiRoleAuthorityStorage()
    internal
    pure
    returns (MultiRoleAuthorityStorage storage state)
  {
    bytes32 position = MULTI_ROLE_AUTHORITY;
    assembly {
      state.slot := position
    }
  }

  constructor() {}

  modifier onlyOwner() {
    if (_multiRoleAuthorityStorage().owner != _msgSender()) {
      revert CallerNotOwner();
    }
    _;
  }

  modifier onlyAdmin() {
    if (_multiRoleAuthorityStorage().admin != _msgSender()) {
      revert CallerNotAdmin();
    }
    _;
  }
}

abstract contract MultiRoleAuthority is Context, MultiRoleAuthorityBase {
  constructor(address admin_) {
    _transferOwnership(admin_);
    _transferAdmin(admin_);
  }

  function owner() public view virtual returns (address) {
    return _multiRoleAuthorityStorage().owner;
  }

  function _transferOwnership(address newOwner) internal virtual {
    MultiRoleAuthorityStorage storage state = _multiRoleAuthorityStorage();
    address oldOwner = state.owner;
    state.owner = newOwner;
    emit OwnershipTransferred(oldOwner, newOwner);
  }

  function admin() public view returns (address) {
    return _multiRoleAuthorityStorage().admin;
  }

  function transferAdmin(address newAdmin) public onlyAdmin {
    _transferAdmin(newAdmin);
  }

  function _transferAdmin(address newAdmin) internal virtual {
    MultiRoleAuthorityStorage storage state = _multiRoleAuthorityStorage();
    address oldAdmin = state.admin;
    state.admin = newAdmin;
    emit AdminTransferred(oldAdmin, newAdmin);
  }

  function transferLowerOwnership(address newOwner) public onlyAdmin {
    _transferOwnership(newOwner);
  }
}

File 26 of 31 : ERC721A.sol
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs

pragma solidity ^0.8.4;

library ERC721AStorage {
  // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
  struct TokenApprovalRef {
    address value;
  }

  struct Layout {
    // =============================================================
    //                            STORAGE
    // =============================================================

    // The next token ID to be minted.
    uint256 _currentIndex;
    // The number of tokens burned.
    uint256 _burnCounter;
    // Token name
    string _name;
    // Token symbol
    string _symbol;
    // Mapping from token ID to ownership details
    // An empty struct value does not necessarily mean the token is unowned.
    // See {_packedOwnershipOf} implementation for details.
    //
    // Bits Layout:
    // - [0..159]   `addr`
    // - [160..223] `startTimestamp`
    // - [224]      `burned`
    // - [225]      `nextInitialized`
    // - [232..255] `extraData`
    mapping(uint256 => uint256) _packedOwnerships;
    // Mapping owner address to address data.
    //
    // Bits Layout:
    // - [0..63]    `balance`
    // - [64..127]  `numberMinted`
    // - [128..191] `numberBurned`
    // - [192..255] `aux`
    mapping(address => uint256) _packedAddressData;
    // Mapping from token ID to approved address.
    mapping(uint256 => ERC721AStorage.TokenApprovalRef) _tokenApprovals;
    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) _operatorApprovals;
  }

  bytes32 internal constant STORAGE_SLOT =
    keccak256('ERC721A.contracts.storage.ERC721A');

  function layout() internal pure returns (Layout storage l) {
    bytes32 slot = STORAGE_SLOT;
    assembly {
      l.slot := slot
    }
  }
}

/**
 * @dev Interface of ERC721A.
 */
interface IERC721A {
  /**
   * The caller must own the token or be an approved operator.
   */
  error ApprovalCallerNotOwnerNorApproved();

  /**
   * The token does not exist.
   */
  error ApprovalQueryForNonexistentToken();

  /**
   * Cannot query the balance for the zero address.
   */
  error BalanceQueryForZeroAddress();

  /**
   * Cannot mint to the zero address.
   */
  error MintToZeroAddress();

  /**
   * The quantity of tokens minted must be more than zero.
   */
  error MintZeroQuantity();

  /**
   * The token does not exist.
   */
  error OwnerQueryForNonexistentToken();

  /**
   * The caller must own the token or be an approved operator.
   */
  error TransferCallerNotOwnerNorApproved();

  /**
   * The token must be owned by `from`.
   */
  error TransferFromIncorrectOwner();

  /**
   * Cannot safely transfer to a contract that does not implement the
   * ERC721Receiver interface.
   */
  error TransferToNonERC721ReceiverImplementer();

  /**
   * Cannot transfer to the zero address.
   */
  error TransferToZeroAddress();

  /**
   * The token does not exist.
   */
  error URIQueryForNonexistentToken();

  /**
   * The `quantity` minted with ERC2309 exceeds the safety limit.
   */
  error MintERC2309QuantityExceedsLimit();

  /**
   * The `extraData` cannot be set on an unintialized ownership slot.
   */
  error OwnershipNotInitializedForExtraData();

  // =============================================================
  //                            STRUCTS
  // =============================================================

  struct TokenOwnership {
    // The address of the owner.
    address addr;
    // Stores the start time of ownership with minimal overhead for tokenomics.
    uint64 startTimestamp;
    // Whether the token has been burned.
    bool burned;
    // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
    uint24 extraData;
  }

  // =============================================================
  //                         TOKEN COUNTERS
  // =============================================================

  /**
   * @dev Returns the total number of tokens in existence.
   * Burned tokens will reduce the count.
   * To get the total number of tokens minted, please see {_totalMinted}.
   */
  function totalSupply() external view returns (uint256);

  // =============================================================
  //                            IERC165
  // =============================================================

  /**
   * @dev Returns true if this contract implements the interface defined by
   * `interfaceId`. See the corresponding
   * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
   * to learn more about how these ids are created.
   *
   * This function call must use less than 30000 gas.
   */
  function supportsInterface(bytes4 interfaceId) external view returns (bool);

  // =============================================================
  //                            IERC721
  // =============================================================

  /**
   * @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`,
   * 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 be 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,
    bytes calldata data
  ) external payable;

  /**
   * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
   */
  function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId
  ) external payable;

  /**
   * @dev Transfers `tokenId` from `from` to `to`.
   *
   * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
   * whenever possible.
   *
   * 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 payable;

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

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

  // =============================================================
  //                        IERC721Metadata
  // =============================================================

  /**
   * @dev Returns the token collection name.
   */
  function name() external view returns (string memory);

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

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

  // =============================================================
  //                           IERC2309
  // =============================================================

  /**
   * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
   * (inclusive) is transferred from `from` to `to`, as defined in the
   * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
   *
   * See {_mintERC2309} for more details.
   */
  event ConsecutiveTransfer(
    uint256 indexed fromTokenId,
    uint256 toTokenId,
    address indexed from,
    address indexed to
  );
}

/**
 * @dev Interface of ERC721 token receiver.
 */
interface ERC721A__IERC721Receiver {
  function onERC721Received(
    address operator,
    address from,
    uint256 tokenId,
    bytes calldata data
  ) external returns (bytes4);
}

/**
 * @title ERC721A
 *
 * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
 * Non-Fungible Token Standard, including the Metadata extension.
 * Optimized for lower gas during batch mints.
 *
 * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
 * starting from `_startTokenId()`.
 *
 * Assumptions:
 *
 * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
 * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
 */
contract ERC721A is IERC721A {
  using ERC721AStorage for ERC721AStorage.Layout;

  // =============================================================
  //                           CONSTANTS
  // =============================================================

  // Mask of an entry in packed address data.
  uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;

  // The bit position of `numberMinted` in packed address data.
  uint256 private constant _BITPOS_NUMBER_MINTED = 64;

  // The bit position of `numberBurned` in packed address data.
  uint256 private constant _BITPOS_NUMBER_BURNED = 128;

  // The bit position of `aux` in packed address data.
  uint256 private constant _BITPOS_AUX = 192;

  // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
  uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;

  // The bit position of `startTimestamp` in packed ownership.
  uint256 private constant _BITPOS_START_TIMESTAMP = 160;

  // The bit mask of the `burned` bit in packed ownership.
  uint256 private constant _BITMASK_BURNED = 1 << 224;

  // The bit position of the `nextInitialized` bit in packed ownership.
  uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;

  // The bit mask of the `nextInitialized` bit in packed ownership.
  uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;

  // The bit position of `extraData` in packed ownership.
  uint256 private constant _BITPOS_EXTRA_DATA = 232;

  // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
  uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;

  // The mask of the lower 160 bits for addresses.
  uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;

  // The maximum `quantity` that can be minted with {_mintERC2309}.
  // This limit is to prevent overflows on the address data entries.
  // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
  // is required to cause an overflow, which is unrealistic.
  uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;

  // The `Transfer` event signature is given by:
  // `keccak256(bytes("Transfer(address,address,uint256)"))`.
  bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
    0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

  // =============================================================
  //                          CONSTRUCTOR
  // =============================================================

  constructor(string memory name_, string memory symbol_) {
    ERC721AStorage.layout()._name = name_;
    ERC721AStorage.layout()._symbol = symbol_;
    ERC721AStorage.layout()._currentIndex = _startTokenId();
  }

  // =============================================================
  //                   TOKEN COUNTING OPERATIONS
  // =============================================================

  /**
   * @dev Returns the starting token ID.
   * To change the starting token ID, please override this function.
   */
  function _startTokenId() internal view virtual returns (uint256) {
    return 0;
  }

  /**
   * @dev Returns the next token ID to be minted.
   */
  function _nextTokenId() internal view virtual returns (uint256) {
    return ERC721AStorage.layout()._currentIndex;
  }

  /**
   * @dev Returns the total number of tokens in existence.
   * Burned tokens will reduce the count.
   * To get the total number of tokens minted, please see {_totalMinted}.
   */
  function totalSupply() public view virtual override returns (uint256) {
    // Counter underflow is impossible as _burnCounter cannot be incremented
    // more than `_currentIndex - _startTokenId()` times.
    unchecked {
      return
        ERC721AStorage.layout()._currentIndex -
        ERC721AStorage.layout()._burnCounter -
        _startTokenId();
    }
  }

  /**
   * @dev Returns the total amount of tokens minted in the contract.
   */
  function _totalMinted() internal view virtual returns (uint256) {
    // Counter underflow is impossible as `_currentIndex` does not decrement,
    // and it is initialized to `_startTokenId()`.
    unchecked {
      return ERC721AStorage.layout()._currentIndex - _startTokenId();
    }
  }

  /**
   * @dev Returns the total number of tokens burned.
   */
  function _totalBurned() internal view virtual returns (uint256) {
    return ERC721AStorage.layout()._burnCounter;
  }

  // =============================================================
  //                    ADDRESS DATA OPERATIONS
  // =============================================================

  /**
   * @dev Returns the number of tokens in `owner`'s account.
   */
  function balanceOf(
    address owner
  ) public view virtual override returns (uint256) {
    if (owner == address(0)) _revert(BalanceQueryForZeroAddress.selector);
    return
      ERC721AStorage.layout()._packedAddressData[owner] &
      _BITMASK_ADDRESS_DATA_ENTRY;
  }

  /**
   * Returns the number of tokens minted by `owner`.
   */
  function _numberMinted(address owner) internal view returns (uint256) {
    return
      (ERC721AStorage.layout()._packedAddressData[owner] >>
        _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
  }

  /**
   * Returns the number of tokens burned by or on behalf of `owner`.
   */
  function _numberBurned(address owner) internal view returns (uint256) {
    return
      (ERC721AStorage.layout()._packedAddressData[owner] >>
        _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
  }

  /**
   * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
   */
  function _getAux(address owner) internal view returns (uint64) {
    return
      uint64(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_AUX);
  }

  /**
   * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
   * If there are multiple variables, please pack them into a uint64.
   */
  function _setAux(address owner, uint64 aux) internal virtual {
    uint256 packed = ERC721AStorage.layout()._packedAddressData[owner];
    uint256 auxCasted;
    // Cast `aux` with assembly to avoid redundant masking.
    assembly {
      auxCasted := aux
    }
    packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
    ERC721AStorage.layout()._packedAddressData[owner] = packed;
  }

  // =============================================================
  //                            IERC165
  // =============================================================

  /**
   * @dev Returns true if this contract implements the interface defined by
   * `interfaceId`. See the corresponding
   * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
   * to learn more about how these ids are created.
   *
   * This function call must use less than 30000 gas.
   */
  function supportsInterface(
    bytes4 interfaceId
  ) public view virtual override returns (bool) {
    // The interface IDs are constants representing the first 4 bytes
    // of the XOR of all function selectors in the interface.
    // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
    // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
    return
      interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
      interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
      interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
  }

  // =============================================================
  //                        IERC721Metadata
  // =============================================================

  /**
   * @dev Returns the token collection name.
   */
  function name() public view virtual override returns (string memory) {
    return ERC721AStorage.layout()._name;
  }

  /**
   * @dev Returns the token collection symbol.
   */
  function symbol() public view virtual override returns (string memory) {
    return ERC721AStorage.layout()._symbol;
  }

  /**
   * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
   */
  function tokenURI(
    uint256 tokenId
  ) public view virtual override returns (string memory) {
    if (!_exists(tokenId)) _revert(URIQueryForNonexistentToken.selector);
    return '';
  }

  // =============================================================
  //                     OWNERSHIPS OPERATIONS
  // =============================================================

  /**
   * @dev Returns the owner of the `tokenId` token.
   *
   * Requirements:
   *
   * - `tokenId` must exist.
   */
  function ownerOf(
    uint256 tokenId
  ) public view virtual override returns (address) {
    return address(uint160(_packedOwnershipOf(tokenId)));
  }

  /**
   * @dev Gas spent here starts off proportional to the maximum mint batch size.
   * It gradually moves to O(1) as tokens get transferred around over time.
   */
  function _ownershipOf(
    uint256 tokenId
  ) internal view virtual returns (TokenOwnership memory) {
    return _unpackedOwnership(_packedOwnershipOf(tokenId));
  }

  /**
   * @dev Returns the unpacked `TokenOwnership` struct at `index`.
   */
  function _ownershipAt(
    uint256 index
  ) internal view virtual returns (TokenOwnership memory) {
    return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]);
  }

  /**
   * @dev Returns whether the ownership slot at `index` is initialized.
   * An uninitialized slot does not necessarily mean that the slot has no owner.
   */
  function _ownershipIsInitialized(
    uint256 index
  ) internal view virtual returns (bool) {
    return ERC721AStorage.layout()._packedOwnerships[index] != 0;
  }

  /**
   * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
   */
  function _initializeOwnershipAt(uint256 index) internal virtual {
    if (ERC721AStorage.layout()._packedOwnerships[index] == 0) {
      ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(
        index
      );
    }
  }

  /**
   * Returns the packed ownership data of `tokenId`.
   */
  function _packedOwnershipOf(
    uint256 tokenId
  ) private view returns (uint256 packed) {
    if (_startTokenId() <= tokenId) {
      packed = ERC721AStorage.layout()._packedOwnerships[tokenId];
      // If the data at the starting slot does not exist, start the scan.
      if (packed == 0) {
        if (tokenId >= ERC721AStorage.layout()._currentIndex)
          _revert(OwnerQueryForNonexistentToken.selector);
        // Invariant:
        // There will always be an initialized ownership slot
        // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
        // before an unintialized ownership slot
        // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
        // Hence, `tokenId` will not underflow.
        //
        // We can directly compare the packed value.
        // If the address is zero, packed will be zero.
        for (;;) {
          unchecked {
            packed = ERC721AStorage.layout()._packedOwnerships[--tokenId];
          }
          if (packed == 0) continue;
          if (packed & _BITMASK_BURNED == 0) return packed;
          // Otherwise, the token is burned, and we must revert.
          // This handles the case of batch burned tokens, where only the burned bit
          // of the starting slot is set, and remaining slots are left uninitialized.
          _revert(OwnerQueryForNonexistentToken.selector);
        }
      }
      // Otherwise, the data exists and we can skip the scan.
      // This is possible because we have already achieved the target condition.
      // This saves 2143 gas on transfers of initialized tokens.
      // If the token is not burned, return `packed`. Otherwise, revert.
      if (packed & _BITMASK_BURNED == 0) return packed;
    }
    _revert(OwnerQueryForNonexistentToken.selector);
  }

  /**
   * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
   */
  function _unpackedOwnership(
    uint256 packed
  ) private pure returns (TokenOwnership memory ownership) {
    ownership.addr = address(uint160(packed));
    ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
    ownership.burned = packed & _BITMASK_BURNED != 0;
    ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
  }

  /**
   * @dev Packs ownership data into a single uint256.
   */
  function _packOwnershipData(
    address owner,
    uint256 flags
  ) private view returns (uint256 result) {
    assembly {
      // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
      owner := and(owner, _BITMASK_ADDRESS)
      // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
      result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
    }
  }

  /**
   * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
   */
  function _nextInitializedFlag(
    uint256 quantity
  ) private pure returns (uint256 result) {
    // For branchless setting of the `nextInitialized` flag.
    assembly {
      // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
      result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
    }
  }

  // =============================================================
  //                      APPROVAL OPERATIONS
  // =============================================================

  /**
   * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
   *
   * Requirements:
   *
   * - The caller must own the token or be an approved operator.
   */
  function approve(
    address to,
    uint256 tokenId
  ) public payable virtual override {
    _approve(to, tokenId, true);
  }

  /**
   * @dev Returns the account approved for `tokenId` token.
   *
   * Requirements:
   *
   * - `tokenId` must exist.
   */
  function getApproved(
    uint256 tokenId
  ) public view virtual override returns (address) {
    if (!_exists(tokenId)) _revert(ApprovalQueryForNonexistentToken.selector);

    return ERC721AStorage.layout()._tokenApprovals[tokenId].value;
  }

  /**
   * @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
  ) public virtual override {
    ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][
      operator
    ] = approved;
    emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
  }

  /**
   * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
   *
   * See {setApprovalForAll}.
   */
  function isApprovedForAll(
    address owner,
    address operator
  ) public view virtual override returns (bool) {
    return ERC721AStorage.layout()._operatorApprovals[owner][operator];
  }

  /**
   * @dev Returns whether `tokenId` exists.
   *
   * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
   *
   * Tokens start existing when they are minted. See {_mint}.
   */
  function _exists(
    uint256 tokenId
  ) internal view virtual returns (bool result) {
    if (_startTokenId() <= tokenId) {
      if (tokenId < ERC721AStorage.layout()._currentIndex) {
        uint256 packed;
        while (
          (packed = ERC721AStorage.layout()._packedOwnerships[tokenId]) == 0
        ) --tokenId;
        result = packed & _BITMASK_BURNED == 0;
      }
    }
  }

  /**
   * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
   */
  function _isSenderApprovedOrOwner(
    address approvedAddress,
    address owner,
    address msgSender
  ) private pure returns (bool result) {
    assembly {
      // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
      owner := and(owner, _BITMASK_ADDRESS)
      // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
      msgSender := and(msgSender, _BITMASK_ADDRESS)
      // `msgSender == owner || msgSender == approvedAddress`.
      result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
    }
  }

  /**
   * @dev Returns the storage slot and value for the approved address of `tokenId`.
   */
  function _getApprovedSlotAndAddress(
    uint256 tokenId
  )
    private
    view
    returns (uint256 approvedAddressSlot, address approvedAddress)
  {
    ERC721AStorage.TokenApprovalRef storage tokenApproval = ERC721AStorage
      .layout()
      ._tokenApprovals[tokenId];
    // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
    assembly {
      approvedAddressSlot := tokenApproval.slot
      approvedAddress := sload(approvedAddressSlot)
    }
  }

  // =============================================================
  //                      TRANSFER OPERATIONS
  // =============================================================

  /**
   * @dev Transfers `tokenId` from `from` to `to`.
   *
   * 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
  ) public payable virtual override {
    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

    // Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean.
    from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));

    if (address(uint160(prevOwnershipPacked)) != from)
      _revert(TransferFromIncorrectOwner.selector);

    (
      uint256 approvedAddressSlot,
      address approvedAddress
    ) = _getApprovedSlotAndAddress(tokenId);

    // The nested ifs save around 20+ gas over a compound boolean condition.
    if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
      if (!isApprovedForAll(from, _msgSenderERC721A()))
        _revert(TransferCallerNotOwnerNorApproved.selector);

    _beforeTokenTransfers(from, to, tokenId, 1);

    // Clear approvals from the previous owner.
    assembly {
      if approvedAddress {
        // This is equivalent to `delete _tokenApprovals[tokenId]`.
        sstore(approvedAddressSlot, 0)
      }
    }

    // Underflow of the sender's balance is impossible because we check for
    // ownership above and the recipient's balance can't realistically overflow.
    // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
    unchecked {
      // We can directly increment and decrement the balances.
      --ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`.
      ++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`.

      // Updates:
      // - `address` to the next owner.
      // - `startTimestamp` to the timestamp of transfering.
      // - `burned` to `false`.
      // - `nextInitialized` to `true`.
      ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
        to,
        _BITMASK_NEXT_INITIALIZED |
          _nextExtraData(from, to, prevOwnershipPacked)
      );

      // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
      if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
        uint256 nextTokenId = tokenId + 1;
        // If the next slot's address is zero and not burned (i.e. packed value is zero).
        if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
          // If the next slot is within bounds.
          if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
            // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
            ERC721AStorage.layout()._packedOwnerships[
              nextTokenId
            ] = prevOwnershipPacked;
          }
        }
      }
    }

    // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
    uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
    assembly {
      // Emit the `Transfer` event.
      log4(
        0, // Start of data (0, since no data).
        0, // End of data (0, since no data).
        _TRANSFER_EVENT_SIGNATURE, // Signature.
        from, // `from`.
        toMasked, // `to`.
        tokenId // `tokenId`.
      )
    }
    if (toMasked == 0) _revert(TransferToZeroAddress.selector);

    _afterTokenTransfers(from, to, tokenId, 1);
  }

  /**
   * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
   */
  function safeTransferFrom(
    address from,
    address to,
    uint256 tokenId
  ) public payable virtual override {
    safeTransferFrom(from, to, tokenId, '');
  }

  /**
   * @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 memory _data
  ) public payable virtual override {
    transferFrom(from, to, tokenId);
    if (to.code.length != 0)
      if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
        _revert(TransferToNonERC721ReceiverImplementer.selector);
      }
  }

  /**
   * @dev Hook that is called before a set of serially-ordered token IDs
   * are about to be transferred. This includes minting.
   * And also called before burning one token.
   *
   * `startTokenId` - the first token ID to be transferred.
   * `quantity` - the amount to be transferred.
   *
   * Calling conditions:
   *
   * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
   * transferred to `to`.
   * - When `from` is zero, `tokenId` will be minted for `to`.
   * - When `to` is zero, `tokenId` will be burned by `from`.
   * - `from` and `to` are never both zero.
   */
  function _beforeTokenTransfers(
    address from,
    address to,
    uint256 startTokenId,
    uint256 quantity
  ) internal virtual {}

  /**
   * @dev Hook that is called after a set of serially-ordered token IDs
   * have been transferred. This includes minting.
   * And also called after one token has been burned.
   *
   * `startTokenId` - the first token ID to be transferred.
   * `quantity` - the amount to be transferred.
   *
   * Calling conditions:
   *
   * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
   * transferred to `to`.
   * - When `from` is zero, `tokenId` has been minted for `to`.
   * - When `to` is zero, `tokenId` has been burned by `from`.
   * - `from` and `to` are never both zero.
   */
  function _afterTokenTransfers(
    address from,
    address to,
    uint256 startTokenId,
    uint256 quantity
  ) internal virtual {}

  /**
   * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
   *
   * `from` - Previous owner of the given token ID.
   * `to` - Target address that will receive the token.
   * `tokenId` - Token ID to be transferred.
   * `_data` - Optional data to send along with the call.
   *
   * Returns whether the call correctly returned the expected magic value.
   */
  function _checkContractOnERC721Received(
    address from,
    address to,
    uint256 tokenId,
    bytes memory _data
  ) private returns (bool) {
    try
      ERC721A__IERC721Receiver(to).onERC721Received(
        _msgSenderERC721A(),
        from,
        tokenId,
        _data
      )
    returns (bytes4 retval) {
      return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
    } catch (bytes memory reason) {
      if (reason.length == 0) {
        _revert(TransferToNonERC721ReceiverImplementer.selector);
      }
      assembly {
        revert(add(32, reason), mload(reason))
      }
    }
  }

  // =============================================================
  //                        MINT OPERATIONS
  // =============================================================

  /**
   * @dev Mints `quantity` tokens and transfers them to `to`.
   *
   * Requirements:
   *
   * - `to` cannot be the zero address.
   * - `quantity` must be greater than 0.
   *
   * Emits a {Transfer} event for each mint.
   */
  function _mint(address to, uint256 quantity) internal virtual {
    uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
    if (quantity == 0) _revert(MintZeroQuantity.selector);

    _beforeTokenTransfers(address(0), to, startTokenId, quantity);

    // Overflows are incredibly unrealistic.
    // `balance` and `numberMinted` have a maximum limit of 2**64.
    // `tokenId` has a maximum limit of 2**256.
    unchecked {
      // Updates:
      // - `address` to the owner.
      // - `startTimestamp` to the timestamp of minting.
      // - `burned` to `false`.
      // - `nextInitialized` to `quantity == 1`.
      ERC721AStorage.layout()._packedOwnerships[
        startTokenId
      ] = _packOwnershipData(
        to,
        _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
      );

      // Updates:
      // - `balance += quantity`.
      // - `numberMinted += quantity`.
      //
      // We can directly add to the `balance` and `numberMinted`.
      ERC721AStorage.layout()._packedAddressData[to] +=
        quantity *
        ((1 << _BITPOS_NUMBER_MINTED) | 1);

      // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
      uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;

      if (toMasked == 0) _revert(MintToZeroAddress.selector);

      uint256 end = startTokenId + quantity;
      uint256 tokenId = startTokenId;

      do {
        assembly {
          // Emit the `Transfer` event.
          log4(
            0, // Start of data (0, since no data).
            0, // End of data (0, since no data).
            _TRANSFER_EVENT_SIGNATURE, // Signature.
            0, // `address(0)`.
            toMasked, // `to`.
            tokenId // `tokenId`.
          )
        }
        // The `!=` check ensures that large values of `quantity`
        // that overflows uint256 will make the loop run out of gas.
      } while (++tokenId != end);

      ERC721AStorage.layout()._currentIndex = end;
    }
    _afterTokenTransfers(address(0), to, startTokenId, quantity);
  }

  /**
   * @dev Mints `quantity` tokens and transfers them to `to`.
   *
   * This function is intended for efficient minting only during contract creation.
   *
   * It emits only one {ConsecutiveTransfer} as defined in
   * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
   * instead of a sequence of {Transfer} event(s).
   *
   * Calling this function outside of contract creation WILL make your contract
   * non-compliant with the ERC721 standard.
   * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
   * {ConsecutiveTransfer} event is only permissible during contract creation.
   *
   * Requirements:
   *
   * - `to` cannot be the zero address.
   * - `quantity` must be greater than 0.
   *
   * Emits a {ConsecutiveTransfer} event.
   */
  function _mintERC2309(address to, uint256 quantity) internal virtual {
    uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
    if (to == address(0)) _revert(MintToZeroAddress.selector);
    if (quantity == 0) _revert(MintZeroQuantity.selector);
    if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT)
      _revert(MintERC2309QuantityExceedsLimit.selector);

    _beforeTokenTransfers(address(0), to, startTokenId, quantity);

    // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
    unchecked {
      // Updates:
      // - `balance += quantity`.
      // - `numberMinted += quantity`.
      //
      // We can directly add to the `balance` and `numberMinted`.
      ERC721AStorage.layout()._packedAddressData[to] +=
        quantity *
        ((1 << _BITPOS_NUMBER_MINTED) | 1);

      // Updates:
      // - `address` to the owner.
      // - `startTimestamp` to the timestamp of minting.
      // - `burned` to `false`.
      // - `nextInitialized` to `quantity == 1`.
      ERC721AStorage.layout()._packedOwnerships[
        startTokenId
      ] = _packOwnershipData(
        to,
        _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
      );

      emit ConsecutiveTransfer(
        startTokenId,
        startTokenId + quantity - 1,
        address(0),
        to
      );

      ERC721AStorage.layout()._currentIndex = startTokenId + quantity;
    }
    _afterTokenTransfers(address(0), to, startTokenId, quantity);
  }

  /**
   * @dev Safely mints `quantity` tokens and transfers them to `to`.
   *
   * Requirements:
   *
   * - If `to` refers to a smart contract, it must implement
   * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
   * - `quantity` must be greater than 0.
   *
   * See {_mint}.
   *
   * Emits a {Transfer} event for each mint.
   */
  function _safeMint(
    address to,
    uint256 quantity,
    bytes memory _data
  ) internal virtual {
    _mint(to, quantity);

    unchecked {
      if (to.code.length != 0) {
        uint256 end = ERC721AStorage.layout()._currentIndex;
        uint256 index = end - quantity;
        do {
          if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
            _revert(TransferToNonERC721ReceiverImplementer.selector);
          }
        } while (index < end);
        // Reentrancy protection.
        if (ERC721AStorage.layout()._currentIndex != end) _revert(bytes4(0));
      }
    }
  }

  /**
   * @dev Equivalent to `_safeMint(to, quantity, '')`.
   */
  function _safeMint(address to, uint256 quantity) internal virtual {
    _safeMint(to, quantity, '');
  }

  // =============================================================
  //                       APPROVAL OPERATIONS
  // =============================================================

  /**
   * @dev Equivalent to `_approve(to, tokenId, false)`.
   */
  function _approve(address to, uint256 tokenId) internal virtual {
    _approve(to, tokenId, false);
  }

  /**
   * @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:
   *
   * - `tokenId` must exist.
   *
   * Emits an {Approval} event.
   */
  function _approve(
    address to,
    uint256 tokenId,
    bool approvalCheck
  ) internal virtual {
    address owner = ownerOf(tokenId);

    if (approvalCheck && _msgSenderERC721A() != owner)
      if (!isApprovedForAll(owner, _msgSenderERC721A())) {
        _revert(ApprovalCallerNotOwnerNorApproved.selector);
      }

    ERC721AStorage.layout()._tokenApprovals[tokenId].value = to;
    emit Approval(owner, to, tokenId);
  }

  // =============================================================
  //                        BURN OPERATIONS
  // =============================================================

  /**
   * @dev Equivalent to `_burn(tokenId, false)`.
   */
  function _burn(uint256 tokenId) internal virtual {
    _burn(tokenId, false);
  }

  /**
   * @dev Destroys `tokenId`.
   * The approval is cleared when the token is burned.
   *
   * Requirements:
   *
   * - `tokenId` must exist.
   *
   * Emits a {Transfer} event.
   */
  function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

    address from = address(uint160(prevOwnershipPacked));

    (
      uint256 approvedAddressSlot,
      address approvedAddress
    ) = _getApprovedSlotAndAddress(tokenId);

    if (approvalCheck) {
      // The nested ifs save around 20+ gas over a compound boolean condition.
      if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
        if (!isApprovedForAll(from, _msgSenderERC721A()))
          _revert(TransferCallerNotOwnerNorApproved.selector);
    }

    _beforeTokenTransfers(from, address(0), tokenId, 1);

    // Clear approvals from the previous owner.
    assembly {
      if approvedAddress {
        // This is equivalent to `delete _tokenApprovals[tokenId]`.
        sstore(approvedAddressSlot, 0)
      }
    }

    // Underflow of the sender's balance is impossible because we check for
    // ownership above and the recipient's balance can't realistically overflow.
    // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
    unchecked {
      // Updates:
      // - `balance -= 1`.
      // - `numberBurned += 1`.
      //
      // We can directly decrement the balance, and increment the number burned.
      // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
      ERC721AStorage.layout()._packedAddressData[from] +=
        (1 << _BITPOS_NUMBER_BURNED) -
        1;

      // Updates:
      // - `address` to the last owner.
      // - `startTimestamp` to the timestamp of burning.
      // - `burned` to `true`.
      // - `nextInitialized` to `true`.
      ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
        from,
        (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) |
          _nextExtraData(from, address(0), prevOwnershipPacked)
      );

      // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
      if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
        uint256 nextTokenId = tokenId + 1;
        // If the next slot's address is zero and not burned (i.e. packed value is zero).
        if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
          // If the next slot is within bounds.
          if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
            // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
            ERC721AStorage.layout()._packedOwnerships[
              nextTokenId
            ] = prevOwnershipPacked;
          }
        }
      }
    }

    emit Transfer(from, address(0), tokenId);
    _afterTokenTransfers(from, address(0), tokenId, 1);

    // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
    unchecked {
      ERC721AStorage.layout()._burnCounter++;
    }
  }

  // =============================================================
  //                     EXTRA DATA OPERATIONS
  // =============================================================

  /**
   * @dev Directly sets the extra data for the ownership data `index`.
   */
  function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
    uint256 packed = ERC721AStorage.layout()._packedOwnerships[index];
    if (packed == 0) _revert(OwnershipNotInitializedForExtraData.selector);
    uint256 extraDataCasted;
    // Cast `extraData` with assembly to avoid redundant masking.
    assembly {
      extraDataCasted := extraData
    }
    packed =
      (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) |
      (extraDataCasted << _BITPOS_EXTRA_DATA);
    ERC721AStorage.layout()._packedOwnerships[index] = packed;
  }

  /**
   * @dev Called during each token transfer to set the 24bit `extraData` field.
   * Intended to be overridden by the cosumer contract.
   *
   * `previousExtraData` - the value of `extraData` before transfer.
   *
   * Calling conditions:
   *
   * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
   * transferred to `to`.
   * - When `from` is zero, `tokenId` will be minted for `to`.
   * - When `to` is zero, `tokenId` will be burned by `from`.
   * - `from` and `to` are never both zero.
   */
  function _extraData(
    address from,
    address to,
    uint24 previousExtraData
  ) internal view virtual returns (uint24) {}

  /**
   * @dev Returns the next extra data for the packed ownership data.
   * The returned result is shifted into position.
   */
  function _nextExtraData(
    address from,
    address to,
    uint256 prevOwnershipPacked
  ) private view returns (uint256) {
    uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
    return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
  }

  // =============================================================
  //                       OTHER OPERATIONS
  // =============================================================

  /**
   * @dev Returns the message sender (defaults to `msg.sender`).
   *
   * If you are writing GSN compatible contracts, you need to override this function.
   */
  function _msgSenderERC721A() internal view virtual returns (address) {
    return msg.sender;
  }

  /**
   * @dev Converts a uint256 to its ASCII string decimal representation.
   */
  function _toString(
    uint256 value
  ) internal pure virtual returns (string memory str) {
    assembly {
      // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
      // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
      // We will need 1 word for the trailing zeros padding, 1 word for the length,
      // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
      let m := add(mload(0x40), 0xa0)
      // Update the free memory pointer to allocate.
      mstore(0x40, m)
      // Assign the `str` to the end.
      str := sub(m, 0x20)
      // Zeroize the slot after the string.
      mstore(str, 0)

      // Cache the end of the memory to calculate the length later.
      let end := str

      // We write the string from rightmost digit to leftmost digit.
      // The following is essentially a do-while loop that also handles the zero case.
      // prettier-ignore
      for { let temp := value } 1 {} {
                str := sub(str, 1)
                // Write the character to the pointer.
                // The ASCII index of the '0' character is 48.
                mstore8(str, add(48, mod(temp, 10)))
                // Keep dividing `temp` until zero.
                temp := div(temp, 10)
                // prettier-ignore
                if iszero(temp) { break }
            }

      let length := sub(end, str)
      // Move the pointer 32 bytes leftwards to make room for the length.
      str := sub(str, 0x20)
      // Store the length.
      mstore(str, length)
    }
  }

  /**
   * @dev For more efficient reverts.
   */
  function _revert(bytes4 errorSelector) internal pure {
    assembly {
      mstore(0x00, errorSelector)
      revert(0x00, 0x04)
    }
  }
}

File 27 of 31 : ERC721C.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

import './ERC721A.sol';
import '../ownable/MultiRoleAuthority.sol';
import '../interfaces/IERC721CLogic.sol';

error SettingLogicThatIsImmutable();
error FunctionDoesNotExist();

interface IERC721CDelegatedMetadata {
  function delegatedTokenURI(
    uint256 tokenId
  ) external view returns (string memory);
}

abstract contract ERC721C is ERC721A, MultiRoleAuthority {
  uint256 internal constant EIP1967_LOGIC_SLOT =
    0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

  bytes32 internal constant ERC721C_LOGIC = keccak256('com.erc721c.ERC721C');

  event Upgraded(address indexed logic);

  struct ERC721CStorage {
    bool isLogicImmutable;
  }

  constructor(address logic) {
    _setLogic(logic);
  }

  function _erc721cStorage()
    internal
    pure
    returns (ERC721CStorage storage state)
  {
    bytes32 position = ERC721C_LOGIC;
    assembly {
      state.slot := position
    }
  }

  function _setLogic(address logic) internal {
    if (_erc721cStorage().isLogicImmutable)
      revert SettingLogicThatIsImmutable();
    emit Upgraded(logic);
    assembly {
      sstore(EIP1967_LOGIC_SLOT, logic)
    }
  }

  function setLogic(address logic) public onlyAdmin {
    _setLogic(logic);
  }

  function isLogicImmutable() public view returns (bool) {
    return _erc721cStorage().isLogicImmutable;
  }

  function setLogicImmutable() public onlyAdmin {
    _erc721cStorage().isLogicImmutable = true;
  }

  function logicContract() public view returns (address logic_) {
    assembly {
      logic_ := sload(EIP1967_LOGIC_SLOT)
    }
  }

  function supportsInterface(
    bytes4 interfaceId
  ) public view virtual override returns (bool) {
    return
      // no need to delegatecall, basically pure
      IERC721CLogic(logicContract()).supportsInterface(interfaceId) ||
      super.supportsInterface(interfaceId);
  }

  function tokenURI(
    uint256 tokenId
  ) public view virtual override returns (string memory) {
    if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
    return IERC721CDelegatedMetadata(address(this)).delegatedTokenURI(tokenId);
  }

  function delegatedTokenURI(
    // is view but not declared as such - psudo implementation of IERC721CMetadata
    uint256 tokenId
  ) external returns (string memory) {
    (bool success, bytes memory returndata) = logicContract().delegatecall(
      abi.encodeWithSelector(IERC721CLogic.tokenURI.selector, tokenId)
    );
    if (!success) {
      assembly {
        revert(add(returndata, 0x20), mload(returndata))
      }
    }
    return abi.decode(returndata, (string));
  }

  fallback(bytes calldata callData) external returns (bytes memory resultData) {
    bool success;
    (success, resultData) = logicContract().delegatecall(callData);
    if (!success) {
      if (resultData.length > 0) {
        assembly {
          revert(add(resultData, 0x20), mload(resultData))
        }
      } else {
        revert FunctionDoesNotExist();
      }
    }
  }
}

File 28 of 31 : ERC721CMintingBase.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

import './ERC721C.sol';

error EmergencyShutdownInPlace();
error MintingGroupNotActive();
error ExceedsMintingGroupSupply();
error MintingGroupNotTransferrable();
error ExceedsMintingGroupTransferrableSupply();
error SettingMintingGroupThatIsImmutable();
error CallerNotMintingAuthority();

abstract contract ERC721CMintingBase is ERC721C {
  bytes32 internal constant ERC721C_MINTING_BASE =
    keccak256('com.erc721c.ERC721CMintingBase');

  event EmergencyShutdown(bool emergencyShutdown);
  event UpdatedMintingGroup(uint id);
  event TransferredMintingSupply(uint fromId, uint toId, uint quantity);
  event MintedFromGroup(uint id, address to, uint quantity);
  event UpdatedMintingAuthority(address mintingAuthority);

  struct ERC721CMetadataLogicStorage {
    bool emergencyShutdown;
    mapping(uint => MintingGroup) mintingGroups;
  }

  struct MintingGroup {
    address mintingAuthority;
    uint64 supply; // max size of a group is 64 bits
    uint64 numMinted;
    uint40 activeFromTimestamp;
    uint40 endAtTimestamp;
    bool isTransferrable; // dictates if supply can be moved
    bool isImmutable; // dictates if minting parameters can be changed, time stamp + authority
  }

  constructor(MintingGroup[] memory mintingGroups_) {
    for (uint i = 0; i < mintingGroups_.length; ++i) {
      MintingGroup memory group = mintingGroups_[i];
      _ERC721CMintingBaseStorage().mintingGroups[i] = group;
    }
  }

  function _ERC721CMintingBaseStorage()
    internal
    pure
    returns (ERC721CMetadataLogicStorage storage state)
  {
    bytes32 position = ERC721C_MINTING_BASE;
    assembly {
      state.slot := position
    }
  }

  function mintingGroup(uint id) external view returns (MintingGroup memory) {
    return _ERC721CMintingBaseStorage().mintingGroups[id];
  }

  function emergencyShutdown() external view returns (bool) {
    return _ERC721CMintingBaseStorage().emergencyShutdown;
  }

  function setEmergencyShutdown(bool _emergencyShutdown) external onlyAdmin {
    ERC721CMetadataLogicStorage storage state = _ERC721CMintingBaseStorage();
    state.emergencyShutdown = _emergencyShutdown;
    emit EmergencyShutdown(state.emergencyShutdown);
  }

  function setIsImmutable(
    uint _mintingGroupIndex,
    bool _isImmutable
  ) external onlyAdmin onlyNotImmutable(_mintingGroupIndex) {
    MintingGroup storage group = _ERC721CMintingBaseStorage().mintingGroups[
      _mintingGroupIndex
    ];
    group.isImmutable = _isImmutable;
    emit UpdatedMintingGroup(_mintingGroupIndex);
  }

  function setIsTransferrable(
    uint _mintingGroupIndex,
    bool _isTransferrable
  ) external onlyAdmin onlyNotImmutable(_mintingGroupIndex) {
    MintingGroup storage group = _ERC721CMintingBaseStorage().mintingGroups[
      _mintingGroupIndex
    ];
    group.isTransferrable = _isTransferrable;
    emit UpdatedMintingGroup(_mintingGroupIndex);
  }

  function setMintingAuthority(
    uint _mintingGroupIndex,
    address _mintingAuthority
  ) external onlyAdmin onlyNotImmutable(_mintingGroupIndex) {
    MintingGroup storage group = _ERC721CMintingBaseStorage().mintingGroups[
      _mintingGroupIndex
    ];
    group.mintingAuthority = _mintingAuthority;
    emit UpdatedMintingGroup(_mintingGroupIndex);
  }

  function setTimestamp(
    uint _mintingGroupIndex,
    uint40 _activeFromTimestamp,
    uint40 _endAtTimestamp
  ) external onlyAdmin onlyNotImmutable(_mintingGroupIndex) {
    MintingGroup storage group = _ERC721CMintingBaseStorage().mintingGroups[
      _mintingGroupIndex
    ];
    group.activeFromTimestamp = _activeFromTimestamp;
    group.endAtTimestamp = _endAtTimestamp;
    emit UpdatedMintingGroup(_mintingGroupIndex);
  }

  modifier onlyNotImmutable(uint id) {
    MintingGroup storage group = _ERC721CMintingBaseStorage().mintingGroups[id];
    if (group.isImmutable) revert SettingMintingGroupThatIsImmutable();
    _;
  }

  modifier onlyIsActive(uint id) {
    if (_ERC721CMintingBaseStorage().emergencyShutdown)
      revert EmergencyShutdownInPlace();
    ERC721CMintingBase.MintingGroup storage group = _ERC721CMintingBaseStorage()
      .mintingGroups[id];
    if (
      (group.activeFromTimestamp > block.timestamp ||
        group.endAtTimestamp < block.timestamp)
    ) revert MintingGroupNotActive();
    _;
  }

  function _mintFromGroup(address to, uint64 numMints, uint id) internal {
    MintingGroup storage group = _ERC721CMintingBaseStorage().mintingGroups[id];
    unchecked {
      if (group.numMinted + numMints > group.supply) {
        revert ExceedsMintingGroupSupply();
      }
      group.numMinted += numMints;
      _mint(to, numMints);
      emit MintedFromGroup(id, to, numMints);
    }
  }

  function _transferMintGroupSupply(
    uint fromId,
    uint toId,
    uint64 quantity
  ) internal {
    MintingGroup storage fromGroup = _ERC721CMintingBaseStorage().mintingGroups[
      fromId
    ];
    if (!fromGroup.isTransferrable) revert MintingGroupNotTransferrable();
    unchecked {
      if (quantity > fromGroup.supply - fromGroup.numMinted)
        revert ExceedsMintingGroupTransferrableSupply();
      _ERC721CMintingBaseStorage().mintingGroups[toId].supply += quantity;
      fromGroup.supply -= quantity;
      emit TransferredMintingSupply(fromId, toId, quantity);
    }
  }

  function numberMinted(address minter) external view returns (uint256) {
    return _numberMinted(minter);
  }

  function totalMinted() external view returns (uint256) {
    return _totalMinted();
  }

  function nextTokenId() external view returns (uint256) {
    return _nextTokenId();
  }

  modifier onlyMintingAuthority(uint mintingGroupIndex) {
    if (
      _msgSender() !=
      _ERC721CMintingBaseStorage()
        .mintingGroups[mintingGroupIndex]
        .mintingAuthority
    ) revert CallerNotMintingAuthority();
    _;
  }

  function transferMintGroupSupply(
    uint fromId,
    uint toId,
    uint64 quantity
  ) public onlyAdmin onlyIsActive(fromId) {
    _transferMintGroupSupply(fromId, toId, quantity);
  }
}

File 29 of 31 : HiraethTokenURIUtils.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;
import '@protocol/core/contracts/interfaces/IComponent.sol';
import '@protocol/core/contracts/libraries/bytes/BytesUtils.sol';
import '@protocol/core/contracts/libraries/sstore2/SSTORE2Map.sol';
import '@protocol/core/contracts/libraries/ComponentUtils.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import '@protocol/core/contracts/libraries/bytes/DynamicBuffer.sol';
import '@protocol/core/contracts/libraries/UnicodeUtils.sol';

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

import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@protocol/core/contracts/interfaces/IScriptyBuilder.sol';
import '@protocol/core/contracts/interfaces/IContractScript.sol';
import '@protocol/core/contracts/interfaces/IDataStorage.sol';
import '@protocol/core/contracts/utils/OnchainMetadataUtils.sol';

contract HiraethTokenURIUtils {
  bytes31 public constant nameKey =
    0x6e616d65000000000000000000000000000000000000000000000000000000;
  bytes31 public constant descriptionKey =
    0x6465736372697074696f6e0000000000000000000000000000000000000000;

  function getParametersFromProps(
    bytes calldata props
  )
    public
    pure
    returns (address hiraeth, uint tokenId, bytes32 txnHash, address minter)
  {
    hiraeth = BytesUtils.toAddress(props, 0);
    tokenId = BytesUtils.toUint256(props, 20);
    txnHash = BytesUtils.toBytes32(props, 52);
    minter = BytesUtils.toAddress(props, 84);
  }

  bytes16 private constant HEX_DIGITS = '0123456789abcdef';

  function getDefaultName(bytes32 txnHash) public pure returns (string memory) {
    bytes memory txnHashString = bytes(Strings.toHexString(uint(txnHash), 32));

    return
      string(
        abi.encodePacked(
          BytesUtils.slice(txnHashString, 0, 8),
          '...',
          BytesUtils.slice(txnHashString, 60, 6)
        )
      );
  }

  function getDefaultDescription(bytes32) public pure returns (string memory) {
    return
      string(
        abi.encodePacked(
          'Here%20lies%20a%20relic%20of%20our%20crypto%20history.'
        )
      );
  }
}

File 30 of 31 : Hiraeth.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;
import '@protocol/erc721c/contracts/tokens/ERC721CMintingBase.sol';
import './HiraethBase.sol';

error HiraethUnsetMintNotAllowed();
error HiraethAlreadyInitialized();

contract Hiraeth is ERC721CMintingBase, HiraethBase {
  constructor(
    string memory name_,
    string memory symbol_,
    ERC721CMintingBase.MintingGroup[] memory mintingGroups_,
    address logic,
    address admin,
    uint256 epochSize
  )
    MultiRoleAuthority(admin)
    ERC721A(name_, symbol_)
    ERC721C(logic)
    ERC721CMintingBase(mintingGroups_)
  {
    _HiraethStorage().epochSize = epochSize;
  }

  function _startTokenId() internal view virtual override returns (uint256) {
    return 1;
  }

  event HiraethClaimed(uint256 tokenId, bytes32 txnHash);

  function getEpochSize() external view returns (uint) {
    return _HiraethStorage().epochSize;
  }

  function tokenMetadata(
    uint256 tokenId
  ) public view returns (HiraethTokenMetadata memory) {
    HiraethTokenMetadata memory metadata;

    while (true) {
      metadata = _HiraethStorage().tokenMetadata[tokenId];
      // ERC721A does not allow for a null address mint, so this should be a good check for initialized metadata
      if (metadata.minter != address(0)) {
        return metadata;
      }
      if (tokenId == 0) {
        return HiraethTokenMetadata(address(0), 0x000000);
      }
      unchecked {
        tokenId -= 1;
      }
    }

    return HiraethTokenMetadata(address(0), 0x000000);
  }

  function tokenMetadataByTxnHash(
    bytes32 txnHash
  ) external view returns (HiraethTokenMetadata memory metadata) {
    uint256 tokenId = _HiraethStorage().txnHashToTokenId[txnHash];
    return tokenMetadata(tokenId);
  }

  function tokenIdToTxnHash(
    uint256 tokenId
  ) external view returns (bytes32 txnHash) {
    return _HiraethStorage().tokenIdToTxnHash[tokenId];
  }

  function txnHashToTokenId(
    bytes32 txnHash
  ) external view returns (uint256 tokenId) {
    return _HiraethStorage().txnHashToTokenId[txnHash];
  }

  function ownerOfByTxnHash(
    bytes32 txnHash
  ) external view returns (address owner) {
    return ownerOf(_HiraethStorage().txnHashToTokenId[txnHash]);
  }

  function getEpoch(uint256 tokenId) public view returns (uint256) {
    return ((tokenId - _startTokenId()) / _HiraethStorage().epochSize) + 1;
  }

  function _inscribeHiraethMints(
    address minter,
    bytes32[] memory txnHashes
  ) internal returns (uint64) {
    HiraethStorage storage state = _HiraethStorage();

    unchecked {
      uint64 numMints = 0;
      uint256 currentIndex = _nextTokenId();
      for (uint256 i = 0; i < txnHashes.length; ++i) {
        bytes32 txnHash = txnHashes[i];
        if (txnHash != 0 && state.txnHashToTokenId[txnHash] == 0) {
          // we will write the metadata to the first token minted in a multi-mint
          if (i == 0) {
            state.tokenMetadata[currentIndex] = HiraethTokenMetadata(
              minter,
              0x000000
            );
          }

          state.tokenIdToTxnHash[currentIndex] = txnHash;
          state.txnHashToTokenId[txnHash] = currentIndex;
          emit HiraethClaimed(currentIndex, txnHash);

          currentIndex++;
          numMints++;
        }
      }
      return numMints;
    }
  }

  function mintHiraeth(
    uint id,
    address to,
    address minter,
    bytes32[] memory txnHashes
  ) public onlyMintingAuthority(id) onlyIsActive(id) returns (uint64 numMints) {
    numMints = _inscribeHiraethMints(minter, txnHashes);
    if (numMints != 0) {
      _mintFromGroup(to, numMints, id);
    }
  }
}

File 31 of 31 : HiraethBase.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;
import '@protocol/erc721c/contracts/tokens/ERC721CMintingBase.sol';

abstract contract HiraethBase {
  bytes32 internal constant HIRAETH_BASE = keccak256('com.hiraeth.Hiraeth');

  struct HiraethTokenMetadata {
    address minter;
    bytes12 data; // extra data space for future use
  }

  struct HiraethStorage {
    // for the sake of gas efficiency, tokenMetadata will only be set on the leading token in a multi-mint;
    mapping(uint256 => HiraethTokenMetadata) tokenMetadata;
    mapping(uint256 => bytes32) tokenIdToTxnHash;
    mapping(bytes32 => uint256) txnHashToTokenId;
    uint epochSize;
  }

  function _HiraethStorage()
    internal
    pure
    returns (HiraethStorage storage state)
  {
    bytes32 position = HIRAETH_BASE;
    assembly {
      state.slot := position
    }
  }
}

Settings
{
  "evmVersion": "paris",
  "optimizer": {
    "enabled": false,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "@protocol/core/contracts/utils/OnchainMetadataUtils.sol": {
      "OnchainMetadataUtils": "0xCf774c85617Ea916cEB13C14aC5f7EF2134b2730"
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"utils_","type":"address"},{"internalType":"string","name":"externalUrlRoot_","type":"string"},{"internalType":"string","name":"imageUrlRoot_","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"length","type":"uint256"}],"name":"StringsInsufficientHexLength","type":"error"},{"inputs":[],"name":"externalUrlRoot","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"imageUrlRoot","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"props","type":"bytes"}],"name":"render","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"utils","outputs":[{"internalType":"contract HiraethTokenURIUtils","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

60806040523480156200001157600080fd5b50604051620024073803806200240783398181016040528101906200003791906200029d565b82600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550816000908162000089919062000582565b5080600190816200009b919062000582565b5050505062000669565b6000604051905090565b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000620000e682620000b9565b9050919050565b620000f881620000d9565b81146200010457600080fd5b50565b6000815190506200011881620000ed565b92915050565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b620001738262000128565b810181811067ffffffffffffffff8211171562000195576200019462000139565b5b80604052505050565b6000620001aa620000a5565b9050620001b8828262000168565b919050565b600067ffffffffffffffff821115620001db57620001da62000139565b5b620001e68262000128565b9050602081019050919050565b60005b8381101562000213578082015181840152602081019050620001f6565b60008484015250505050565b6000620002366200023084620001bd565b6200019e565b90508281526020810184848401111562000255576200025462000123565b5b62000262848285620001f3565b509392505050565b600082601f8301126200028257620002816200011e565b5b8151620002948482602086016200021f565b91505092915050565b600080600060608486031215620002b957620002b8620000af565b5b6000620002c98682870162000107565b935050602084015167ffffffffffffffff811115620002ed57620002ec620000b4565b5b620002fb868287016200026a565b925050604084015167ffffffffffffffff8111156200031f576200031e620000b4565b5b6200032d868287016200026a565b9150509250925092565b600081519050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b600060028204905060018216806200038a57607f821691505b602082108103620003a0576200039f62000342565b5b50919050565b60008190508160005260206000209050919050565b60006020601f8301049050919050565b600082821b905092915050565b6000600883026200040a7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82620003cb565b620004168683620003cb565b95508019841693508086168417925050509392505050565b6000819050919050565b6000819050919050565b6000620004636200045d62000457846200042e565b62000438565b6200042e565b9050919050565b6000819050919050565b6200047f8362000442565b620004976200048e826200046a565b848454620003d8565b825550505050565b600090565b620004ae6200049f565b620004bb81848462000474565b505050565b5b81811015620004e357620004d7600082620004a4565b600181019050620004c1565b5050565b601f8211156200053257620004fc81620003a6565b6200050784620003bb565b8101602085101562000517578190505b6200052f6200052685620003bb565b830182620004c0565b50505b505050565b600082821c905092915050565b6000620005576000198460080262000537565b1980831691505092915050565b600062000572838362000544565b9150826002028217905092915050565b6200058d8262000337565b67ffffffffffffffff811115620005a957620005a862000139565b5b620005b5825462000371565b620005c2828285620004e7565b600060209050601f831160018114620005fa5760008415620005e5578287015190505b620005f1858262000564565b86555062000661565b601f1984166200060a86620003a6565b60005b8281101562000634578489015182556001820191506020850194506020810190506200060d565b8683101562000654578489015162000650601f89168262000544565b8355505b6001600288020188555050505b505050505050565b611d8e80620006796000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c806301ffc9a71461005c5780632b9513321461008c578063316df61e146100aa5780635a29638d146100da578063e62b06e0146100f8575b600080fd5b61007660048036038101906100719190610e07565b610116565b6040516100839190610e4f565b60405180910390f35b610094610190565b6040516100a19190610efa565b60405180910390f35b6100c460048036038101906100bf9190610f81565b61021e565b6040516100d19190611023565b60405180910390f35b6100e261072c565b6040516100ef91906110c4565b60405180910390f35b610100610752565b60405161010d9190610efa565b60405180910390f35b60007f316df61e000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614806101895750610188826107e0565b5b9050919050565b6000805461019d9061110e565b80601f01602080910402602001604051908101604052809291908181526020018280546101c99061110e565b80156102165780601f106101eb57610100808354040283529160200191610216565b820191906000526020600020905b8154815290600101906020018083116101f957829003601f168201915b505050505081565b6060600080600080600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ca47a9ca88886040518363ffffffff1660e01b815260040161028392919061117b565b608060405180830381865afa1580156102a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102c49190611249565b935093509350935060008473ffffffffffffffffffffffffffffffffffffffff1663bc0bc6ba856040518263ffffffff1660e01b815260040161030791906112bf565b602060405180830381865afa158015610324573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061034891906112da565b905060006103588460001c61084a565b90506000600267ffffffffffffffff81111561037757610376611307565b5b6040519080825280602002602001820160405280156103b057816020015b61039d610d5f565b8152602001906001900390816103955790505b5090506040518060400160405280600a81526020017f54786e2532304861736800000000000000000000000000000000000000000000815250816000815181106103fd576103fc611336565b5b602002602001015160200181905250818160008151811061042157610420611336565b5b60200260200101516040018190525060018160008151811061044657610445611336565b5b602002602001015160600190151590811515815250506040518060400160405280600681526020017f4d696e7465720000000000000000000000000000000000000000000000000000815250816001815181106104a6576104a5611336565b5b6020026020010151602001819052506104da8460601b60601c73ffffffffffffffffffffffffffffffffffffffff1661084a565b816001815181106104ee576104ed611336565b5b60200260200101516040018190525060018160018151811061051357610512611336565b5b60200260200101516060019015159081151581525050600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ab02b1bc866040518263ffffffff1660e01b81526004016105849190611374565b600060405180830381865afa1580156105a1573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052508101906105ca9190611481565b73cf774c85617ea916ceb13c14ac5f7ef2134b273063157299e0836040518263ffffffff1660e01b815260040161060191906116c6565b600060405180830381865af415801561061e573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052508101906106479190611789565b60008460018661065689610868565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a962ecc58d6040518263ffffffff1660e01b81526004016106b19190611374565b600060405180830381865afa1580156106ce573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052508101906106f79190611481565b60405160200161070e989796959493929190611b68565b60405160208183030381529060405297505050505050505092915050565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6001805461075f9061110e565b80601f016020809104026020016040519081016040528092919081815260200182805461078b9061110e565b80156107d85780601f106107ad576101008083540402835291602001916107d8565b820191906000526020600020905b8154815290600101906020018083116107bb57829003601f168201915b505050505081565b60007f01ffc9a7000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916149050919050565b606061086182600161085b85610936565b016109c6565b9050919050565b60606000600161087784610c0c565b01905060008167ffffffffffffffff81111561089657610895611307565b5b6040519080825280601f01601f1916602001820160405280156108c85781602001600182028036833780820191505090505b509050600082602001820190505b60011561092b578080600190039150507f3031323334353637383961626364656600000000000000000000000000000000600a86061a8153600a858161091f5761091e611c32565b5b049450600085036108d6575b819350505050919050565b600080600090506000608084901c111561095857608083901c92506010810190505b6000604084901c111561097357604083901c92506008810190505b6000602084901c111561098e57602083901c92506004810190505b6000601084901c11156109a957601083901c92506002810190505b6000600884901c11156109bd576001810190505b80915050919050565b60606000839050600060028460026109de9190611c90565b6109e89190611cd2565b67ffffffffffffffff811115610a0157610a00611307565b5b6040519080825280601f01601f191660200182016040528015610a335781602001600182028036833780820191505090505b5090507f300000000000000000000000000000000000000000000000000000000000000081600081518110610a6b57610a6a611336565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053507f780000000000000000000000000000000000000000000000000000000000000081600181518110610acf57610ace611336565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060006001856002610b0f9190611c90565b610b199190611cd2565b90505b6001811115610bb9577f3031323334353637383961626364656600000000000000000000000000000000600f841660108110610b5b57610b5a611336565b5b1a60f81b828281518110610b7257610b71611336565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600483901c925080610bb290611d06565b9050610b1c565b5060008214610c015784846040517fe22e27eb000000000000000000000000000000000000000000000000000000008152600401610bf8929190611d2f565b60405180910390fd5b809250505092915050565b600080600090507a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000008310610c6a577a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000008381610c6057610c5f611c32565b5b0492506040810190505b6d04ee2d6d415b85acef81000000008310610ca7576d04ee2d6d415b85acef81000000008381610c9d57610c9c611c32565b5b0492506020810190505b662386f26fc100008310610cd657662386f26fc100008381610ccc57610ccb611c32565b5b0492506010810190505b6305f5e1008310610cff576305f5e1008381610cf557610cf4611c32565b5b0492506008810190505b6127108310610d24576127108381610d1a57610d19611c32565b5b0492506004810190505b60648310610d475760648381610d3d57610d3c611c32565b5b0492506002810190505b600a8310610d56576001810190505b80915050919050565b604051806080016040528060006004811115610d7e57610d7d6114f6565b5b815260200160608152602001606081526020016000151581525090565b6000604051905090565b600080fd5b600080fd5b60007fffffffff0000000000000000000000000000000000000000000000000000000082169050919050565b610de481610daf565b8114610def57600080fd5b50565b600081359050610e0181610ddb565b92915050565b600060208284031215610e1d57610e1c610da5565b5b6000610e2b84828501610df2565b91505092915050565b60008115159050919050565b610e4981610e34565b82525050565b6000602082019050610e646000830184610e40565b92915050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610ea4578082015181840152602081019050610e89565b60008484015250505050565b6000601f19601f8301169050919050565b6000610ecc82610e6a565b610ed68185610e75565b9350610ee6818560208601610e86565b610eef81610eb0565b840191505092915050565b60006020820190508181036000830152610f148184610ec1565b905092915050565b600080fd5b600080fd5b600080fd5b60008083601f840112610f4157610f40610f1c565b5b8235905067ffffffffffffffff811115610f5e57610f5d610f21565b5b602083019150836001820283011115610f7a57610f79610f26565b5b9250929050565b60008060208385031215610f9857610f97610da5565b5b600083013567ffffffffffffffff811115610fb657610fb5610daa565b5b610fc285828601610f2b565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000610ff582610fce565b610fff8185610fd9565b935061100f818560208601610e86565b61101881610eb0565b840191505092915050565b6000602082019050818103600083015261103d8184610fea565b905092915050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b600061108a61108561108084611045565b611065565b611045565b9050919050565b600061109c8261106f565b9050919050565b60006110ae82611091565b9050919050565b6110be816110a3565b82525050565b60006020820190506110d960008301846110b5565b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b6000600282049050600182168061112657607f821691505b602082108103611139576111386110df565b5b50919050565b82818337600083830152505050565b600061115a8385610fd9565b935061116783858461113f565b61117083610eb0565b840190509392505050565b6000602082019050818103600083015261119681848661114e565b90509392505050565b60006111aa82611045565b9050919050565b6111ba8161119f565b81146111c557600080fd5b50565b6000815190506111d7816111b1565b92915050565b6000819050919050565b6111f0816111dd565b81146111fb57600080fd5b50565b60008151905061120d816111e7565b92915050565b6000819050919050565b61122681611213565b811461123157600080fd5b50565b6000815190506112438161121d565b92915050565b6000806000806080858703121561126357611262610da5565b5b6000611271878288016111c8565b9450506020611282878288016111fe565b935050604061129387828801611234565b92505060606112a4878288016111c8565b91505092959194509250565b6112b9816111dd565b82525050565b60006020820190506112d460008301846112b0565b92915050565b6000602082840312156112f0576112ef610da5565b5b60006112fe848285016111fe565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b61136e81611213565b82525050565b60006020820190506113896000830184611365565b92915050565b600080fd5b61139d82610eb0565b810181811067ffffffffffffffff821117156113bc576113bb611307565b5b80604052505050565b60006113cf610d9b565b90506113db8282611394565b919050565b600067ffffffffffffffff8211156113fb576113fa611307565b5b61140482610eb0565b9050602081019050919050565b600061142461141f846113e0565b6113c5565b9050828152602081018484840111156114405761143f61138f565b5b61144b848285610e86565b509392505050565b600082601f83011261146857611467610f1c565b5b8151611478848260208601611411565b91505092915050565b60006020828403121561149757611496610da5565b5b600082015167ffffffffffffffff8111156114b5576114b4610daa565b5b6114c184828501611453565b91505092915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b60058110611536576115356114f6565b5b50565b600081905061154782611525565b919050565b600061155782611539565b9050919050565b6115678161154c565b82525050565b600082825260208201905092915050565b600061158982610fce565b611593818561156d565b93506115a3818560208601610e86565b6115ac81610eb0565b840191505092915050565b6115c081610e34565b82525050565b60006080830160008301516115de600086018261155e565b50602083015184820360208601526115f6828261157e565b91505060408301518482036040860152611610828261157e565b915050606083015161162560608601826115b7565b508091505092915050565b600061163c83836115c6565b905092915050565b6000602082019050919050565b600061165c826114ca565b61166681856114d5565b935083602082028501611678856114e6565b8060005b858110156116b457848403895281516116958582611630565b94506116a083611644565b925060208a0199505060018101905061167c565b50829750879550505050505092915050565b600060208201905081810360008301526116e08184611651565b905092915050565b600067ffffffffffffffff82111561170357611702611307565b5b61170c82610eb0565b9050602081019050919050565b600061172c611727846116e8565b6113c5565b9050828152602081018484840111156117485761174761138f565b5b611753848285610e86565b509392505050565b600082601f8301126117705761176f610f1c565b5b8151611780848260208601611719565b91505092915050565b60006020828403121561179f5761179e610da5565b5b600082015167ffffffffffffffff8111156117bd576117bc610daa565b5b6117c98482850161175b565b91505092915050565b600081905092915050565b7f646174613a6170706c69636174696f6e2f6a736f6e2c00000000000000000000600082015250565b60006118136016836117d2565b915061181e826117dd565b601682019050919050565b7f2537422532326e616d6525323225334125323200000000000000000000000000600082015250565b600061185f6013836117d2565b915061186a82611829565b601382019050919050565b600061188082610e6a565b61188a81856117d2565b935061189a818560208601610e86565b80840191505092915050565b7f2532322532432532302532326174747269627574657325323225334125354200600082015250565b60006118dc601f836117d2565b91506118e7826118a6565b601f82019050919050565b600081905092915050565b600061190882610fce565b61191281856118f2565b9350611922818560208601610e86565b80840191505092915050565b7f25354425324325323025323265787465726e616c5f75726c253232253341253260008201527f3200000000000000000000000000000000000000000000000000000000000000602082015250565b600061198a6021836117d2565b91506119958261192e565b602182019050919050565b60008190508160005260206000209050919050565b600081546119c28161110e565b6119cc81866117d2565b945060018216600081146119e757600181146119fc57611a2f565b60ff1983168652811515820286019350611a2f565b611a05856119a0565b60005b83811015611a2757815481890152600182019150602081019050611a08565b838801955050505b50505092915050565b7f253232253243253230253232696d616765253232253341253232000000000000600082015250565b6000611a6e601a836117d2565b9150611a7982611a38565b601a82019050919050565b7f2f696d6167653f7265736f6c7574696f6e3d3426617345706f63683d00000000600082015250565b6000611aba601c836117d2565b9150611ac582611a84565b601c82019050919050565b7f2532322532432532302532326465736372697074696f6e253232253341253232600082015250565b6000611b066020836117d2565b9150611b1182611ad0565b602082019050919050565b7f2532322537440000000000000000000000000000000000000000000000000000600082015250565b6000611b526006836117d2565b9150611b5d82611b1c565b600682019050919050565b6000611b7382611806565b9150611b7e82611852565b9150611b8a828b611875565b9150611b95826118cf565b9150611ba1828a6118fd565b9150611bac8261197d565b9150611bb882896119b5565b9150611bc48288611875565b9150611bcf82611a61565b9150611bdb82876119b5565b9150611be78286611875565b9150611bf282611aad565b9150611bfe8285611875565b9150611c0982611af9565b9150611c158284611875565b9150611c2082611b45565b91508190509998505050505050505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b6000611c9b826111dd565b9150611ca6836111dd565b9250828202611cb4816111dd565b91508282048414831517611ccb57611cca611c61565b5b5092915050565b6000611cdd826111dd565b9150611ce8836111dd565b9250828201905080821115611d0057611cff611c61565b5b92915050565b6000611d11826111dd565b915060008203611d2457611d23611c61565b5b600182039050919050565b6000604082019050611d4460008301856112b0565b611d5160208301846112b0565b939250505056fea26469706673582212206f1b0671507cea961ae5797ef58fb52e33e2bc62bf4378d164e147c140021a8564736f6c63430008150033000000000000000000000000486485a364a90a2e7c2a60a87e27940d4b99c7ac000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002068747470733a2f2f706f622e73747564696f2f686972616574682f626173652f000000000000000000000000000000000000000000000000000000000000002468747470733a2f2f706f622e73747564696f2f6170692f626173652f686972616574682f00000000000000000000000000000000000000000000000000000000

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106100575760003560e01c806301ffc9a71461005c5780632b9513321461008c578063316df61e146100aa5780635a29638d146100da578063e62b06e0146100f8575b600080fd5b61007660048036038101906100719190610e07565b610116565b6040516100839190610e4f565b60405180910390f35b610094610190565b6040516100a19190610efa565b60405180910390f35b6100c460048036038101906100bf9190610f81565b61021e565b6040516100d19190611023565b60405180910390f35b6100e261072c565b6040516100ef91906110c4565b60405180910390f35b610100610752565b60405161010d9190610efa565b60405180910390f35b60007f316df61e000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614806101895750610188826107e0565b5b9050919050565b6000805461019d9061110e565b80601f01602080910402602001604051908101604052809291908181526020018280546101c99061110e565b80156102165780601f106101eb57610100808354040283529160200191610216565b820191906000526020600020905b8154815290600101906020018083116101f957829003601f168201915b505050505081565b6060600080600080600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ca47a9ca88886040518363ffffffff1660e01b815260040161028392919061117b565b608060405180830381865afa1580156102a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102c49190611249565b935093509350935060008473ffffffffffffffffffffffffffffffffffffffff1663bc0bc6ba856040518263ffffffff1660e01b815260040161030791906112bf565b602060405180830381865afa158015610324573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061034891906112da565b905060006103588460001c61084a565b90506000600267ffffffffffffffff81111561037757610376611307565b5b6040519080825280602002602001820160405280156103b057816020015b61039d610d5f565b8152602001906001900390816103955790505b5090506040518060400160405280600a81526020017f54786e2532304861736800000000000000000000000000000000000000000000815250816000815181106103fd576103fc611336565b5b602002602001015160200181905250818160008151811061042157610420611336565b5b60200260200101516040018190525060018160008151811061044657610445611336565b5b602002602001015160600190151590811515815250506040518060400160405280600681526020017f4d696e7465720000000000000000000000000000000000000000000000000000815250816001815181106104a6576104a5611336565b5b6020026020010151602001819052506104da8460601b60601c73ffffffffffffffffffffffffffffffffffffffff1661084a565b816001815181106104ee576104ed611336565b5b60200260200101516040018190525060018160018151811061051357610512611336565b5b60200260200101516060019015159081151581525050600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ab02b1bc866040518263ffffffff1660e01b81526004016105849190611374565b600060405180830381865afa1580156105a1573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052508101906105ca9190611481565b73cf774c85617ea916ceb13c14ac5f7ef2134b273063157299e0836040518263ffffffff1660e01b815260040161060191906116c6565b600060405180830381865af415801561061e573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052508101906106479190611789565b60008460018661065689610868565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a962ecc58d6040518263ffffffff1660e01b81526004016106b19190611374565b600060405180830381865afa1580156106ce573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052508101906106f79190611481565b60405160200161070e989796959493929190611b68565b60405160208183030381529060405297505050505050505092915050565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6001805461075f9061110e565b80601f016020809104026020016040519081016040528092919081815260200182805461078b9061110e565b80156107d85780601f106107ad576101008083540402835291602001916107d8565b820191906000526020600020905b8154815290600101906020018083116107bb57829003601f168201915b505050505081565b60007f01ffc9a7000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916827bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916149050919050565b606061086182600161085b85610936565b016109c6565b9050919050565b60606000600161087784610c0c565b01905060008167ffffffffffffffff81111561089657610895611307565b5b6040519080825280601f01601f1916602001820160405280156108c85781602001600182028036833780820191505090505b509050600082602001820190505b60011561092b578080600190039150507f3031323334353637383961626364656600000000000000000000000000000000600a86061a8153600a858161091f5761091e611c32565b5b049450600085036108d6575b819350505050919050565b600080600090506000608084901c111561095857608083901c92506010810190505b6000604084901c111561097357604083901c92506008810190505b6000602084901c111561098e57602083901c92506004810190505b6000601084901c11156109a957601083901c92506002810190505b6000600884901c11156109bd576001810190505b80915050919050565b60606000839050600060028460026109de9190611c90565b6109e89190611cd2565b67ffffffffffffffff811115610a0157610a00611307565b5b6040519080825280601f01601f191660200182016040528015610a335781602001600182028036833780820191505090505b5090507f300000000000000000000000000000000000000000000000000000000000000081600081518110610a6b57610a6a611336565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053507f780000000000000000000000000000000000000000000000000000000000000081600181518110610acf57610ace611336565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535060006001856002610b0f9190611c90565b610b199190611cd2565b90505b6001811115610bb9577f3031323334353637383961626364656600000000000000000000000000000000600f841660108110610b5b57610b5a611336565b5b1a60f81b828281518110610b7257610b71611336565b5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600483901c925080610bb290611d06565b9050610b1c565b5060008214610c015784846040517fe22e27eb000000000000000000000000000000000000000000000000000000008152600401610bf8929190611d2f565b60405180910390fd5b809250505092915050565b600080600090507a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000008310610c6a577a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000008381610c6057610c5f611c32565b5b0492506040810190505b6d04ee2d6d415b85acef81000000008310610ca7576d04ee2d6d415b85acef81000000008381610c9d57610c9c611c32565b5b0492506020810190505b662386f26fc100008310610cd657662386f26fc100008381610ccc57610ccb611c32565b5b0492506010810190505b6305f5e1008310610cff576305f5e1008381610cf557610cf4611c32565b5b0492506008810190505b6127108310610d24576127108381610d1a57610d19611c32565b5b0492506004810190505b60648310610d475760648381610d3d57610d3c611c32565b5b0492506002810190505b600a8310610d56576001810190505b80915050919050565b604051806080016040528060006004811115610d7e57610d7d6114f6565b5b815260200160608152602001606081526020016000151581525090565b6000604051905090565b600080fd5b600080fd5b60007fffffffff0000000000000000000000000000000000000000000000000000000082169050919050565b610de481610daf565b8114610def57600080fd5b50565b600081359050610e0181610ddb565b92915050565b600060208284031215610e1d57610e1c610da5565b5b6000610e2b84828501610df2565b91505092915050565b60008115159050919050565b610e4981610e34565b82525050565b6000602082019050610e646000830184610e40565b92915050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610ea4578082015181840152602081019050610e89565b60008484015250505050565b6000601f19601f8301169050919050565b6000610ecc82610e6a565b610ed68185610e75565b9350610ee6818560208601610e86565b610eef81610eb0565b840191505092915050565b60006020820190508181036000830152610f148184610ec1565b905092915050565b600080fd5b600080fd5b600080fd5b60008083601f840112610f4157610f40610f1c565b5b8235905067ffffffffffffffff811115610f5e57610f5d610f21565b5b602083019150836001820283011115610f7a57610f79610f26565b5b9250929050565b60008060208385031215610f9857610f97610da5565b5b600083013567ffffffffffffffff811115610fb657610fb5610daa565b5b610fc285828601610f2b565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000610ff582610fce565b610fff8185610fd9565b935061100f818560208601610e86565b61101881610eb0565b840191505092915050565b6000602082019050818103600083015261103d8184610fea565b905092915050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b600061108a61108561108084611045565b611065565b611045565b9050919050565b600061109c8261106f565b9050919050565b60006110ae82611091565b9050919050565b6110be816110a3565b82525050565b60006020820190506110d960008301846110b5565b92915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b6000600282049050600182168061112657607f821691505b602082108103611139576111386110df565b5b50919050565b82818337600083830152505050565b600061115a8385610fd9565b935061116783858461113f565b61117083610eb0565b840190509392505050565b6000602082019050818103600083015261119681848661114e565b90509392505050565b60006111aa82611045565b9050919050565b6111ba8161119f565b81146111c557600080fd5b50565b6000815190506111d7816111b1565b92915050565b6000819050919050565b6111f0816111dd565b81146111fb57600080fd5b50565b60008151905061120d816111e7565b92915050565b6000819050919050565b61122681611213565b811461123157600080fd5b50565b6000815190506112438161121d565b92915050565b6000806000806080858703121561126357611262610da5565b5b6000611271878288016111c8565b9450506020611282878288016111fe565b935050604061129387828801611234565b92505060606112a4878288016111c8565b91505092959194509250565b6112b9816111dd565b82525050565b60006020820190506112d460008301846112b0565b92915050565b6000602082840312156112f0576112ef610da5565b5b60006112fe848285016111fe565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b61136e81611213565b82525050565b60006020820190506113896000830184611365565b92915050565b600080fd5b61139d82610eb0565b810181811067ffffffffffffffff821117156113bc576113bb611307565b5b80604052505050565b60006113cf610d9b565b90506113db8282611394565b919050565b600067ffffffffffffffff8211156113fb576113fa611307565b5b61140482610eb0565b9050602081019050919050565b600061142461141f846113e0565b6113c5565b9050828152602081018484840111156114405761143f61138f565b5b61144b848285610e86565b509392505050565b600082601f83011261146857611467610f1c565b5b8151611478848260208601611411565b91505092915050565b60006020828403121561149757611496610da5565b5b600082015167ffffffffffffffff8111156114b5576114b4610daa565b5b6114c184828501611453565b91505092915050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b60058110611536576115356114f6565b5b50565b600081905061154782611525565b919050565b600061155782611539565b9050919050565b6115678161154c565b82525050565b600082825260208201905092915050565b600061158982610fce565b611593818561156d565b93506115a3818560208601610e86565b6115ac81610eb0565b840191505092915050565b6115c081610e34565b82525050565b60006080830160008301516115de600086018261155e565b50602083015184820360208601526115f6828261157e565b91505060408301518482036040860152611610828261157e565b915050606083015161162560608601826115b7565b508091505092915050565b600061163c83836115c6565b905092915050565b6000602082019050919050565b600061165c826114ca565b61166681856114d5565b935083602082028501611678856114e6565b8060005b858110156116b457848403895281516116958582611630565b94506116a083611644565b925060208a0199505060018101905061167c565b50829750879550505050505092915050565b600060208201905081810360008301526116e08184611651565b905092915050565b600067ffffffffffffffff82111561170357611702611307565b5b61170c82610eb0565b9050602081019050919050565b600061172c611727846116e8565b6113c5565b9050828152602081018484840111156117485761174761138f565b5b611753848285610e86565b509392505050565b600082601f8301126117705761176f610f1c565b5b8151611780848260208601611719565b91505092915050565b60006020828403121561179f5761179e610da5565b5b600082015167ffffffffffffffff8111156117bd576117bc610daa565b5b6117c98482850161175b565b91505092915050565b600081905092915050565b7f646174613a6170706c69636174696f6e2f6a736f6e2c00000000000000000000600082015250565b60006118136016836117d2565b915061181e826117dd565b601682019050919050565b7f2537422532326e616d6525323225334125323200000000000000000000000000600082015250565b600061185f6013836117d2565b915061186a82611829565b601382019050919050565b600061188082610e6a565b61188a81856117d2565b935061189a818560208601610e86565b80840191505092915050565b7f2532322532432532302532326174747269627574657325323225334125354200600082015250565b60006118dc601f836117d2565b91506118e7826118a6565b601f82019050919050565b600081905092915050565b600061190882610fce565b61191281856118f2565b9350611922818560208601610e86565b80840191505092915050565b7f25354425324325323025323265787465726e616c5f75726c253232253341253260008201527f3200000000000000000000000000000000000000000000000000000000000000602082015250565b600061198a6021836117d2565b91506119958261192e565b602182019050919050565b60008190508160005260206000209050919050565b600081546119c28161110e565b6119cc81866117d2565b945060018216600081146119e757600181146119fc57611a2f565b60ff1983168652811515820286019350611a2f565b611a05856119a0565b60005b83811015611a2757815481890152600182019150602081019050611a08565b838801955050505b50505092915050565b7f253232253243253230253232696d616765253232253341253232000000000000600082015250565b6000611a6e601a836117d2565b9150611a7982611a38565b601a82019050919050565b7f2f696d6167653f7265736f6c7574696f6e3d3426617345706f63683d00000000600082015250565b6000611aba601c836117d2565b9150611ac582611a84565b601c82019050919050565b7f2532322532432532302532326465736372697074696f6e253232253341253232600082015250565b6000611b066020836117d2565b9150611b1182611ad0565b602082019050919050565b7f2532322537440000000000000000000000000000000000000000000000000000600082015250565b6000611b526006836117d2565b9150611b5d82611b1c565b600682019050919050565b6000611b7382611806565b9150611b7e82611852565b9150611b8a828b611875565b9150611b95826118cf565b9150611ba1828a6118fd565b9150611bac8261197d565b9150611bb882896119b5565b9150611bc48288611875565b9150611bcf82611a61565b9150611bdb82876119b5565b9150611be78286611875565b9150611bf282611aad565b9150611bfe8285611875565b9150611c0982611af9565b9150611c158284611875565b9150611c2082611b45565b91508190509998505050505050505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b6000611c9b826111dd565b9150611ca6836111dd565b9250828202611cb4816111dd565b91508282048414831517611ccb57611cca611c61565b5b5092915050565b6000611cdd826111dd565b9150611ce8836111dd565b9250828201905080821115611d0057611cff611c61565b5b92915050565b6000611d11826111dd565b915060008203611d2457611d23611c61565b5b600182039050919050565b6000604082019050611d4460008301856112b0565b611d5160208301846112b0565b939250505056fea26469706673582212206f1b0671507cea961ae5797ef58fb52e33e2bc62bf4378d164e147c140021a8564736f6c63430008150033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000486485a364a90a2e7c2a60a87e27940d4b99c7ac000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002068747470733a2f2f706f622e73747564696f2f686972616574682f626173652f000000000000000000000000000000000000000000000000000000000000002468747470733a2f2f706f622e73747564696f2f6170692f626173652f686972616574682f00000000000000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : utils_ (address): 0x486485a364a90A2e7C2A60a87E27940D4b99c7Ac
Arg [1] : externalUrlRoot_ (string): https://pob.studio/hiraeth/base/
Arg [2] : imageUrlRoot_ (string): https://pob.studio/api/base/hiraeth/

-----Encoded View---------------
8 Constructor Arguments found :
Arg [0] : 000000000000000000000000486485a364a90a2e7c2a60a87e27940d4b99c7ac
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000060
Arg [2] : 00000000000000000000000000000000000000000000000000000000000000a0
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000020
Arg [4] : 68747470733a2f2f706f622e73747564696f2f686972616574682f626173652f
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000024
Arg [6] : 68747470733a2f2f706f622e73747564696f2f6170692f626173652f68697261
Arg [7] : 6574682f00000000000000000000000000000000000000000000000000000000


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.