creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981Upgradeable is IERC165Upgradeable {\n    /**\n     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n     */\n    function royaltyInfo(uint256 tokenId, uint256 salePrice)\n        external\n        view\n        returns (address receiver, uint256 royaltyAmount);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for\n * deploying minimal proxy contracts, also known as \"clones\".\n *\n * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies\n * > a minimal bytecode implementation that delegates all calls to a known, fixed address.\n *\n * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`\n * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the\n * deterministic method.\n *\n * _Available since v3.4._\n */\nlibrary ClonesUpgradeable {\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n     *\n     * This function uses the create opcode, which should never revert.\n     */\n    function clone(address implementation) internal returns (address instance) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create(0, 0x09, 0x37)\n        }\n        require(instance != address(0), \"ERC1167: create failed\");\n    }\n\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n     *\n     * This function uses the create2 opcode and a `salt` to deterministically deploy\n     * the clone. Using the same `implementation` and `salt` multiple time will revert, since\n     * the clones cannot be deployed twice at the same address.\n     */\n    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create2(0, 0x09, 0x37, salt)\n        }\n        require(instance != address(0), \"ERC1167: create2 failed\");\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(\n        address implementation,\n        bytes32 salt,\n        address deployer\n    ) internal pure returns (address predicted) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40)\n            mstore(add(ptr, 0x38), deployer)\n            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)\n            mstore(add(ptr, 0x14), implementation)\n            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)\n            mstore(add(ptr, 0x58), salt)\n            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))\n            predicted := keccak256(add(ptr, 0x43), 0x55)\n        }\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(address implementation, bytes32 salt)\n        internal\n        view\n        returns (address predicted)\n    {\n        return predictDeterministicAddress(implementation, salt, address(this));\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized < type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Internal function that returns the initialized version. Returns `_initialized`\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Internal function that returns the initialized version. Returns `_initializing`\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/common/ERC2981Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../interfaces/IERC2981Upgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.\n *\n * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for\n * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.\n *\n * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the\n * fee is specified in basis points by default.\n *\n * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See\n * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to\n * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.\n *\n * _Available since v4.5._\n */\nabstract contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {\n    function __ERC2981_init() internal onlyInitializing {\n    }\n\n    function __ERC2981_init_unchained() internal onlyInitializing {\n    }\n    struct RoyaltyInfo {\n        address receiver;\n        uint96 royaltyFraction;\n    }\n\n    RoyaltyInfo private _defaultRoyaltyInfo;\n    mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) {\n        return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @inheritdoc IERC2981Upgradeable\n     */\n    function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {\n        RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];\n\n        if (royalty.receiver == address(0)) {\n            royalty = _defaultRoyaltyInfo;\n        }\n\n        uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();\n\n        return (royalty.receiver, royaltyAmount);\n    }\n\n    /**\n     * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a\n     * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an\n     * override.\n     */\n    function _feeDenominator() internal pure virtual returns (uint96) {\n        return 10000;\n    }\n\n    /**\n     * @dev Sets the royalty information that all ids in this contract will default to.\n     *\n     * Requirements:\n     *\n     * - `receiver` cannot be the zero address.\n     * - `feeNumerator` cannot be greater than the fee denominator.\n     */\n    function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {\n        require(feeNumerator <= _feeDenominator(), \"ERC2981: royalty fee will exceed salePrice\");\n        require(receiver != address(0), \"ERC2981: invalid receiver\");\n\n        _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);\n    }\n\n    /**\n     * @dev Removes default royalty information.\n     */\n    function _deleteDefaultRoyalty() internal virtual {\n        delete _defaultRoyaltyInfo;\n    }\n\n    /**\n     * @dev Sets the royalty information for a specific token id, overriding the global default.\n     *\n     * Requirements:\n     *\n     * - `receiver` cannot be the zero address.\n     * - `feeNumerator` cannot be greater than the fee denominator.\n     */\n    function _setTokenRoyalty(\n        uint256 tokenId,\n        address receiver,\n        uint96 feeNumerator\n    ) internal virtual {\n        require(feeNumerator <= _feeDenominator(), \"ERC2981: royalty fee will exceed salePrice\");\n        require(receiver != address(0), \"ERC2981: Invalid parameters\");\n\n        _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);\n    }\n\n    /**\n     * @dev Resets royalty information for the token id back to the global default.\n     */\n    function _resetTokenRoyalty(uint256 tokenId) internal virtual {\n        delete _tokenRoyaltyInfo[tokenId];\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[48] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165Upgradeable).interfaceId;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "contracts/Archetype.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Archetype v0.7.0 - DN404\n//\n//        d8888                 888               888\n//       d88888                 888               888\n//      d88P888                 888               888\n//     d88P 888 888d888 .d8888b 88888b.   .d88b.  888888 888  888 88888b.   .d88b.\n//    d88P  888 888P\"  d88P\"    888 \"88b d8P  Y8b 888    888  888 888 \"88b d8P  Y8b\n//   d88P   888 888    888      888  888 88888888 888    888  888 888  888 88888888\n//  d8888888888 888    Y88b.    888  888 Y8b.     Y88b.  Y88b 888 888 d88P Y8b.\n// d88P     888 888     \"Y8888P 888  888  \"Y8888   \"Y888  \"Y88888 88888P\"   \"Y8888\n//                                                            888 888\n//                                                       Y8b d88P 888\n//                                                        \"Y88P\"  888\n\npragma solidity ^0.8.4;\n\nimport \"./ArchetypeLogic.sol\";\nimport \"dn404/src/DN404.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"solady/src/utils/LibString.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/common/ERC2981Upgradeable.sol\";\n\ncontract Archetype is DN404, Initializable, OwnableUpgradeable, ERC2981Upgradeable {\n  //\n  // EVENTS\n  //\n  event Invited(bytes32 indexed key, bytes32 indexed cid);\n  event Referral(address indexed affiliate, address token, uint128 wad, uint256 numMints);\n  event Withdrawal(address indexed src, address token, uint128 wad);\n\n  //\n  // VARIABLES\n  //\n  mapping(bytes32 => DutchInvite) public invites;\n  mapping(address => mapping(bytes32 => uint256)) private _minted;\n  mapping(bytes32 => uint256) private _listSupply;\n  mapping(address => uint128) private _ownerBalance;\n  mapping(address => mapping(address => uint128)) private _affiliateBalance;\n\n  string private _name;\n  string private _symbol;\n  Config public config;\n  PayoutConfig public payoutConfig;\n  Options public options;\n\n  //\n  // METHODS\n  //\n  function initialize(\n    string memory name_,\n    string memory symbol_,\n    Config calldata config_,\n    PayoutConfig calldata payoutConfig_,\n    address mirror,\n    address _receiver\n  ) external initializer {\n    _name = name_;\n    _symbol = symbol_;\n\n    _initializeDN404(0, address(0), mirror);\n\n    // check max bps not reached and min platform fee.\n    if (\n      config_.affiliateFee > MAXBPS ||\n      config_.discounts.affiliateDiscount > MAXBPS ||\n      config_.affiliateSigner == address(0) ||\n      config_.maxBatchSize == 0\n    ) {\n      revert InvalidConfig();\n    }\n    // ensure mint tiers are correctly ordered from highest to lowest.\n    for (uint256 i = 1; i < config_.discounts.mintTiers.length; ) {\n      if (\n        config_.discounts.mintTiers[i].mintDiscount > MAXBPS ||\n        config_.discounts.mintTiers[i].numMints > config_.discounts.mintTiers[i - 1].numMints\n      ) {\n        revert InvalidConfig();\n      }\n      unchecked {\n        ++i;\n      }\n    }\n    config = config_;\n    __Ownable_init();\n\n    uint256 totalShares = payoutConfig_.ownerBps +\n      payoutConfig_.platformBps +\n      payoutConfig_.partnerBps +\n      payoutConfig_.superAffiliateBps;\n\n    if (\n      payoutConfig_.platformBps < 250 ||\n      payoutConfig_.superAffiliate != DEVVAULT ||\n      payoutConfig_.superAffiliateBps < 250 ||\n      totalShares != 10000\n    ) {\n      revert InvalidSplitShares();\n    }\n    payoutConfig = payoutConfig_;\n    setDefaultRoyalty(_receiver, config.defaultRoyalty);\n  }\n\n  //\n  // PUBLIC\n  //\n  function mint(\n    Auth calldata auth,\n    uint256 quantity,\n    address affiliate,\n    bytes calldata signature\n  ) external payable {\n    mintTo(auth, quantity, _msgSender(), affiliate, signature);\n  }\n\n  function batchMintTo(\n    Auth calldata auth,\n    address[] calldata toList,\n    uint256[] calldata quantityList,\n    address affiliate,\n    bytes calldata signature\n  ) external payable {\n    if (quantityList.length != toList.length) {\n      revert InvalidConfig();\n    }\n\n    DutchInvite storage invite = invites[auth.key];\n    uint256 quantity;\n\n    for (uint256 i; i < toList.length; ) {\n      uint256 quantityToAdd;\n      if (invite.unitSize > 1) {\n        quantityToAdd = quantityList[i] * invite.unitSize;\n      } else {\n        quantityToAdd = quantityList[i];\n      }\n      quantity += quantityToAdd;\n\n      _mintNext(toList[i], quantityToAdd * _unit());\n\n      unchecked {\n        ++i;\n      }\n    }\n\n    ValidationArgs memory args;\n    {\n      args = ValidationArgs({\n        owner: owner(),\n        affiliate: affiliate,\n        quantity: quantity,\n        curSupply: numMinted(),\n        listSupply: _listSupply[auth.key]\n      });\n    }\n\n    uint128 cost = uint128(\n      ArchetypeLogic.computePrice(\n        invite,\n        config.discounts,\n        args.quantity,\n        args.listSupply,\n        args.affiliate != address(0)\n      )\n    );\n\n    ArchetypeLogic.validateMint(invite, config, auth, _minted, signature, args, cost);\n\n    if (invite.limit < invite.maxSupply) {\n      _minted[_msgSender()][auth.key] += quantity;\n    }\n    if (invite.maxSupply < UINT32_MAX) {\n      _listSupply[auth.key] += quantity;\n    }\n\n    ArchetypeLogic.updateBalances(\n      invite,\n      config,\n      _ownerBalance,\n      _affiliateBalance,\n      affiliate,\n      quantity,\n      cost\n    );\n\n    if (msg.value > cost) {\n      _refund(_msgSender(), msg.value - cost);\n    }\n  }\n\n  function mintTo(\n    Auth calldata auth,\n    uint256 quantity,\n    address to,\n    address affiliate,\n    bytes calldata signature\n  ) public payable {\n    DutchInvite storage i = invites[auth.key];\n\n    if (i.unitSize > 1) {\n      quantity = quantity * i.unitSize;\n    }\n\n    ValidationArgs memory args;\n    {\n      args = ValidationArgs({\n        owner: owner(),\n        affiliate: affiliate,\n        quantity: quantity,\n        curSupply: numMinted(),\n        listSupply: _listSupply[auth.key]\n      });\n    }\n\n    uint128 cost = uint128(\n      ArchetypeLogic.computePrice(\n        i,\n        config.discounts,\n        args.quantity,\n        args.listSupply,\n        args.affiliate != address(0)\n      )\n    );\n\n    ArchetypeLogic.validateMint(i, config, auth, _minted, signature, args, cost);\n\n    _mintNext(to, quantity * _unit());\n\n    if (i.limit < i.maxSupply) {\n      _minted[_msgSender()][auth.key] += quantity;\n    }\n    if (i.maxSupply < UINT32_MAX) {\n      _listSupply[auth.key] += quantity;\n    }\n\n    ArchetypeLogic.updateBalances(\n      i,\n      config,\n      _ownerBalance,\n      _affiliateBalance,\n      affiliate,\n      quantity,\n      cost\n    );\n\n    if (msg.value > cost) {\n      _refund(_msgSender(), msg.value - cost);\n    }\n  }\n\n  function name() public view override returns (string memory) {\n    return _name;\n  }\n\n  function symbol() public view override returns (string memory) {\n    return _symbol;\n  }\n\n  function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n    if (!_exists(tokenId)) revert URIQueryForNonexistentToken();\n\n    return\n      bytes(config.baseUri).length != 0\n        ? string(abi.encodePacked(config.baseUri, LibString.toString(tokenId)))\n        : \"\";\n  }\n\n  function withdraw() external {\n    address[] memory tokens = new address[](1);\n    tokens[0] = address(0);\n    withdrawTokens(tokens);\n  }\n\n  function withdrawTokens(address[] memory tokens) public {\n    ArchetypeLogic.withdrawTokens(payoutConfig, _ownerBalance, owner(), tokens);\n  }\n\n  function withdrawAffiliate() external {\n    address[] memory tokens = new address[](1);\n    tokens[0] = address(0);\n    withdrawTokensAffiliate(tokens);\n  }\n\n  function withdrawTokensAffiliate(address[] memory tokens) public {\n    ArchetypeLogic.withdrawTokensAffiliate(_affiliateBalance, tokens);\n  }\n\n  function ownerBalance() external view returns (uint128) {\n    return _ownerBalance[address(0)];\n  }\n\n  function ownerBalanceToken(address token) external view returns (uint128) {\n    return _ownerBalance[token];\n  }\n\n  function affiliateBalance(address affiliate) external view returns (uint128) {\n    return _affiliateBalance[affiliate][address(0)];\n  }\n\n  function affiliateBalanceToken(address affiliate, address token) external view returns (uint128) {\n    return _affiliateBalance[affiliate][token];\n  }\n\n  function minted(address minter, bytes32 key) external view returns (uint256) {\n    return _minted[minter][key];\n  }\n\n  function listSupply(bytes32 key) external view returns (uint256) {\n    return _listSupply[key];\n  }\n\n  function numMinted() public view returns (uint256) {\n    return totalSupply() / _unit();\n  }\n\n  function platform() external pure returns (address) {\n    return PLATFORM;\n  }\n\n  function devVault() external pure returns (address) {\n    return DEVVAULT;\n  }\n\n  function computePrice(\n    bytes32 key,\n    uint256 quantity,\n    bool affiliateUsed\n  ) external view returns (uint256) {\n    DutchInvite storage i = invites[key];\n    uint256 listSupply_ = _listSupply[key];\n    return ArchetypeLogic.computePrice(i, config.discounts, quantity, listSupply_, affiliateUsed);\n  }\n\n  //\n  // OWNER ONLY\n  //\n\n  function setBaseURI(string memory baseUri) external _onlyOwner {\n    if (options.uriLocked) {\n      revert LockedForever();\n    }\n\n    config.baseUri = baseUri;\n  }\n\n  /// @notice the password is \"forever\"\n  function lockURI(string memory password) external _onlyOwner {\n    if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked(\"forever\"))) {\n      revert WrongPassword();\n    }\n\n    options.uriLocked = true;\n  }\n\n  // max supply cannot subceed total supply. Be careful changing.\n  function setMaxSupply(uint32 maxSupply) external _onlyOwner {\n    if (options.maxSupplyLocked) {\n      revert LockedForever();\n    }\n\n    if (maxSupply < numMinted()) {\n      revert MaxSupplyExceeded();\n    }\n\n    config.maxSupply = maxSupply;\n  }\n\n  /// @notice the password is \"forever\"\n  function lockMaxSupply(string memory password) external _onlyOwner {\n    if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked(\"forever\"))) {\n      revert WrongPassword();\n    }\n\n    options.maxSupplyLocked = true;\n  }\n\n  function setAffiliateFee(uint16 affiliateFee) external _onlyOwner {\n    if (options.affiliateFeeLocked) {\n      revert LockedForever();\n    }\n    if (affiliateFee > MAXBPS) {\n      revert InvalidConfig();\n    }\n\n    config.affiliateFee = affiliateFee;\n  }\n\n  function lockAffiliateFee() external _onlyOwner {\n    options.affiliateFeeLocked = true;\n  }\n\n  function setDiscounts(Discount calldata discounts) external _onlyOwner {\n    if (options.discountsLocked) {\n      revert LockedForever();\n    }\n\n    if (discounts.affiliateDiscount > MAXBPS) {\n      revert InvalidConfig();\n    }\n\n    // ensure mint tiers are correctly ordered from highest to lowest.\n    for (uint256 i = 1; i < discounts.mintTiers.length; ) {\n      if (\n        discounts.mintTiers[i].mintDiscount > MAXBPS ||\n        discounts.mintTiers[i].numMints > discounts.mintTiers[i - 1].numMints\n      ) {\n        revert InvalidConfig();\n      }\n      unchecked {\n        ++i;\n      }\n    }\n\n    config.discounts = discounts;\n  }\n\n  function lockDiscounts() external _onlyOwner {\n    options.discountsLocked = true;\n  }\n\n  function setMaxBatchSize(uint32 maxBatchSize) external _onlyOwner {\n    config.maxBatchSize = maxBatchSize;\n  }\n\n  function setInvite(\n    bytes32 _key,\n    bytes32 _cid,\n    Invite calldata _invite\n  ) external _onlyOwner {\n    // approve token for withdrawals if erc20 list\n    if (_invite.tokenAddress != address(0)) {\n      bool success = IERC20(_invite.tokenAddress).approve(PAYOUTS, 2**256 - 1);\n      if (!success) {\n        revert NotApprovedToTransfer();\n      }\n    }\n    invites[_key] = DutchInvite({\n      price: _invite.price,\n      reservePrice: _invite.price,\n      delta: 0,\n      start: _invite.start,\n      end: _invite.end,\n      limit: _invite.limit,\n      maxSupply: _invite.maxSupply,\n      interval: 0,\n      unitSize: _invite.unitSize,\n      tokenAddress: _invite.tokenAddress,\n      isBlacklist: _invite.isBlacklist\n    });\n    emit Invited(_key, _cid);\n  }\n\n  function setDutchInvite(\n    bytes32 _key,\n    bytes32 _cid,\n    DutchInvite memory _dutchInvite\n  ) external _onlyOwner {\n    // approve token for withdrawals if erc20 list\n    if (_dutchInvite.tokenAddress != address(0)) {\n      bool success = IERC20(_dutchInvite.tokenAddress).approve(PAYOUTS, 2**256 - 1);\n      if (!success) {\n        revert NotApprovedToTransfer();\n      }\n    }\n    if (_dutchInvite.start < block.timestamp) {\n      _dutchInvite.start = uint32(block.timestamp);\n    }\n    invites[_key] = _dutchInvite;\n    emit Invited(_key, _cid);\n  }\n\n  function setDefaultRoyalty(address receiver, uint16 feeNumerator) public _onlyOwner {\n    config.defaultRoyalty = feeNumerator;\n    _setDefaultRoyalty(receiver, feeNumerator);\n  }\n\n  //\n  // INTERNAL\n  //\n\n  function _msgSender() internal view override returns (address) {\n    return msg.sender == BATCH ? tx.origin : msg.sender;\n  }\n\n  modifier _onlyOwner() {\n    if (_msgSender() != owner()) {\n      revert NotOwner();\n    }\n    _;\n  }\n\n  function _refund(address to, uint256 refund) internal {\n    (bool success, ) = payable(to).call{ value: refund }(\"\");\n    if (!success) {\n      revert TransferFailed();\n    }\n  }\n}\n"
      },
      "contracts/ArchetypeLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// ArchetypeLogic v0.7.0 - DN404\n//\n//        d8888                 888               888\n//       d88888                 888               888\n//      d88P888                 888               888\n//     d88P 888 888d888 .d8888b 88888b.   .d88b.  888888 888  888 88888b.   .d88b.\n//    d88P  888 888P\"  d88P\"    888 \"88b d8P  Y8b 888    888  888 888 \"88b d8P  Y8b\n//   d88P   888 888    888      888  888 88888888 888    888  888 888  888 88888888\n//  d8888888888 888    Y88b.    888  888 Y8b.     Y88b.  Y88b 888 888 d88P Y8b.\n// d88P     888 888     \"Y8888P 888  888  \"Y8888   \"Y888  \"Y88888 88888P\"   \"Y8888\n//                                                            888 888\n//                                                       Y8b d88P 888\n//                                                        \"Y88P\"  888\n\npragma solidity ^0.8.4;\n\nimport \"./ArchetypePayouts.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"solady/src/utils/MerkleProofLib.sol\";\nimport \"solady/src/utils/ECDSA.sol\";\n\nerror InvalidConfig();\nerror MintNotYetStarted();\nerror MintEnded();\nerror WalletUnauthorizedToMint();\nerror InsufficientEthSent();\nerror ExcessiveEthSent();\nerror Erc20BalanceTooLow();\nerror MaxSupplyExceeded();\nerror ListMaxSupplyExceeded();\nerror NumberOfMintsExceeded();\nerror MintingPaused();\nerror InvalidReferral();\nerror InvalidSignature();\nerror MaxBatchSizeExceeded();\nerror NotTokenOwner();\nerror NotPlatform();\nerror NotOwner();\nerror NotShareholder();\nerror NotApprovedToTransfer();\nerror InvalidAmountOfTokens();\nerror WrongPassword();\nerror LockedForever();\nerror Blacklisted();\nerror URIQueryForNonexistentToken();\n\n//\n// STRUCTS\n//\nstruct Auth {\n  bytes32 key;\n  bytes32[] proof;\n}\n\nstruct MintTier {\n  uint16 numMints;\n  uint16 mintDiscount; //BPS\n}\n\nstruct Discount {\n  uint16 affiliateDiscount; //BPS\n  MintTier[] mintTiers;\n}\n\nstruct Config {\n  string baseUri;\n  address affiliateSigner;\n  uint32 maxSupply;\n  uint32 maxBatchSize;\n  uint16 affiliateFee; //BPS\n  uint16 defaultRoyalty; //BPS\n  Discount discounts;\n}\n\nstruct PayoutConfig {\n  uint16 ownerBps;\n  uint16 platformBps;\n  uint16 partnerBps;\n  uint16 superAffiliateBps;\n  address partner;\n  address superAffiliate;\n}\n\nstruct Options {\n  bool uriLocked;\n  bool maxSupplyLocked;\n  bool affiliateFeeLocked;\n  bool discountsLocked;\n  bool ownerAltPayoutLocked;\n}\n\nstruct DutchInvite {\n  uint128 price;\n  uint128 reservePrice;\n  uint128 delta;\n  uint32 start;\n  uint32 end;\n  uint32 limit;\n  uint32 maxSupply;\n  uint32 interval;\n  uint32 unitSize; // mint 1 get x\n  address tokenAddress;\n  bool isBlacklist;\n}\n\nstruct Invite {\n  uint128 price;\n  uint32 start;\n  uint32 end;\n  uint32 limit;\n  uint32 maxSupply;\n  uint32 unitSize; // mint 1 get x\n  address tokenAddress;\n  bool isBlacklist;\n}\n\nstruct ValidationArgs {\n  address owner;\n  address affiliate;\n  uint256 quantity;\n  uint256 curSupply;\n  uint256 listSupply;\n}\n\n// UPDATE CONSTANTS BEFORE DEPLOY\naddress constant PLATFORM = 0x86B82972282Dd22348374bC63fd21620F7ED847B;\naddress constant DEVVAULT = 0xe9191E06EaA1b32997FFAFB9a2AbBab525518Fa8;\naddress constant BATCH = 0x6Bc558A6DC48dEfa0e7022713c23D65Ab26e4Fa7;\naddress constant PAYOUTS = 0xaAfdfA4a935d8511bF285af11A0544ce7e4a1199;\nuint16 constant MAXBPS = 5000; // max fee or discount is 50%\nuint32 constant UINT32_MAX = 2**32 - 1;\n\nlibrary ArchetypeLogic {\n  //\n  // EVENTS\n  //\n  event Invited(bytes32 indexed key, bytes32 indexed cid);\n  event Referral(address indexed affiliate, address token, uint128 wad, uint256 numMints);\n  event Withdrawal(address indexed src, address token, uint128 wad);\n\n  // calculate price based on affiliate usage and mint discounts\n  function computePrice(\n    DutchInvite storage invite,\n    Discount storage discounts,\n    uint256 numTokens,\n    uint256 listSupply,\n    bool affiliateUsed\n  ) public view returns (uint256) {\n    uint256 price = invite.price;\n    uint256 cost;\n    if (invite.interval > 0 && invite.delta > 0) {\n      // Apply dutch pricing\n      uint256 diff = (((block.timestamp - invite.start) / invite.interval) * invite.delta);\n      if (price > invite.reservePrice) {\n        if (diff > price - invite.reservePrice) {\n          price = invite.reservePrice;\n        } else {\n          price = price - diff;\n        }\n      } else if (price < invite.reservePrice) {\n        if (diff > invite.reservePrice - price) {\n          price = invite.reservePrice;\n        } else {\n          price = price + diff;\n        }\n      }\n      cost = price * numTokens;\n    } else if (invite.interval == 0 && invite.delta > 0) {\n      // Apply linear curve\n      uint256 lastPrice = price + invite.delta * listSupply;\n      cost = lastPrice * numTokens + (invite.delta * numTokens * (numTokens - 1)) / 2;\n    } else {\n      cost = price * numTokens;\n    }\n\n    if (affiliateUsed) {\n      cost = cost - ((cost * discounts.affiliateDiscount) / 10000);\n    }\n\n    uint256 numMints = discounts.mintTiers.length;\n    for (uint256 i; i < numMints; ) {\n      uint256 tierNumMints = discounts.mintTiers[i].numMints;\n      if (numTokens >= tierNumMints) {\n        return cost - ((cost * discounts.mintTiers[i].mintDiscount) / 10000);\n      }\n      unchecked {\n        ++i;\n      }\n    }\n    return cost;\n  }\n\n  function validateMint(\n    DutchInvite storage i,\n    Config storage config,\n    Auth calldata auth,\n    mapping(address => mapping(bytes32 => uint256)) storage minted,\n    bytes calldata signature,\n    ValidationArgs memory args,\n    uint128 cost\n  ) public view {\n    address msgSender = _msgSender();\n    if (args.affiliate != address(0)) {\n      if (\n        args.affiliate == PLATFORM || args.affiliate == args.owner || args.affiliate == msgSender\n      ) {\n        revert InvalidReferral();\n      }\n      validateAffiliate(args.affiliate, signature, config.affiliateSigner);\n    }\n\n    if (i.limit == 0) {\n      revert MintingPaused();\n    }\n\n    if (!i.isBlacklist) {\n      if (!verify(auth, i.tokenAddress, msgSender)) {\n        revert WalletUnauthorizedToMint();\n      }\n    } else {\n      if (verify(auth, i.tokenAddress, msgSender)) {\n        revert Blacklisted();\n      }\n    }\n\n    if (block.timestamp < i.start) {\n      revert MintNotYetStarted();\n    }\n\n    if (i.end > i.start && block.timestamp > i.end) {\n      revert MintEnded();\n    }\n\n    if (i.limit < i.maxSupply) {\n      uint256 totalAfterMint = minted[msgSender][auth.key] + args.quantity;\n\n      if (totalAfterMint > i.limit) {\n        revert NumberOfMintsExceeded();\n      }\n    }\n\n    if (i.maxSupply < config.maxSupply) {\n      uint256 totalAfterMint = args.listSupply + args.quantity;\n      if (totalAfterMint > i.maxSupply) {\n        revert ListMaxSupplyExceeded();\n      }\n    }\n\n    if (args.quantity > config.maxBatchSize) {\n      revert MaxBatchSizeExceeded();\n    }\n\n    if ((args.curSupply + args.quantity) > config.maxSupply) {\n      revert MaxSupplyExceeded();\n    }\n\n    if (i.tokenAddress != address(0)) {\n      IERC20 erc20Token = IERC20(i.tokenAddress);\n      if (erc20Token.allowance(msgSender, address(this)) < cost) {\n        revert NotApprovedToTransfer();\n      }\n\n      if (erc20Token.balanceOf(msgSender) < cost) {\n        revert Erc20BalanceTooLow();\n      }\n\n      if (msg.value != 0) {\n        revert ExcessiveEthSent();\n      }\n    } else {\n      if (msg.value < cost) {\n        revert InsufficientEthSent();\n      }\n    }\n  }\n\n  function updateBalances(\n    DutchInvite storage i,\n    Config storage config,\n    mapping(address => uint128) storage _ownerBalance,\n    mapping(address => mapping(address => uint128)) storage _affiliateBalance,\n    address affiliate,\n    uint256 quantity,\n    uint128 value\n  ) public {\n    address tokenAddress = i.tokenAddress;\n\n    uint128 affiliateWad;\n    if (affiliate != address(0)) {\n      affiliateWad = (value * config.affiliateFee) / 10000;\n      _affiliateBalance[affiliate][tokenAddress] += affiliateWad;\n      emit Referral(affiliate, tokenAddress, affiliateWad, quantity);\n    }\n\n    uint128 balance = _ownerBalance[tokenAddress];\n    uint128 ownerWad = value - affiliateWad;\n    _ownerBalance[tokenAddress] = balance + ownerWad;\n\n    if (tokenAddress != address(0)) {\n      IERC20 erc20Token = IERC20(tokenAddress);\n      bool success = erc20Token.transferFrom(_msgSender(), address(this), value);\n      if (!success) {\n        revert TransferFailed();\n      }\n    }\n  }\n\n  function withdrawTokensAffiliate(\n    mapping(address => mapping(address => uint128)) storage _affiliateBalance,\n    address[] calldata tokens\n  ) public {\n    address msgSender = _msgSender();\n\n    for (uint256 i; i < tokens.length; i++) {\n      address tokenAddress = tokens[i];\n      uint128 wad = _affiliateBalance[msgSender][tokenAddress];\n      _affiliateBalance[msgSender][tokenAddress] = 0;\n\n      if (wad == 0) {\n        revert BalanceEmpty();\n      }\n\n      if (tokenAddress == address(0)) {\n        bool success = false;\n        (success, ) = msgSender.call{ value: wad }(\"\");\n        if (!success) {\n          revert TransferFailed();\n        }\n      } else {\n        IERC20 erc20Token = IERC20(tokenAddress);\n        bool success = erc20Token.transfer(msgSender, wad);\n        if (!success) {\n          revert TransferFailed();\n        }\n      }\n\n      emit Withdrawal(msgSender, tokenAddress, wad);\n    }\n  }\n\n  function withdrawTokens(\n    PayoutConfig storage payoutConfig,\n    mapping(address => uint128) storage _ownerBalance,\n    address owner,\n    address[] calldata tokens\n  ) public {\n    address msgSender = _msgSender();\n    for (uint256 i; i < tokens.length; i++) {\n      address tokenAddress = tokens[i];\n      uint128 wad;\n\n      if (\n        msgSender == owner ||\n        msgSender == PLATFORM ||\n        msgSender == payoutConfig.partner ||\n        msgSender == payoutConfig.superAffiliate\n      ) {\n        wad = _ownerBalance[tokenAddress];\n        _ownerBalance[tokenAddress] = 0;\n      } else {\n        revert NotShareholder();\n      }\n\n      if (wad == 0) {\n        revert BalanceEmpty();\n      }\n\n      address[] memory recipients = new address[](4);\n      recipients[0] = owner;\n      recipients[1] = PLATFORM;\n      recipients[2] = payoutConfig.partner;\n      recipients[3] = payoutConfig.superAffiliate;\n\n      uint16[] memory splits = new uint16[](4);\n      splits[0] = payoutConfig.ownerBps;\n      splits[1] = payoutConfig.platformBps;\n      splits[2] = payoutConfig.partnerBps;\n      splits[3] = payoutConfig.superAffiliateBps;\n\n      if (tokenAddress == address(0)) {\n        ArchetypePayouts(PAYOUTS).updateBalances{ value: wad }(\n          wad,\n          tokenAddress,\n          recipients,\n          splits\n        );\n      } else {\n        ArchetypePayouts(PAYOUTS).updateBalances(wad, tokenAddress, recipients, splits);\n      }\n      emit Withdrawal(msgSender, tokenAddress, wad);\n    }\n  }\n\n  function validateAffiliate(\n    address affiliate,\n    bytes calldata signature,\n    address affiliateSigner\n  ) public view {\n    bytes32 signedMessagehash = ECDSA.toEthSignedMessageHash(\n      keccak256(abi.encodePacked(affiliate))\n    );\n    address signer = ECDSA.recover(signedMessagehash, signature);\n\n    if (signer != affiliateSigner) {\n      revert InvalidSignature();\n    }\n  }\n\n  function verify(\n    Auth calldata auth,\n    address tokenAddress,\n    address account\n  ) public pure returns (bool) {\n    // keys 0-255 and tokenAddress are public\n    if (uint256(auth.key) <= 0xff || auth.key == keccak256(abi.encodePacked(tokenAddress))) {\n      return true;\n    }\n\n    return MerkleProofLib.verify(auth.proof, auth.key, keccak256(abi.encodePacked(account)));\n  }\n\n  function _msgSender() internal view returns (address) {\n    return msg.sender == BATCH ? tx.origin : msg.sender;\n  }\n}\n"
      },
      "contracts/ArchetypePayouts.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// ArchetypePayouts v0.7.0\n//\n//        d8888                 888               888\n//       d88888                 888               888\n//      d88P888                 888               888\n//     d88P 888 888d888 .d8888b 88888b.   .d88b.  888888 888  888 88888b.   .d88b.\n//    d88P  888 888P\"  d88P\"    888 \"88b d8P  Y8b 888    888  888 888 \"88b d8P  Y8b\n//   d88P   888 888    888      888  888 88888888 888    888  888 888  888 88888888\n//  d8888888888 888    Y88b.    888  888 Y8b.     Y88b.  Y88b 888 888 d88P Y8b.\n// d88P     888 888     \"Y8888P 888  888  \"Y8888   \"Y888  \"Y88888 88888P\"   \"Y8888\n//                                                            888 888\n//                                                       Y8b d88P 888\n//\n\npragma solidity ^0.8.4;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nerror InvalidLength();\nerror InvalidSplitShares();\nerror TransferFailed();\nerror BalanceEmpty();\nerror NotApprovedToWithdraw();\n\ncontract ArchetypePayouts {\n  event Withdrawal(address indexed src, address token, uint256 wad);\n  event FundsAdded(address indexed recipient, address token, uint256 amount);\n\n  mapping(address => mapping(address => uint256)) private _balance;\n  mapping(address => mapping(address => bool)) private _approvals;\n\n  function updateBalances(\n    uint256 totalAmount,\n    address token,\n    address[] calldata recipients,\n    uint16[] calldata splits\n  ) public payable {\n    if (recipients.length != splits.length) {\n      revert InvalidLength();\n    }\n\n    uint256 totalShares = 0;\n    for (uint256 i = 0; i < splits.length; i++) {\n      totalShares += splits[i];\n    }\n    if (totalShares != 10000) {\n      revert InvalidSplitShares();\n    }\n\n    if (token == address(0)) {\n      // ETH payments\n      uint256 totalReceived = msg.value;\n      for (uint256 i = 0; i < recipients.length; i++) {\n        if (splits[i] > 0) {\n          uint256 amountToAdd = (totalReceived * splits[i]) / 10000;\n          _balance[recipients[i]][token] += amountToAdd;\n          emit FundsAdded(recipients[i], token, amountToAdd);\n        }\n      }\n    } else {\n      // ERC20 payments\n      IERC20 paymentToken = IERC20(token);\n      bool success = paymentToken.transferFrom(msg.sender, address(this), totalAmount);\n      if (!success) {\n        revert TransferFailed();\n      }\n\n      for (uint256 i = 0; i < recipients.length; i++) {\n        if (splits[i] > 0) {\n          uint256 amountToAdd = (totalAmount * splits[i]) / 10000;\n          _balance[recipients[i]][token] += amountToAdd;\n          emit FundsAdded(recipients[i], token, amountToAdd);\n        }\n      }\n    }\n  }\n\n  function withdraw() external {\n    address msgSender = msg.sender;\n    _withdraw(msgSender, msgSender, address(0));\n  }\n\n  function withdrawTokens(address[] memory tokens) external {\n    address msgSender = msg.sender;\n\n    for (uint256 i = 0; i < tokens.length; i++) {\n      _withdraw(msgSender, msgSender, tokens[i]);\n    }\n  }\n\n  function withdrawFrom(address from, address to) public {\n    if (from != msg.sender && !_approvals[from][to]) {\n      revert NotApprovedToWithdraw();\n    }\n    _withdraw(from, to, address(0));\n  }\n\n  function withdrawTokensFrom(\n    address from,\n    address to,\n    address[] memory tokens\n  ) public {\n    if (from != msg.sender && !_approvals[from][to]) {\n      revert NotApprovedToWithdraw();\n    }\n    for (uint256 i = 0; i < tokens.length; i++) {\n      _withdraw(from, to, tokens[i]);\n    }\n  }\n\n  function _withdraw(\n    address from,\n    address to,\n    address token\n  ) internal {\n    uint256 wad;\n\n    wad = _balance[from][token];\n    _balance[from][token] = 0;\n\n    if (wad == 0) {\n      revert BalanceEmpty();\n    }\n\n    if (token == address(0)) {\n      bool success = false;\n      (success, ) = to.call{ value: wad }(\"\");\n      if (!success) {\n        revert TransferFailed();\n      }\n    } else {\n      IERC20 erc20Token = IERC20(token);\n      bool success = erc20Token.transfer(to, wad);\n      if (!success) {\n        revert TransferFailed();\n      }\n    }\n    emit Withdrawal(from, token, wad);\n  }\n\n  function approveWithdrawal(address delegate, bool approved) external {\n    _approvals[msg.sender][delegate] = approved;\n  }\n\n  function isApproved(address from, address delegate) external view returns (bool) {\n    return _approvals[from][delegate];\n  }\n\n  function balance(address recipient) external view returns (uint256) {\n    return _balance[recipient][address(0)];\n  }\n\n  function balanceToken(address recipient, address token) external view returns (uint256) {\n    return _balance[recipient][token];\n  }\n}\n"
      },
      "contracts/Factory.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Factory v0.4.0\n//\n// 8888888888                888\n// 888                       888\n// 888                       888\n// 8888888  8888b.   .d8888b 888888 .d88b.  888d888 888  888\n// 888         \"88b d88P\"    888   d88\"\"88b 888P\"   888  888\n// 888     .d888888 888      888   888  888 888     888  888\n// 888     888  888 Y88b.    Y88b. Y88..88P 888     Y88b 888\n// 888     \"Y888888  \"Y8888P  \"Y888 \"Y88P\"  888      \"Y88888\n//                                                       888\n//                                                  Y8b d88P\n//                                                   \"Y88P\"\n\npragma solidity ^0.8.4;\n\nimport \"./Archetype.sol\";\nimport \"./ArchetypeLogic.sol\";\nimport \"dn404/src/DN404Mirror.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract Factory is Ownable {\n  event CollectionAdded(address indexed sender, address indexed receiver, address collection);\n  address public archetype;\n\n  constructor(address archetype_) {\n    archetype = archetype_;\n  }\n\n  /// @notice config is a struct in the shape of {string placeholder; string base; uint64 supply; bool permanent;}\n  function createCollection(\n    address _receiver,\n    string memory name,\n    string memory symbol,\n    Config calldata config,\n    PayoutConfig calldata payoutConfig\n  ) external payable returns (address) {\n    address mirror = address(new DN404Mirror(address(this)));\n\n    address clone = ClonesUpgradeable.clone(archetype);\n    Archetype token = Archetype(payable(clone));\n    token.initialize(name, symbol, config, payoutConfig, mirror, _receiver);\n\n    token.transferOwnership(_receiver);\n    DN404Mirror(payable(mirror)).pullOwner();\n\n    if (msg.value > 0) {\n      (bool sent, ) = payable(_receiver).call{ value: msg.value }(\"\");\n      require(sent, \"1\");\n    }\n    emit CollectionAdded(_msgSender(), _receiver, clone);\n    return clone;\n  }\n\n  function setArchetype(address archetype_) public onlyOwner {\n    archetype = archetype_;\n  }\n}\n"
      },
      "dn404/src/DN404.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @title DN404\n/// @notice DN404 is a hybrid ERC20 and ERC721 implementation that mints\n/// and burns NFTs based on an account's ERC20 token balance.\n///\n/// @author vectorized.eth (@optimizoor)\n/// @author Quit (@0xQuit)\n/// @author Michael Amadi (@AmadiMichaels)\n/// @author cygaar (@0xCygaar)\n/// @author Thomas (@0xjustadev)\n/// @author Harrison (@PopPunkOnChain)\n///\n/// @dev Note:\n/// - The ERC721 data is stored in this base DN404 contract, however a\n///   DN404Mirror contract ***MUST*** be deployed and linked during\n///   initialization.\nabstract contract DN404 {\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                           EVENTS                           */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /// @dev Emitted when `target` sets their skipNFT flag to `status`.\n    event SkipNFTSet(address indexed target, bool status);\n\n    /// @dev `keccak256(bytes(\"Transfer(address,address,uint256)\"))`.\n    uint256 private constant _TRANSFER_EVENT_SIGNATURE =\n        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;\n\n    /// @dev `keccak256(bytes(\"Approval(address,address,uint256)\"))`.\n    uint256 private constant _APPROVAL_EVENT_SIGNATURE =\n        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;\n\n    /// @dev `keccak256(bytes(\"SkipNFTSet(address,bool)\"))`.\n    uint256 private constant _SKIP_NFT_SET_EVENT_SIGNATURE =\n        0xb5a1de456fff688115a4f75380060c23c8532d14ff85f687cc871456d6420393;\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                        CUSTOM ERRORS                       */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Thrown when attempting to double-initialize the contract.\n    error DNAlreadyInitialized();\n\n    /// @dev Thrown when attempting to transfer or burn more tokens than sender's balance.\n    error InsufficientBalance();\n\n    /// @dev Thrown when a spender attempts to transfer tokens with an insufficient allowance.\n    error InsufficientAllowance();\n\n    /// @dev Thrown when minting an amount of tokens that would overflow the max tokens.\n    error TotalSupplyOverflow();\n\n    /// @dev The unit cannot be zero.\n    error UnitIsZero();\n\n    /// @dev Thrown when the caller for a fallback NFT function is not the mirror contract.\n    error SenderNotMirror();\n\n    /// @dev Thrown when attempting to transfer tokens to the zero address.\n    error TransferToZeroAddress();\n\n    /// @dev Thrown when the mirror address provided for initialization is the zero address.\n    error MirrorAddressIsZero();\n\n    /// @dev Thrown when the link call to the mirror contract reverts.\n    error LinkMirrorContractFailed();\n\n    /// @dev Thrown when setting an NFT token approval\n    /// and the caller is not the owner or an approved operator.\n    error ApprovalCallerNotOwnerNorApproved();\n\n    /// @dev Thrown when transferring an NFT\n    /// and the caller is not the owner or an approved operator.\n    error TransferCallerNotOwnerNorApproved();\n\n    /// @dev Thrown when transferring an NFT and the from address is not the current owner.\n    error TransferFromIncorrectOwner();\n\n    /// @dev Thrown when checking the owner or approved address for a non-existent NFT.\n    error TokenDoesNotExist();\n\n    /// @dev The function selector is not recognized.\n    error FnSelectorNotRecognized();\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                         CONSTANTS                          */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev The flag to denote that the address data is initialized.\n    uint8 internal constant _ADDRESS_DATA_INITIALIZED_FLAG = 1 << 0;\n\n    /// @dev The flag to denote that the address should skip NFTs.\n    uint8 internal constant _ADDRESS_DATA_SKIP_NFT_FLAG = 1 << 1;\n\n    /// @dev The flag to denote that the address has overridden the default Permit2 allowance.\n    uint8 internal constant _ADDRESS_DATA_OVERRIDE_PERMIT2_FLAG = 1 << 2;\n\n    /// @dev The canonical Permit2 address.\n    /// For signature-based allowance granting for single transaction ERC20 `transferFrom`.\n    /// To enable, override `_givePermit2DefaultInfiniteAllowance()`.\n    /// [Github](https://github.com/Uniswap/permit2)\n    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)\n    address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                          STORAGE                           */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Struct containing an address's token data and settings.\n    struct AddressData {\n        // Auxiliary data.\n        uint88 aux;\n        // Flags for `initialized` and `skipNFT`.\n        uint8 flags;\n        // The alias for the address. Zero means absence of an alias.\n        uint32 addressAlias;\n        // The number of NFT tokens.\n        uint32 ownedLength;\n        // The token balance in wei.\n        uint96 balance;\n    }\n\n    /// @dev A uint32 map in storage.\n    struct Uint32Map {\n        uint256 spacer;\n    }\n\n    /// @dev A bitmap in storage.\n    struct Bitmap {\n        uint256 spacer;\n    }\n\n    /// @dev A struct to wrap a uint256 in storage.\n    struct Uint256Ref {\n        uint256 value;\n    }\n\n    /// @dev A mapping of an address pair to a Uint256Ref.\n    struct AddressPairToUint256RefMap {\n        uint256 spacer;\n    }\n\n    /// @dev Struct containing the base token contract storage.\n    struct DN404Storage {\n        // Current number of address aliases assigned.\n        uint32 numAliases;\n        // Next NFT ID to assign for a mint.\n        uint32 nextTokenId;\n        // The head of the burned pool.\n        uint32 burnedPoolHead;\n        // The tail of the burned pool.\n        uint32 burnedPoolTail;\n        // Total supply of minted NFTs.\n        uint32 totalNFTSupply;\n        // Total supply of tokens.\n        uint96 totalSupply;\n        // Address of the NFT mirror contract.\n        address mirrorERC721;\n        // Mapping of a user alias number to their address.\n        mapping(uint32 => address) aliasToAddress;\n        // Mapping of user operator approvals for NFTs.\n        AddressPairToUint256RefMap operatorApprovals;\n        // Mapping of NFT approvals to approved operators.\n        mapping(uint256 => address) nftApprovals;\n        // Bitmap of whether an non-zero NFT approval may exist.\n        Bitmap mayHaveNFTApproval;\n        // Bitmap of whether a NFT ID exists. Ignored if `_useExistsLookup()` returns false.\n        Bitmap exists;\n        // Mapping of user allowances for ERC20 spenders.\n        AddressPairToUint256RefMap allowance;\n        // Mapping of NFT IDs owned by an address.\n        mapping(address => Uint32Map) owned;\n        // The pool of burned NFT IDs.\n        Uint32Map burnedPool;\n        // Even indices: owner aliases. Odd indices: owned indices.\n        Uint32Map oo;\n        // Mapping of user account AddressData.\n        mapping(address => AddressData) addressData;\n    }\n\n    /// @dev Returns a storage pointer for DN404Storage.\n    function _getDN404Storage() internal pure virtual returns (DN404Storage storage $) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // `uint72(bytes9(keccak256(\"DN404_STORAGE\")))`.\n            $.slot := 0xa20d6e21d0e5255308 // Truncate to 9 bytes to reduce bytecode size.\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                         INITIALIZER                        */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Initializes the DN404 contract with an\n    /// `initialTokenSupply`, `initialTokenOwner` and `mirror` NFT contract address.\n    function _initializeDN404(\n        uint256 initialTokenSupply,\n        address initialSupplyOwner,\n        address mirror\n    ) internal virtual {\n        DN404Storage storage $ = _getDN404Storage();\n\n        if ($.nextTokenId != 0) revert DNAlreadyInitialized();\n\n        if (mirror == address(0)) revert MirrorAddressIsZero();\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Make the call to link the mirror contract.\n            mstore(0x00, 0x0f4599e5) // `linkMirrorContract(address)`.\n            mstore(0x20, caller())\n            if iszero(and(eq(mload(0x00), 1), call(gas(), mirror, 0, 0x1c, 0x24, 0x00, 0x20))) {\n                mstore(0x00, 0xd125259c) // `LinkMirrorContractFailed()`.\n                revert(0x1c, 0x04)\n            }\n        }\n\n        $.nextTokenId = 1;\n        $.mirrorERC721 = mirror;\n\n        if (_unit() == 0) revert UnitIsZero();\n\n        if (initialTokenSupply != 0) {\n            if (initialSupplyOwner == address(0)) revert TransferToZeroAddress();\n            if (_totalSupplyOverflows(initialTokenSupply)) revert TotalSupplyOverflow();\n\n            $.totalSupply = uint96(initialTokenSupply);\n            AddressData storage initialOwnerAddressData = _addressData(initialSupplyOwner);\n            initialOwnerAddressData.balance = uint96(initialTokenSupply);\n\n            /// @solidity memory-safe-assembly\n            assembly {\n                // Emit the {Transfer} event.\n                mstore(0x00, initialTokenSupply)\n                log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, shl(96, initialSupplyOwner)))\n            }\n\n            _setSkipNFT(initialSupplyOwner, true);\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*               BASE UNIT FUNCTION TO OVERRIDE               */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Amount of token balance that is equal to one NFT.\n    function _unit() internal view virtual returns (uint256) {\n        return 10 ** 18;\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*               METADATA FUNCTIONS TO OVERRIDE               */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns the name of the token.\n    function name() public view virtual returns (string memory);\n\n    /// @dev Returns the symbol of the token.\n    function symbol() public view virtual returns (string memory);\n\n    /// @dev Returns the Uniform Resource Identifier (URI) for token `id`.\n    function tokenURI(uint256 id) public view virtual returns (string memory);\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                      ERC20 OPERATIONS                      */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns the decimals places of the token. Always 18.\n    function decimals() public pure returns (uint8) {\n        return 18;\n    }\n\n    /// @dev Returns the amount of tokens in existence.\n    function totalSupply() public view virtual returns (uint256) {\n        return uint256(_getDN404Storage().totalSupply);\n    }\n\n    /// @dev Returns the amount of tokens owned by `owner`.\n    function balanceOf(address owner) public view virtual returns (uint256) {\n        return _getDN404Storage().addressData[owner].balance;\n    }\n\n    /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.\n    function allowance(address owner, address spender) public view returns (uint256) {\n        if (_givePermit2DefaultInfiniteAllowance() && spender == _PERMIT2) {\n            uint8 flags = _getDN404Storage().addressData[owner].flags;\n            if (flags & _ADDRESS_DATA_OVERRIDE_PERMIT2_FLAG == 0) return type(uint256).max;\n        }\n        return _ref(_getDN404Storage().allowance, owner, spender).value;\n    }\n\n    /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n    ///\n    /// Emits a {Approval} event.\n    function approve(address spender, uint256 amount) public virtual returns (bool) {\n        _approve(msg.sender, spender, amount);\n        return true;\n    }\n\n    /// @dev Transfer `amount` tokens from the caller to `to`.\n    ///\n    /// Will burn sender NFTs if balance after transfer is less than\n    /// the amount required to support the current NFT balance.\n    ///\n    /// Will mint NFTs to `to` if the recipient's new balance supports\n    /// additional NFTs ***AND*** the `to` address's skipNFT flag is\n    /// set to false.\n    ///\n    /// Requirements:\n    /// - `from` must at least have `amount`.\n    ///\n    /// Emits a {Transfer} event.\n    function transfer(address to, uint256 amount) public virtual returns (bool) {\n        _transfer(msg.sender, to, amount);\n        return true;\n    }\n\n    /// @dev Transfers `amount` tokens from `from` to `to`.\n    ///\n    /// Note: Does not update the allowance if it is the maximum uint256 value.\n    ///\n    /// Will burn sender NFTs if balance after transfer is less than\n    /// the amount required to support the current NFT balance.\n    ///\n    /// Will mint NFTs to `to` if the recipient's new balance supports\n    /// additional NFTs ***AND*** the `to` address's skipNFT flag is\n    /// set to false.\n    ///\n    /// Requirements:\n    /// - `from` must at least have `amount`.\n    /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.\n    ///\n    /// Emits a {Transfer} event.\n    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {\n        Uint256Ref storage a = _ref(_getDN404Storage().allowance, from, msg.sender);\n\n        uint256 allowed = _givePermit2DefaultInfiniteAllowance() && msg.sender == _PERMIT2\n            && (_getDN404Storage().addressData[from].flags & _ADDRESS_DATA_OVERRIDE_PERMIT2_FLAG) == 0\n            ? type(uint256).max\n            : a.value;\n\n        if (allowed != type(uint256).max) {\n            if (amount > allowed) revert InsufficientAllowance();\n            unchecked {\n                a.value = allowed - amount;\n            }\n        }\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                          PERMIT2                           */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Whether Permit2 has infinite allowances by default for all owners.\n    /// For signature-based allowance granting for single transaction ERC20 `transferFrom`.\n    /// To enable, override this function to return true.\n    function _givePermit2DefaultInfiniteAllowance() internal view virtual returns (bool) {\n        return false;\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                  INTERNAL MINT FUNCTIONS                   */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Mints `amount` tokens to `to`, increasing the total supply.\n    ///\n    /// Will mint NFTs to `to` if the recipient's new balance supports\n    /// additional NFTs ***AND*** the `to` address's skipNFT flag is\n    /// set to false.\n    ///\n    /// Emits a {Transfer} event.\n    function _mint(address to, uint256 amount) internal virtual {\n        if (to == address(0)) revert TransferToZeroAddress();\n\n        AddressData storage toAddressData = _addressData(to);\n        DN404Storage storage $ = _getDN404Storage();\n\n        _DNMintTemps memory t;\n        unchecked {\n            uint256 toBalance = uint256(toAddressData.balance) + amount;\n            toAddressData.balance = uint96(toBalance);\n            t.toEnd = toBalance / _unit();\n        }\n        uint256 maxId;\n        unchecked {\n            uint256 totalSupply_ = uint256($.totalSupply) + amount;\n            $.totalSupply = uint96(totalSupply_);\n            uint256 overflows = _toUint(_totalSupplyOverflows(totalSupply_));\n            if (overflows | _toUint(totalSupply_ < amount) != 0) revert TotalSupplyOverflow();\n            maxId = totalSupply_ / _unit();\n        }\n        unchecked {\n            if (toAddressData.flags & _ADDRESS_DATA_SKIP_NFT_FLAG == 0) {\n                Uint32Map storage toOwned = $.owned[to];\n                Uint32Map storage oo = $.oo;\n                uint256 toIndex = toAddressData.ownedLength;\n                _DNPackedLogs memory packedLogs = _packedLogsMalloc(_zeroFloorSub(t.toEnd, toIndex));\n\n                if (packedLogs.logs.length != 0) {\n                    _packedLogsSet(packedLogs, to, 0);\n                    $.totalNFTSupply += uint32(packedLogs.logs.length);\n                    toAddressData.ownedLength = uint32(t.toEnd);\n                    t.toAlias = _registerAndResolveAlias(toAddressData, to);\n                    uint32 burnedPoolHead = $.burnedPoolHead;\n                    uint32 burnedPoolTail = $.burnedPoolTail;\n                    uint256 nextTokenId = $.nextTokenId;\n                    // Mint loop.\n                    do {\n                        uint256 id;\n                        if (burnedPoolHead != burnedPoolTail) {\n                            id = _get($.burnedPool, burnedPoolHead++);\n                        } else {\n                            id = nextTokenId;\n                            while (_get(oo, _ownershipIndex(id)) != 0) {\n                                id = _useExistsLookup()\n                                    ? _wrapNFTId(_findFirstUnset($.exists, id + 1, maxId + 1), maxId)\n                                    : _wrapNFTId(id + 1, maxId);\n                            }\n                            nextTokenId = _wrapNFTId(id + 1, maxId);\n                        }\n                        if (_useExistsLookup()) _set($.exists, id, true);\n                        _set(toOwned, toIndex, uint32(id));\n                        _setOwnerAliasAndOwnedIndex(oo, id, t.toAlias, uint32(toIndex++));\n                        _packedLogsAppend(packedLogs, id);\n                    } while (toIndex != t.toEnd);\n\n                    $.nextTokenId = uint32(nextTokenId);\n                    $.burnedPoolHead = burnedPoolHead;\n                    _packedLogsSend(packedLogs, $.mirrorERC721);\n                }\n            }\n        }\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Emit the {Transfer} event.\n            mstore(0x00, amount)\n            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, shl(96, to)))\n        }\n    }\n\n    /// @dev Mints `amount` tokens to `to`, increasing the total supply.\n    /// This variant mints NFT tokens starting from ID `preTotalSupply / _unit() + 1`.\n    /// It will skip the burned pool.\n    ///\n    /// Will mint NFTs to `to` if the recipient's new balance supports\n    /// additional NFTs ***AND*** the `to` address's skipNFT flag is\n    /// set to false.\n    ///\n    /// Emits a {Transfer} event.\n    function _mintNext(address to, uint256 amount) internal virtual {\n        if (to == address(0)) revert TransferToZeroAddress();\n\n        AddressData storage toAddressData = _addressData(to);\n        DN404Storage storage $ = _getDN404Storage();\n\n        _DNMintTemps memory t;\n        unchecked {\n            uint256 toBalance = uint256(toAddressData.balance) + amount;\n            toAddressData.balance = uint96(toBalance);\n            t.toEnd = toBalance / _unit();\n        }\n        uint256 startId;\n        uint256 maxId;\n        unchecked {\n            uint256 preTotalSupply = uint256($.totalSupply);\n            startId = preTotalSupply / _unit() + 1;\n            uint256 totalSupply_ = uint256(preTotalSupply) + amount;\n            $.totalSupply = uint96(totalSupply_);\n            uint256 overflows = _toUint(_totalSupplyOverflows(totalSupply_));\n            if (overflows | _toUint(totalSupply_ < amount) != 0) revert TotalSupplyOverflow();\n            maxId = totalSupply_ / _unit();\n        }\n        unchecked {\n            if (toAddressData.flags & _ADDRESS_DATA_SKIP_NFT_FLAG == 0) {\n                Uint32Map storage toOwned = $.owned[to];\n                Uint32Map storage oo = $.oo;\n                uint256 toIndex = toAddressData.ownedLength;\n                _DNPackedLogs memory packedLogs = _packedLogsMalloc(_zeroFloorSub(t.toEnd, toIndex));\n\n                if (packedLogs.logs.length != 0) {\n                    _packedLogsSet(packedLogs, to, 0);\n                    $.totalNFTSupply += uint32(packedLogs.logs.length);\n                    toAddressData.ownedLength = uint32(t.toEnd);\n                    t.toAlias = _registerAndResolveAlias(toAddressData, to);\n                    // Mint loop.\n                    do {\n                        uint256 id = startId;\n                        while (_get(oo, _ownershipIndex(id)) != 0) {\n                            id = _useExistsLookup()\n                                ? _wrapNFTId(_findFirstUnset($.exists, id + 1, maxId + 1), maxId)\n                                : _wrapNFTId(id + 1, maxId);\n                        }\n                        startId = _wrapNFTId(id + 1, maxId);\n                        if (_useExistsLookup()) _set($.exists, id, true);\n                        _set(toOwned, toIndex, uint32(id));\n                        _setOwnerAliasAndOwnedIndex(oo, id, t.toAlias, uint32(toIndex++));\n                        _packedLogsAppend(packedLogs, id);\n                    } while (toIndex != t.toEnd);\n\n                    _packedLogsSend(packedLogs, $.mirrorERC721);\n                }\n            }\n        }\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Emit the {Transfer} event.\n            mstore(0x00, amount)\n            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, shl(96, to)))\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                  INTERNAL BURN FUNCTIONS                   */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Burns `amount` tokens from `from`, reducing the total supply.\n    ///\n    /// Will burn sender NFTs if balance after transfer is less than\n    /// the amount required to support the current NFT balance.\n    ///\n    /// Emits a {Transfer} event.\n    function _burn(address from, uint256 amount) internal virtual {\n        AddressData storage fromAddressData = _addressData(from);\n        DN404Storage storage $ = _getDN404Storage();\n\n        uint256 fromBalance = fromAddressData.balance;\n        if (amount > fromBalance) revert InsufficientBalance();\n\n        unchecked {\n            fromAddressData.balance = uint96(fromBalance -= amount);\n            uint256 totalSupply_ = uint256($.totalSupply) - amount;\n            $.totalSupply = uint96(totalSupply_);\n\n            Uint32Map storage fromOwned = $.owned[from];\n            uint256 fromIndex = fromAddressData.ownedLength;\n            uint256 numNFTBurns = _zeroFloorSub(fromIndex, fromBalance / _unit());\n\n            if (numNFTBurns != 0) {\n                _DNPackedLogs memory packedLogs = _packedLogsMalloc(numNFTBurns);\n                _packedLogsSet(packedLogs, from, 1);\n                uint256 totalNFTSupply = uint256($.totalNFTSupply) - numNFTBurns;\n                $.totalNFTSupply = uint32(totalNFTSupply);\n                bool addToBurnedPool = _addToBurnedPool(totalNFTSupply, totalSupply_);\n\n                Uint32Map storage oo = $.oo;\n                uint256 fromEnd = fromIndex - numNFTBurns;\n                fromAddressData.ownedLength = uint32(fromEnd);\n                uint32 burnedPoolTail = $.burnedPoolTail;\n                // Burn loop.\n                do {\n                    uint256 id = _get(fromOwned, --fromIndex);\n                    _setOwnerAliasAndOwnedIndex(oo, id, 0, 0);\n                    _packedLogsAppend(packedLogs, id);\n                    if (_useExistsLookup()) _set($.exists, id, false);\n                    if (addToBurnedPool) _set($.burnedPool, burnedPoolTail++, uint32(id));\n                    if (_get($.mayHaveNFTApproval, id)) {\n                        _set($.mayHaveNFTApproval, id, false);\n                        delete $.nftApprovals[id];\n                    }\n                } while (fromIndex != fromEnd);\n\n                if (addToBurnedPool) $.burnedPoolTail = burnedPoolTail;\n                _packedLogsSend(packedLogs, $.mirrorERC721);\n            }\n        }\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Emit the {Transfer} event.\n            mstore(0x00, amount)\n            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                INTERNAL TRANSFER FUNCTIONS                 */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Moves `amount` of tokens from `from` to `to`.\n    ///\n    /// Will burn sender NFTs if balance after transfer is less than\n    /// the amount required to support the current NFT balance.\n    ///\n    /// Will mint NFTs to `to` if the recipient's new balance supports\n    /// additional NFTs ***AND*** the `to` address's skipNFT flag is\n    /// set to false.\n    ///\n    /// Emits a {Transfer} event.\n    function _transfer(address from, address to, uint256 amount) internal virtual {\n        if (to == address(0)) revert TransferToZeroAddress();\n\n        AddressData storage fromAddressData = _addressData(from);\n        AddressData storage toAddressData = _addressData(to);\n        DN404Storage storage $ = _getDN404Storage();\n\n        _DNTransferTemps memory t;\n        t.fromOwnedLength = fromAddressData.ownedLength;\n        t.toOwnedLength = toAddressData.ownedLength;\n        t.totalSupply = $.totalSupply;\n\n        if (amount > (t.fromBalance = fromAddressData.balance)) revert InsufficientBalance();\n\n        unchecked {\n            fromAddressData.balance = uint96(t.fromBalance -= amount);\n            toAddressData.balance = uint96(t.toBalance = uint256(toAddressData.balance) + amount);\n\n            t.numNFTBurns = _zeroFloorSub(t.fromOwnedLength, t.fromBalance / _unit());\n\n            if (toAddressData.flags & _ADDRESS_DATA_SKIP_NFT_FLAG == 0) {\n                if (from == to) t.toOwnedLength = t.fromOwnedLength - t.numNFTBurns;\n                t.numNFTMints = _zeroFloorSub(t.toBalance / _unit(), t.toOwnedLength);\n            }\n\n            t.totalNFTSupply = uint256($.totalNFTSupply) + t.numNFTMints - t.numNFTBurns;\n            $.totalNFTSupply = uint32(t.totalNFTSupply);\n\n            Uint32Map storage oo = $.oo;\n\n            if (_toUint(_useDirectTransfersIfPossible()) & _toUint(from != to) != 0) {\n                uint256 n = _min(t.fromOwnedLength, _min(t.numNFTBurns, t.numNFTMints));\n                if (n != 0) {\n                    _DNDirectLogs memory directLogs = _directLogsMalloc(n, from, to);\n                    t.numNFTBurns -= n;\n                    t.numNFTMints -= n;\n                    Uint32Map storage fromOwned = $.owned[from];\n                    Uint32Map storage toOwned = $.owned[to];\n                    t.toAlias = _registerAndResolveAlias(toAddressData, to);\n                    // Direct transfer loop.\n                    do {\n                        uint256 id = _get(fromOwned, --t.fromOwnedLength);\n                        _set(toOwned, t.toOwnedLength, uint32(id));\n                        _setOwnerAliasAndOwnedIndex(oo, id, t.toAlias, uint32(t.toOwnedLength++));\n                        _directLogsAppend(directLogs, id);\n                        if (_get($.mayHaveNFTApproval, id)) {\n                            _set($.mayHaveNFTApproval, id, false);\n                            delete $.nftApprovals[id];\n                        }\n                    } while (--n != 0);\n\n                    _directLogsSend(directLogs, $.mirrorERC721);\n                    fromAddressData.ownedLength = uint32(t.fromOwnedLength);\n                    toAddressData.ownedLength = uint32(t.toOwnedLength);\n                }\n            }\n\n            _DNPackedLogs memory packedLogs = _packedLogsMalloc(t.numNFTBurns + t.numNFTMints);\n\n            t.burnedPoolTail = $.burnedPoolTail;\n            if (t.numNFTBurns != 0) {\n                _packedLogsSet(packedLogs, from, 1);\n                bool addToBurnedPool = _addToBurnedPool(t.totalNFTSupply, t.totalSupply);\n                Uint32Map storage fromOwned = $.owned[from];\n                uint256 fromIndex = t.fromOwnedLength;\n                fromAddressData.ownedLength = uint32(t.fromEnd = fromIndex - t.numNFTBurns);\n                uint32 burnedPoolTail = t.burnedPoolTail;\n                // Burn loop.\n                do {\n                    uint256 id = _get(fromOwned, --fromIndex);\n                    _setOwnerAliasAndOwnedIndex(oo, id, 0, 0);\n                    _packedLogsAppend(packedLogs, id);\n                    if (_useExistsLookup()) _set($.exists, id, false);\n                    if (addToBurnedPool) _set($.burnedPool, burnedPoolTail++, uint32(id));\n                    if (_get($.mayHaveNFTApproval, id)) {\n                        _set($.mayHaveNFTApproval, id, false);\n                        delete $.nftApprovals[id];\n                    }\n                } while (fromIndex != t.fromEnd);\n\n                if (addToBurnedPool) $.burnedPoolTail = (t.burnedPoolTail = burnedPoolTail);\n            }\n\n            if (t.numNFTMints != 0) {\n                _packedLogsSet(packedLogs, to, 0);\n                t.nextTokenId = $.nextTokenId;\n                Uint32Map storage toOwned = $.owned[to];\n                t.toAlias = _registerAndResolveAlias(toAddressData, to);\n                uint256 maxId = t.totalSupply / _unit();\n                uint256 toIndex = t.toOwnedLength;\n                toAddressData.ownedLength = uint32(t.toEnd = toIndex + t.numNFTMints);\n                uint32 burnedPoolHead = $.burnedPoolHead;\n                // Mint loop.\n                do {\n                    uint256 id;\n                    if (burnedPoolHead != t.burnedPoolTail) {\n                        id = _get($.burnedPool, burnedPoolHead++);\n                    } else {\n                        id = t.nextTokenId;\n                        while (_get(oo, _ownershipIndex(id)) != 0) {\n                            id = _useExistsLookup()\n                                ? _wrapNFTId(_findFirstUnset($.exists, id + 1, maxId + 1), maxId)\n                                : _wrapNFTId(id + 1, maxId);\n                        }\n                        t.nextTokenId = _wrapNFTId(id + 1, maxId);\n                    }\n                    if (_useExistsLookup()) _set($.exists, id, true);\n                    _set(toOwned, toIndex, uint32(id));\n                    _setOwnerAliasAndOwnedIndex(oo, id, t.toAlias, uint32(toIndex++));\n                    _packedLogsAppend(packedLogs, id);\n                } while (toIndex != t.toEnd);\n\n                $.burnedPoolHead = burnedPoolHead;\n                $.nextTokenId = uint32(t.nextTokenId);\n            }\n\n            if (packedLogs.logs.length != 0) {\n                _packedLogsSend(packedLogs, $.mirrorERC721);\n            }\n        }\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Emit the {Transfer} event.\n            mstore(0x00, amount)\n            // forgefmt: disable-next-item\n            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), shr(96, shl(96, to)))\n        }\n    }\n\n    /// @dev Returns if direct NFT transfers should be used during ERC20 transfers\n    /// whenever possible, instead of burning and re-minting.\n    function _useDirectTransfersIfPossible() internal view virtual returns (bool) {\n        return true;\n    }\n\n    /// @dev Returns if burns should be added to the burn pool.\n    /// This returns false by default, which means the NFT IDs are re-minted in a cycle.\n    function _addToBurnedPool(uint256 totalNFTSupplyAfterBurn, uint256 totalSupplyAfterBurn)\n        internal\n        view\n        virtual\n        returns (bool)\n    {\n        totalNFTSupplyAfterBurn = totalNFTSupplyAfterBurn; // Silence compiler warning.\n        totalSupplyAfterBurn = totalSupplyAfterBurn; // Silence compiler warning.\n        return false;\n    }\n\n    /// @dev Returns whether to use the exists lookup for more efficient\n    /// scanning of an empty token ID slot. Highly recommended for collections\n    /// with near full load factor `totalNFTSupply * _unit() / totalSupply`.\n    /// The trade off is slightly higher initial storage write costs,\n    /// which will be quickly amortized away.\n    function _useExistsLookup() internal pure virtual returns (bool) {\n        return true;\n    }\n\n    /// @dev Transfers token `id` from `from` to `to`.\n    ///\n    /// Requirements:\n    ///\n    /// - Call must originate from the mirror contract.\n    /// - Token `id` must exist.\n    /// - `from` must be the owner of the token.\n    /// - `to` cannot be the zero address.\n    ///   `msgSender` must be the owner of the token, or be approved to manage the token.\n    ///\n    /// Emits a {Transfer} event.\n    function _transferFromNFT(address from, address to, uint256 id, address msgSender)\n        internal\n        virtual\n    {\n        DN404Storage storage $ = _getDN404Storage();\n\n        if (to == address(0)) revert TransferToZeroAddress();\n\n        Uint32Map storage oo = $.oo;\n\n        if (from != $.aliasToAddress[_get(oo, _ownershipIndex(_restrictNFTId(id)))]) {\n            revert TransferFromIncorrectOwner();\n        }\n\n        if (msgSender != from) {\n            if (_ref($.operatorApprovals, from, msgSender).value == 0) {\n                if (msgSender != $.nftApprovals[id]) {\n                    revert TransferCallerNotOwnerNorApproved();\n                }\n            }\n        }\n\n        AddressData storage fromAddressData = _addressData(from);\n        AddressData storage toAddressData = _addressData(to);\n\n        uint256 unit = _unit();\n\n        unchecked {\n            {\n                uint256 fromBalance = fromAddressData.balance;\n                if (unit > fromBalance) revert InsufficientBalance();\n                fromAddressData.balance = uint96(fromBalance - unit);\n                toAddressData.balance += uint96(unit);\n            }\n            mapping(address => Uint32Map) storage owned = $.owned;\n            Uint32Map storage fromOwned = owned[from];\n\n            if (_get($.mayHaveNFTApproval, id)) {\n                _set($.mayHaveNFTApproval, id, false);\n                delete $.nftApprovals[id];\n            }\n\n            {\n                uint32 updatedId = _get(fromOwned, --fromAddressData.ownedLength);\n                uint32 i = _get(oo, _ownedIndex(id));\n                _set(fromOwned, i, updatedId);\n                _set(oo, _ownedIndex(updatedId), i);\n            }\n            uint32 n = toAddressData.ownedLength++;\n            _set(owned[to], n, uint32(id));\n            _setOwnerAliasAndOwnedIndex(oo, id, _registerAndResolveAlias(toAddressData, to), n);\n        }\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Emit the {Transfer} event.\n            mstore(0x00, unit)\n            // forgefmt: disable-next-item\n            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), shr(96, shl(96, to)))\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                 INTERNAL APPROVE FUNCTIONS                 */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.\n    ///\n    /// Emits a {Approval} event.\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        if (_givePermit2DefaultInfiniteAllowance() && spender == _PERMIT2) {\n            _getDN404Storage().addressData[owner].flags |= _ADDRESS_DATA_OVERRIDE_PERMIT2_FLAG;\n        }\n        _ref(_getDN404Storage().allowance, owner, spender).value = amount;\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Emit the {Approval} event.\n            mstore(0x00, amount)\n            // forgefmt: disable-next-item\n            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, shl(96, owner)), shr(96, shl(96, spender)))\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                 DATA HITCHHIKING FUNCTIONS                 */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns the auxiliary data for `owner`.\n    /// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.\n    /// Auxiliary data can be set for any address, even if it does not have any tokens.\n    function _getAux(address owner) internal view virtual returns (uint88) {\n        return _getDN404Storage().addressData[owner].aux;\n    }\n\n    /// @dev Set the auxiliary data for `owner` to `value`.\n    /// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.\n    /// Auxiliary data can be set for any address, even if it does not have any tokens.\n    function _setAux(address owner, uint88 value) internal virtual {\n        _getDN404Storage().addressData[owner].aux = value;\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                     SKIP NFT FUNCTIONS                     */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns true if minting and transferring ERC20s to `owner` will skip minting NFTs.\n    /// Returns false otherwise.\n    function getSkipNFT(address owner) public view virtual returns (bool) {\n        AddressData storage d = _getDN404Storage().addressData[owner];\n        if (d.flags & _ADDRESS_DATA_INITIALIZED_FLAG == 0) return _hasCode(owner);\n        return d.flags & _ADDRESS_DATA_SKIP_NFT_FLAG != 0;\n    }\n\n    /// @dev Sets the caller's skipNFT flag to `skipNFT`. Returns true.\n    ///\n    /// Emits a {SkipNFTSet} event.\n    function setSkipNFT(bool skipNFT) public virtual returns (bool) {\n        _setSkipNFT(msg.sender, skipNFT);\n        return true;\n    }\n\n    /// @dev Internal function to set account `owner` skipNFT flag to `state`\n    ///\n    /// Initializes account `owner` AddressData if it is not currently initialized.\n    ///\n    /// Emits a {SkipNFTSet} event.\n    function _setSkipNFT(address owner, bool state) internal virtual {\n        AddressData storage d = _addressData(owner);\n        if ((d.flags & _ADDRESS_DATA_SKIP_NFT_FLAG != 0) != state) {\n            d.flags ^= _ADDRESS_DATA_SKIP_NFT_FLAG;\n        }\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x00, iszero(iszero(state)))\n            log2(0x00, 0x20, _SKIP_NFT_SET_EVENT_SIGNATURE, shr(96, shl(96, owner)))\n        }\n    }\n\n    /// @dev Returns a storage data pointer for account `owner` AddressData\n    ///\n    /// Initializes account `owner` AddressData if it is not currently initialized.\n    function _addressData(address owner) internal virtual returns (AddressData storage d) {\n        d = _getDN404Storage().addressData[owner];\n        unchecked {\n            if (d.flags & _ADDRESS_DATA_INITIALIZED_FLAG == 0) {\n                uint256 skipNFT = (_toUint(_hasCode(owner)) * _ADDRESS_DATA_SKIP_NFT_FLAG);\n                d.flags = uint8(skipNFT | _ADDRESS_DATA_INITIALIZED_FLAG);\n            }\n        }\n    }\n\n    /// @dev Returns the `addressAlias` of account `to`.\n    ///\n    /// Assigns and registers the next alias if `to` alias was not previously registered.\n    function _registerAndResolveAlias(AddressData storage toAddressData, address to)\n        internal\n        virtual\n        returns (uint32 addressAlias)\n    {\n        DN404Storage storage $ = _getDN404Storage();\n        addressAlias = toAddressData.addressAlias;\n        if (addressAlias == 0) {\n            unchecked {\n                addressAlias = ++$.numAliases;\n            }\n            toAddressData.addressAlias = addressAlias;\n            $.aliasToAddress[addressAlias] = to;\n            if (addressAlias == 0) revert(); // Overflow.\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                     MIRROR OPERATIONS                      */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns the address of the mirror NFT contract.\n    function mirrorERC721() public view virtual returns (address) {\n        return _getDN404Storage().mirrorERC721;\n    }\n\n    /// @dev Returns the total NFT supply.\n    function _totalNFTSupply() internal view virtual returns (uint256) {\n        return _getDN404Storage().totalNFTSupply;\n    }\n\n    /// @dev Returns `owner` NFT balance.\n    function _balanceOfNFT(address owner) internal view virtual returns (uint256) {\n        return _getDN404Storage().addressData[owner].ownedLength;\n    }\n\n    /// @dev Returns the owner of token `id`.\n    /// Returns the zero address instead of reverting if the token does not exist.\n    function _ownerAt(uint256 id) internal view virtual returns (address) {\n        DN404Storage storage $ = _getDN404Storage();\n        return $.aliasToAddress[_get($.oo, _ownershipIndex(_restrictNFTId(id)))];\n    }\n\n    /// @dev Returns the owner of token `id`.\n    ///\n    /// Requirements:\n    /// - Token `id` must exist.\n    function _ownerOf(uint256 id) internal view virtual returns (address) {\n        if (!_exists(id)) revert TokenDoesNotExist();\n        return _ownerAt(id);\n    }\n\n    /// @dev Returns if token `id` exists.\n    function _exists(uint256 id) internal view virtual returns (bool) {\n        return _ownerAt(id) != address(0);\n    }\n\n    /// @dev Returns the account approved to manage token `id`.\n    ///\n    /// Requirements:\n    /// - Token `id` must exist.\n    function _getApproved(uint256 id) internal view virtual returns (address) {\n        if (!_exists(id)) revert TokenDoesNotExist();\n        return _getDN404Storage().nftApprovals[id];\n    }\n\n    /// @dev Sets `spender` as the approved account to manage token `id`, using `msgSender`.\n    ///\n    /// Requirements:\n    /// - `msgSender` must be the owner or an approved operator for the token owner.\n    function _approveNFT(address spender, uint256 id, address msgSender)\n        internal\n        virtual\n        returns (address owner)\n    {\n        DN404Storage storage $ = _getDN404Storage();\n\n        owner = $.aliasToAddress[_get($.oo, _ownershipIndex(_restrictNFTId(id)))];\n\n        if (msgSender != owner) {\n            if (_ref($.operatorApprovals, owner, msgSender).value == 0) {\n                revert ApprovalCallerNotOwnerNorApproved();\n            }\n        }\n\n        $.nftApprovals[id] = spender;\n        _set($.mayHaveNFTApproval, id, spender != address(0));\n    }\n\n    /// @dev Approve or remove the `operator` as an operator for `msgSender`,\n    /// without authorization checks.\n    function _setApprovalForAll(address operator, bool approved, address msgSender)\n        internal\n        virtual\n    {\n        _ref(_getDN404Storage().operatorApprovals, msgSender, operator).value = _toUint(approved);\n    }\n\n    /// @dev Returns the NFT IDs of `owner` in range `[begin, end)`.\n    /// Optimized for smaller bytecode size, as this function is intended for off-chain calling.\n    function _ownedIds(address owner, uint256 begin, uint256 end)\n        internal\n        view\n        virtual\n        returns (uint256[] memory ids)\n    {\n        DN404Storage storage $ = _getDN404Storage();\n        Uint32Map storage owned = $.owned[owner];\n        uint256 n = $.addressData[owner].ownedLength;\n        /// @solidity memory-safe-assembly\n        assembly {\n            n := xor(n, mul(lt(end, n), xor(end, n))) // `min(n, end)`.\n            ids := mload(0x40)\n            let i := begin\n            for {} lt(i, n) { i := add(i, 1) } {\n                let s := add(shl(96, owned.slot), shr(3, i)) // Storage slot.\n                let id := and(0xffffffff, shr(shl(5, and(i, 7)), sload(s)))\n                mstore(add(add(ids, 0x20), shl(5, sub(i, begin))), id) // Append to.\n            }\n            mstore(ids, sub(i, begin)) // Store the length.\n            mstore(0x40, add(add(ids, 0x20), shl(5, sub(i, begin)))) // Allocate memory.\n        }\n    }\n\n    /// @dev Fallback modifier to dispatch calls from the mirror NFT contract\n    /// to internal functions in this contract.\n    modifier dn404Fallback() virtual {\n        DN404Storage storage $ = _getDN404Storage();\n\n        uint256 fnSelector = _calldataload(0x00) >> 224;\n\n        // `transferFromNFT(address,address,uint256,address)`.\n        if (fnSelector == 0xe5eb36c8) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x84) revert();\n\n            address from = address(uint160(_calldataload(0x04)));\n            address to = address(uint160(_calldataload(0x24)));\n            uint256 id = _calldataload(0x44);\n            address msgSender = address(uint160(_calldataload(0x64)));\n\n            _transferFromNFT(from, to, id, msgSender);\n            _return(1);\n        }\n        // `setApprovalForAll(address,bool,address)`.\n        if (fnSelector == 0x813500fc) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x64) revert();\n\n            address spender = address(uint160(_calldataload(0x04)));\n            bool status = _calldataload(0x24) != 0;\n            address msgSender = address(uint160(_calldataload(0x44)));\n\n            _setApprovalForAll(spender, status, msgSender);\n            _return(1);\n        }\n        // `isApprovedForAll(address,address)`.\n        if (fnSelector == 0xe985e9c5) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x44) revert();\n\n            address owner = address(uint160(_calldataload(0x04)));\n            address operator = address(uint160(_calldataload(0x24)));\n\n            _return(_ref($.operatorApprovals, owner, operator).value);\n        }\n        // `ownerOf(uint256)`.\n        if (fnSelector == 0x6352211e) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x24) revert();\n\n            uint256 id = _calldataload(0x04);\n\n            _return(uint160(_ownerOf(id)));\n        }\n        // `ownerAt(uint256)`.\n        if (fnSelector == 0x24359879) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x24) revert();\n\n            uint256 id = _calldataload(0x04);\n\n            _return(uint160(_ownerAt(id)));\n        }\n        // `approveNFT(address,uint256,address)`.\n        if (fnSelector == 0xd10b6e0c) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x64) revert();\n\n            address spender = address(uint160(_calldataload(0x04)));\n            uint256 id = _calldataload(0x24);\n            address msgSender = address(uint160(_calldataload(0x44)));\n\n            _return(uint160(_approveNFT(spender, id, msgSender)));\n        }\n        // `getApproved(uint256)`.\n        if (fnSelector == 0x081812fc) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x24) revert();\n\n            uint256 id = _calldataload(0x04);\n\n            _return(uint160(_getApproved(id)));\n        }\n        // `balanceOfNFT(address)`.\n        if (fnSelector == 0xf5b100ea) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x24) revert();\n\n            address owner = address(uint160(_calldataload(0x04)));\n\n            _return(_balanceOfNFT(owner));\n        }\n        // `totalNFTSupply()`.\n        if (fnSelector == 0xe2c79281) {\n            if (msg.sender != $.mirrorERC721) revert SenderNotMirror();\n            if (msg.data.length < 0x04) revert();\n\n            _return(_totalNFTSupply());\n        }\n        // `implementsDN404()`.\n        if (fnSelector == 0xb7a94eb8) {\n            _return(1);\n        }\n        _;\n    }\n\n    /// @dev Fallback function for calls from mirror NFT contract.\n    /// Override this if you need to implement your custom\n    /// fallback with utilities like Solady's `LibZip.cdFallback()`.\n    /// And always remember to always wrap the fallback with `dn404Fallback`.\n    fallback() external payable virtual dn404Fallback {\n        revert FnSelectorNotRecognized(); // Not mandatory. Just for quality of life.\n    }\n\n    /// @dev This is to silence the compiler warning.\n    /// Override and remove the revert if you want your contract to receive ETH via receive.\n    receive() external payable virtual {\n        if (msg.value != 0) revert();\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                 INTERNAL / PRIVATE HELPERS                 */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns `(i - 1) << 1`.\n    function _ownershipIndex(uint256 i) internal pure returns (uint256) {\n        unchecked {\n            return (i - 1) << 1; // Minus 1 as token IDs start from 1.\n        }\n    }\n\n    /// @dev Returns `((i - 1) << 1) + 1`.\n    function _ownedIndex(uint256 i) internal pure returns (uint256) {\n        unchecked {\n            return ((i - 1) << 1) + 1; // Minus 1 as token IDs start from 1.\n        }\n    }\n\n    /// @dev Returns the uint32 value at `index` in `map`.\n    function _get(Uint32Map storage map, uint256 index) internal view returns (uint32 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let s := add(shl(96, map.slot), shr(3, index)) // Storage slot.\n            result := and(0xffffffff, shr(shl(5, and(index, 7)), sload(s)))\n        }\n    }\n\n    /// @dev Updates the uint32 value at `index` in `map`.\n    function _set(Uint32Map storage map, uint256 index, uint32 value) internal {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let s := add(shl(96, map.slot), shr(3, index)) // Storage slot.\n            let o := shl(5, and(index, 7)) // Storage slot offset (bits).\n            let v := sload(s) // Storage slot value.\n            let m := 0xffffffff // Value mask.\n            sstore(s, xor(v, shl(o, and(m, xor(shr(o, v), value)))))\n        }\n    }\n\n    /// @dev Sets the owner alias and the owned index together.\n    function _setOwnerAliasAndOwnedIndex(\n        Uint32Map storage map,\n        uint256 id,\n        uint32 ownership,\n        uint32 ownedIndex\n    ) internal {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let i := sub(id, 1) // Index of the uint64 combined value.\n            let s := add(shl(96, map.slot), shr(2, i)) // Storage slot.\n            let o := shl(6, and(i, 3)) // Storage slot offset (bits).\n            let v := sload(s) // Storage slot value.\n            let m := 0xffffffffffffffff // Value mask.\n            let combined := or(shl(32, ownedIndex), and(0xffffffff, ownership))\n            sstore(s, xor(v, shl(o, and(m, xor(shr(o, v), combined)))))\n        }\n    }\n\n    /// @dev Returns the boolean value of the bit at `index` in `bitmap`.\n    function _get(Bitmap storage bitmap, uint256 index) internal view returns (bool result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let s := add(shl(96, bitmap.slot), shr(8, index)) // Storage slot.\n            result := and(1, shr(and(0xff, index), sload(s)))\n        }\n    }\n\n    /// @dev Updates the bit at `index` in `bitmap` to `value`.\n    function _set(Bitmap storage bitmap, uint256 index, bool value) internal {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let s := add(shl(96, bitmap.slot), shr(8, index)) // Storage slot.\n            let o := and(0xff, index) // Storage slot offset (bits).\n            sstore(s, or(and(sload(s), not(shl(o, 1))), shl(o, iszero(iszero(value)))))\n        }\n    }\n\n    /// @dev Returns the index of the least significant unset bit in `[begin, end)`.\n    /// If no unset bit is found, returns `type(uint256).max`.\n    function _findFirstUnset(Bitmap storage bitmap, uint256 begin, uint256 end)\n        internal\n        view\n        returns (uint256 unsetBitIndex)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            unsetBitIndex := not(0) // Initialize to `type(uint256).max`.\n            let s := shl(96, bitmap.slot) // Storage offset of the bitmap.\n            let bucket := add(s, shr(8, begin))\n            let negBits := shl(and(0xff, begin), shr(and(0xff, begin), not(sload(bucket))))\n            if iszero(negBits) {\n                let lastBucket := add(s, shr(8, end))\n                for {} 1 {} {\n                    bucket := add(bucket, 1)\n                    negBits := not(sload(bucket))\n                    if or(negBits, gt(bucket, lastBucket)) { break }\n                }\n                if gt(bucket, lastBucket) {\n                    negBits := shr(and(0xff, not(end)), shl(and(0xff, not(end)), negBits))\n                }\n            }\n            if negBits {\n                // Find-first-set routine.\n                let b := and(negBits, add(not(negBits), 1)) // Isolate the least significant bit.\n                let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, b))\n                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, b))))\n                r := or(r, shl(5, lt(0xffffffff, shr(r, b))))\n                // For the remaining 32 bits, use a De Bruijn lookup.\n                // forgefmt: disable-next-item\n                r := or(r, byte(and(div(0xd76453e0, shr(r, b)), 0x1f),\n                    0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))\n                r := or(shl(8, sub(bucket, s)), r)\n                unsetBitIndex := or(r, sub(0, or(iszero(lt(r, end)), lt(r, begin))))\n            }\n        }\n    }\n\n    /// @dev Returns a storage reference to the value at (`a0`, `a1`) in `map`.\n    function _ref(AddressPairToUint256RefMap storage map, address a0, address a1)\n        internal\n        pure\n        returns (Uint256Ref storage ref)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x28, a1)\n            mstore(0x14, a0)\n            mstore(0x00, map.slot)\n            ref.slot := keccak256(0x00, 0x48)\n            // Clear the part of the free memory pointer that was overwritten.\n            mstore(0x28, 0x00)\n        }\n    }\n\n    /// @dev Wraps the NFT ID.\n    function _wrapNFTId(uint256 id, uint256 maxId) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := or(mul(iszero(gt(id, maxId)), id), gt(id, maxId))\n        }\n    }\n\n    /// @dev Returns `id > type(uint32).max ? 0 : id`.\n    function _restrictNFTId(uint256 id) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := mul(id, lt(id, 0x100000000))\n        }\n    }\n\n    /// @dev Returns whether `amount` is a valid `totalSupply`.\n    function _totalSupplyOverflows(uint256 amount) internal view returns (bool) {\n        unchecked {\n            return _toUint(amount > type(uint96).max)\n                | _toUint(amount / _unit() > type(uint32).max - 1) != 0;\n        }\n    }\n\n    /// @dev Returns `max(0, x - y)`.\n    function _zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mul(gt(x, y), sub(x, y))\n        }\n    }\n\n    /// @dev Returns `x < y ? x : y`.\n    function _min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), lt(y, x)))\n        }\n    }\n\n    /// @dev Returns `b ? 1 : 0`.\n    function _toUint(bool b) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := iszero(iszero(b))\n        }\n    }\n\n    /// @dev Struct containing direct transfer log data for {Transfer} events to be\n    /// emitted by the mirror NFT contract.\n    struct _DNDirectLogs {\n        uint256 offset;\n        address from;\n        address to;\n        uint256[] logs;\n    }\n\n    /// @dev Initiates memory allocation for direct logs with `n` log items.\n    function _directLogsMalloc(uint256 n, address from, address to)\n        private\n        pure\n        returns (_DNDirectLogs memory p)\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Note that `p` implicitly allocates and advances the free memory pointer by\n            // 4 words, which we can safely mutate in `_packedLogsSend`.\n            let logs := mload(0x40)\n            mstore(logs, n) // Store the length.\n            let offset := add(0x20, logs) // Skip the word for `p.logs.length`.\n            mstore(0x40, add(offset, shl(5, n))) // Allocate memory.\n            mstore(add(0x60, p), logs) // Set `p.logs`.\n            mstore(add(0x40, p), to) // Set `p.to`.\n            mstore(add(0x20, p), from) // Set `p.from`.\n            mstore(p, offset) // Set `p.offset`.\n        }\n    }\n\n    /// @dev Adds a direct log item to `p` with token `id`.\n    function _directLogsAppend(_DNDirectLogs memory p, uint256 id) private pure {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let offset := mload(p)\n            mstore(offset, id)\n            mstore(p, add(offset, 0x20))\n        }\n    }\n\n    /// @dev Calls the `mirror` NFT contract to emit {Transfer} events for packed logs `p`.\n    function _directLogsSend(_DNDirectLogs memory p, address mirror) private {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let logs := mload(add(p, 0x60))\n            let n := add(0x84, shl(5, mload(logs))) // Length of calldata to send.\n            let o := sub(logs, 0x80) // Start of calldata to send.\n            mstore(o, 0x144027d3) // `logDirectTransfer(address,address,uint256[])`.\n            mstore(add(o, 0x20), mload(add(0x20, p)))\n            mstore(add(o, 0x40), mload(add(0x40, p)))\n            mstore(add(o, 0x60), 0x60) // Offset of `logs` in the calldata to send.\n            if iszero(and(eq(mload(o), 1), call(gas(), mirror, 0, add(o, 0x1c), n, o, 0x20))) {\n                revert(o, 0x00)\n            }\n        }\n    }\n\n    /// @dev Struct containing packed log data for {Transfer} events to be\n    /// emitted by the mirror NFT contract.\n    struct _DNPackedLogs {\n        uint256 offset;\n        uint256 addressAndBit;\n        uint256[] logs;\n    }\n\n    /// @dev Initiates memory allocation for packed logs with `n` log items.\n    function _packedLogsMalloc(uint256 n) private pure returns (_DNPackedLogs memory p) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Note that `p` implicitly allocates and advances the free memory pointer by\n            // 3 words, which we can safely mutate in `_packedLogsSend`.\n            let logs := mload(0x40)\n            mstore(logs, n) // Store the length.\n            let offset := add(0x20, logs) // Skip the word for `p.logs.length`.\n            mstore(0x40, add(offset, shl(5, n))) // Allocate memory.\n            mstore(add(0x40, p), logs) // Set `p.logs`.\n            mstore(p, offset) // Set `p.offset`.\n        }\n    }\n\n    /// @dev Set the current address and the burn bit.\n    function _packedLogsSet(_DNPackedLogs memory p, address a, uint256 burnBit) private pure {\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(add(p, 0x20), or(shl(96, a), burnBit)) // Set `p.addressAndBit`.\n        }\n    }\n\n    /// @dev Adds a packed log item to `p` with token `id`.\n    function _packedLogsAppend(_DNPackedLogs memory p, uint256 id) private pure {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let offset := mload(p)\n            mstore(offset, or(mload(add(p, 0x20)), shl(8, id))) // `p.addressAndBit | (id << 8)`.\n            mstore(p, add(offset, 0x20))\n        }\n    }\n\n    /// @dev Calls the `mirror` NFT contract to emit {Transfer} events for packed logs `p`.\n    function _packedLogsSend(_DNPackedLogs memory p, address mirror) private {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let logs := mload(add(p, 0x40))\n            let o := sub(logs, 0x40) // Start of calldata to send.\n            mstore(o, 0x263c69d6) // `logTransfer(uint256[])`.\n            mstore(add(o, 0x20), 0x20) // Offset of `logs` in the calldata to send.\n            let n := add(0x44, shl(5, mload(logs))) // Length of calldata to send.\n            if iszero(and(eq(mload(o), 1), call(gas(), mirror, 0, add(o, 0x1c), n, o, 0x20))) {\n                revert(o, 0x00)\n            }\n        }\n    }\n\n    /// @dev Struct of temporary variables for transfers.\n    struct _DNTransferTemps {\n        uint256 numNFTBurns;\n        uint256 numNFTMints;\n        uint256 fromBalance;\n        uint256 toBalance;\n        uint256 fromOwnedLength;\n        uint256 toOwnedLength;\n        uint256 totalSupply;\n        uint256 totalNFTSupply;\n        uint256 fromEnd;\n        uint256 toEnd;\n        uint32 toAlias;\n        uint256 nextTokenId;\n        uint32 burnedPoolTail;\n    }\n\n    /// @dev Struct of temporary variables for mints.\n    struct _DNMintTemps {\n        uint256 toEnd;\n        uint32 toAlias;\n    }\n\n    /// @dev Returns if `a` has bytecode of non-zero length.\n    function _hasCode(address a) private view returns (bool result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := extcodesize(a) // Can handle dirty upper bits.\n        }\n    }\n\n    /// @dev Returns the calldata value at `offset`.\n    function _calldataload(uint256 offset) private pure returns (uint256 value) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            value := calldataload(offset)\n        }\n    }\n\n    /// @dev Executes a return opcode to return `x` and end the current call frame.\n    function _return(uint256 x) private pure {\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x00, x)\n            return(0x00, 0x20)\n        }\n    }\n}\n"
      },
      "dn404/src/DN404Mirror.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @title DN404Mirror\n/// @notice DN404Mirror provides an interface for interacting with the\n/// NFT tokens in a DN404 implementation.\n///\n/// @author vectorized.eth (@optimizoor)\n/// @author Quit (@0xQuit)\n/// @author Michael Amadi (@AmadiMichaels)\n/// @author cygaar (@0xCygaar)\n/// @author Thomas (@0xjustadev)\n/// @author Harrison (@PopPunkOnChain)\n///\n/// @dev Note:\n/// - The ERC721 data is stored in the base DN404 contract.\ncontract DN404Mirror {\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                           EVENTS                           */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Emitted when token `id` is transferred from `from` to `to`.\n    event Transfer(address indexed from, address indexed to, uint256 indexed id);\n\n    /// @dev Emitted when `owner` enables `account` to manage the `id` token.\n    event Approval(address indexed owner, address indexed account, uint256 indexed id);\n\n    /// @dev Emitted when `owner` enables or disables `operator` to manage all of their tokens.\n    event ApprovalForAll(address indexed owner, address indexed operator, bool isApproved);\n\n    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.\n    /// This is for marketplace signaling purposes. This contract has a `pullOwner()`\n    /// function that will sync the owner from the base contract.\n    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);\n\n    /// @dev `keccak256(bytes(\"Transfer(address,address,uint256)\"))`.\n    uint256 private constant _TRANSFER_EVENT_SIGNATURE =\n        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;\n\n    /// @dev `keccak256(bytes(\"Approval(address,address,uint256)\"))`.\n    uint256 private constant _APPROVAL_EVENT_SIGNATURE =\n        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;\n\n    /// @dev `keccak256(bytes(\"ApprovalForAll(address,address,bool)\"))`.\n    uint256 private constant _APPROVAL_FOR_ALL_EVENT_SIGNATURE =\n        0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                        CUSTOM ERRORS                       */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Thrown when a call for an NFT function did not originate\n    /// from the base DN404 contract.\n    error SenderNotBase();\n\n    /// @dev Thrown when a call for an NFT function did not originate from the deployer.\n    error SenderNotDeployer();\n\n    /// @dev Thrown when transferring an NFT to a contract address that\n    /// does not implement ERC721Receiver.\n    error TransferToNonERC721ReceiverImplementer();\n\n    /// @dev Thrown when linking to the DN404 base contract and the\n    /// DN404 supportsInterface check fails or the call reverts.\n    error CannotLink();\n\n    /// @dev Thrown when a linkMirrorContract call is received and the\n    /// NFT mirror contract has already been linked to a DN404 base contract.\n    error AlreadyLinked();\n\n    /// @dev Thrown when retrieving the base DN404 address when a link has not\n    /// been established.\n    error NotLinked();\n\n    /// @dev The function selector is not recognized.\n    error FnSelectorNotRecognized();\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                          STORAGE                           */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Struct contain the NFT mirror contract storage.\n    struct DN404NFTStorage {\n        address baseERC20;\n        address deployer;\n        address owner;\n    }\n\n    /// @dev Returns a storage pointer for DN404NFTStorage.\n    function _getDN404NFTStorage() internal pure virtual returns (DN404NFTStorage storage $) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // `uint72(bytes9(keccak256(\"DN404_MIRROR_STORAGE\")))`.\n            $.slot := 0x3602298b8c10b01230 // Truncate to 9 bytes to reduce bytecode size.\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                        CONSTRUCTOR                         */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    constructor(address deployer) {\n        // For non-proxies, we will store the deployer so that only the deployer can\n        // link the base contract.\n        _getDN404NFTStorage().deployer = deployer;\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                     ERC721 OPERATIONS                      */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns the token collection name from the base DN404 contract.\n    function name() public view virtual returns (string memory result) {\n        return _readString(0x06fdde03, 0); // `name()`.\n    }\n\n    /// @dev Returns the token collection symbol from the base DN404 contract.\n    function symbol() public view virtual returns (string memory result) {\n        return _readString(0x95d89b41, 0); // `symbol()`.\n    }\n\n    /// @dev Returns the Uniform Resource Identifier (URI) for token `id` from\n    /// the base DN404 contract.\n    function tokenURI(uint256 id) public view virtual returns (string memory result) {\n        return _readString(0xc87b56dd, id); // `tokenURI()`.\n    }\n\n    /// @dev Returns the total NFT supply from the base DN404 contract.\n    function totalSupply() public view virtual returns (uint256 result) {\n        return _readWord(0xe2c79281, 0, 0); // `totalNFTSupply()`.\n    }\n\n    /// @dev Returns the number of NFT tokens owned by `nftOwner` from the base DN404 contract.\n    ///\n    /// Requirements:\n    /// - `nftOwner` must not be the zero address.\n    function balanceOf(address nftOwner) public view virtual returns (uint256 result) {\n        return _readWord(0xf5b100ea, uint160(nftOwner), 0); // `balanceOfNFT(address)`.\n    }\n\n    /// @dev Returns the owner of token `id` from the base DN404 contract.\n    ///\n    /// Requirements:\n    /// - Token `id` must exist.\n    function ownerOf(uint256 id) public view virtual returns (address result) {\n        return address(uint160(_readWord(0x6352211e, id, 0))); // `ownerOf(uint256)`.\n    }\n\n    /// @dev Returns the owner of token `id` from the base DN404 contract.\n    /// Returns `address(0)` instead of reverting if the token does not exist.\n    function ownerAt(uint256 id) public view virtual returns (address result) {\n        return address(uint160(_readWord(0x24359879, id, 0))); // `ownerAt(uint256)`.\n    }\n\n    /// @dev Sets `spender` as the approved account to manage token `id` in\n    /// the base DN404 contract.\n    ///\n    /// Requirements:\n    /// - Token `id` must exist.\n    /// - The caller must be the owner of the token,\n    ///   or an approved operator for the token owner.\n    ///\n    /// Emits an {Approval} event.\n    function approve(address spender, uint256 id) public virtual {\n        address base = baseERC20();\n        /// @solidity memory-safe-assembly\n        assembly {\n            spender := shr(96, shl(96, spender))\n            let m := mload(0x40)\n            mstore(0x00, 0xd10b6e0c) // `approveNFT(address,uint256,address)`.\n            mstore(0x20, spender)\n            mstore(0x40, id)\n            mstore(0x60, caller())\n            if iszero(\n                and(\n                    gt(returndatasize(), 0x1f),\n                    call(gas(), base, callvalue(), 0x1c, 0x64, 0x00, 0x20)\n                )\n            ) {\n                returndatacopy(m, 0x00, returndatasize())\n                revert(m, returndatasize())\n            }\n            mstore(0x40, m) // Restore the free memory pointer.\n            mstore(0x60, 0) // Restore the zero pointer.\n            // Emit the {Approval} event.\n            log4(codesize(), 0x00, _APPROVAL_EVENT_SIGNATURE, shr(96, mload(0x0c)), spender, id)\n        }\n    }\n\n    /// @dev Returns the account approved to manage token `id` from\n    /// the base DN404 contract.\n    ///\n    /// Requirements:\n    /// - Token `id` must exist.\n    function getApproved(uint256 id) public view virtual returns (address) {\n        return address(uint160(_readWord(0x081812fc, id, 0))); // `getApproved(uint256)`.\n    }\n\n    /// @dev Sets whether `operator` is approved to manage the tokens of the caller in\n    /// the base DN404 contract.\n    ///\n    /// Emits an {ApprovalForAll} event.\n    function setApprovalForAll(address operator, bool approved) public virtual {\n        address base = baseERC20();\n        /// @solidity memory-safe-assembly\n        assembly {\n            operator := shr(96, shl(96, operator))\n            let m := mload(0x40)\n            mstore(0x00, 0x813500fc) // `setApprovalForAll(address,bool,address)`.\n            mstore(0x20, operator)\n            mstore(0x40, iszero(iszero(approved)))\n            mstore(0x60, caller())\n            if iszero(\n                and(eq(mload(0x00), 1), call(gas(), base, callvalue(), 0x1c, 0x64, 0x00, 0x20))\n            ) {\n                returndatacopy(m, 0x00, returndatasize())\n                revert(m, returndatasize())\n            }\n            // Emit the {ApprovalForAll} event.\n            // The `approved` value is already at 0x40.\n            log3(0x40, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), operator)\n            mstore(0x40, m) // Restore the free memory pointer.\n            mstore(0x60, 0) // Restore the zero pointer.\n        }\n    }\n\n    /// @dev Returns whether `operator` is approved to manage the tokens of `nftOwner` from\n    /// the base DN404 contract.\n    function isApprovedForAll(address nftOwner, address operator)\n        public\n        view\n        virtual\n        returns (bool result)\n    {\n        // `isApprovedForAll(address,address)`.\n        return _readWord(0xe985e9c5, uint160(nftOwner), uint160(operator)) != 0;\n    }\n\n    /// @dev Transfers token `id` from `from` to `to`.\n    ///\n    /// Requirements:\n    ///\n    /// - Token `id` must exist.\n    /// - `from` must be the owner of the token.\n    /// - `to` cannot be the zero address.\n    /// - The caller must be the owner of the token, or be approved to manage the token.\n    ///\n    /// Emits a {Transfer} event.\n    function transferFrom(address from, address to, uint256 id) public virtual {\n        address base = baseERC20();\n        /// @solidity memory-safe-assembly\n        assembly {\n            from := shr(96, shl(96, from))\n            to := shr(96, shl(96, to))\n            let m := mload(0x40)\n            mstore(m, 0xe5eb36c8) // `transferFromNFT(address,address,uint256,address)`.\n            mstore(add(m, 0x20), from)\n            mstore(add(m, 0x40), to)\n            mstore(add(m, 0x60), id)\n            mstore(add(m, 0x80), caller())\n            if iszero(\n                and(eq(mload(m), 1), call(gas(), base, callvalue(), add(m, 0x1c), 0x84, m, 0x20))\n            ) {\n                returndatacopy(m, 0x00, returndatasize())\n                revert(m, returndatasize())\n            }\n            // Emit the {Transfer} event.\n            log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)\n        }\n    }\n\n    /// @dev Equivalent to `safeTransferFrom(from, to, id, \"\")`.\n    function safeTransferFrom(address from, address to, uint256 id) public payable virtual {\n        transferFrom(from, to, id);\n\n        if (_hasCode(to)) _checkOnERC721Received(from, to, id, \"\");\n    }\n\n    /// @dev Transfers token `id` from `from` to `to`.\n    ///\n    /// Requirements:\n    ///\n    /// - Token `id` must exist.\n    /// - `from` must be the owner of the token.\n    /// - `to` cannot be the zero address.\n    /// - The caller must be the owner of the token, or be approved to manage the token.\n    /// - If `to` refers to a smart contract, it must implement\n    ///   {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n    ///\n    /// Emits a {Transfer} event.\n    function safeTransferFrom(address from, address to, uint256 id, bytes calldata data)\n        public\n        virtual\n    {\n        transferFrom(from, to, id);\n\n        if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);\n    }\n\n    /// @dev Returns true if this contract implements the interface defined by `interfaceId`.\n    /// See: https://eips.ethereum.org/EIPS/eip-165\n    /// This function call must use less than 30000 gas.\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let s := shr(224, interfaceId)\n            // ERC165: 0x01ffc9a7, ERC721: 0x80ac58cd, ERC721Metadata: 0x5b5e139f.\n            result := or(or(eq(s, 0x01ffc9a7), eq(s, 0x80ac58cd)), eq(s, 0x5b5e139f))\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                  OWNER SYNCING OPERATIONS                  */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns the `owner` of the contract, for marketplace signaling purposes.\n    function owner() public view virtual returns (address) {\n        return _getDN404NFTStorage().owner;\n    }\n\n    /// @dev Permissionless function to pull the owner from the base DN404 contract\n    /// if it implements ownable, for marketplace signaling purposes.\n    function pullOwner() public virtual {\n        address newOwner;\n        address base = baseERC20();\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x00, 0x8da5cb5b) // `owner()`.\n            if and(gt(returndatasize(), 0x1f), staticcall(gas(), base, 0x1c, 0x04, 0x00, 0x20)) {\n                newOwner := shr(96, mload(0x0c))\n            }\n        }\n        DN404NFTStorage storage $ = _getDN404NFTStorage();\n        address oldOwner = $.owner;\n        if (oldOwner != newOwner) {\n            $.owner = newOwner;\n            emit OwnershipTransferred(oldOwner, newOwner);\n        }\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                     MIRROR OPERATIONS                      */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Returns the address of the base DN404 contract.\n    function baseERC20() public view virtual returns (address base) {\n        base = _getDN404NFTStorage().baseERC20;\n        if (base == address(0)) revert NotLinked();\n    }\n\n    /// @dev Fallback modifier to execute calls from the base DN404 contract.\n    modifier dn404NFTFallback() virtual {\n        DN404NFTStorage storage $ = _getDN404NFTStorage();\n\n        uint256 fnSelector = _calldataload(0x00) >> 224;\n\n        // `logTransfer(uint256[])`.\n        if (fnSelector == 0x263c69d6) {\n            if (msg.sender != $.baseERC20) revert SenderNotBase();\n            /// @solidity memory-safe-assembly\n            assembly {\n                let o := add(0x24, calldataload(0x04)) // Packed logs offset.\n                let end := add(o, shl(5, calldataload(sub(o, 0x20))))\n\n                for {} iszero(eq(o, end)) { o := add(0x20, o) } {\n                    let d := calldataload(o) // Entry in the packed logs.\n                    let a := shr(96, d) // The address.\n                    let b := and(1, d) // Whether it is a burn.\n                    log4(\n                        codesize(),\n                        0x00,\n                        _TRANSFER_EVENT_SIGNATURE,\n                        mul(a, b), // `from`.\n                        mul(a, iszero(b)), // `to`.\n                        shr(168, shl(160, d)) // `id`.\n                    )\n                }\n                mstore(0x00, 0x01)\n                return(0x00, 0x20)\n            }\n        }\n        // `logDirectTransfer(address,address,uint256[])`.\n        if (fnSelector == 0x144027d3) {\n            if (msg.sender != $.baseERC20) revert SenderNotBase();\n            /// @solidity memory-safe-assembly\n            assembly {\n                let from := calldataload(0x04)\n                let to := calldataload(0x24)\n                let o := add(0x24, calldataload(0x44)) // Direct logs offset.\n                let end := add(o, shl(5, calldataload(sub(o, 0x20))))\n\n                for {} iszero(eq(o, end)) { o := add(0x20, o) } {\n                    log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, calldataload(o))\n                }\n                mstore(0x00, 0x01)\n                return(0x00, 0x20)\n            }\n        }\n        // `linkMirrorContract(address)`.\n        if (fnSelector == 0x0f4599e5) {\n            if ($.deployer != address(0)) {\n                if (address(uint160(_calldataload(0x04))) != $.deployer) {\n                    revert SenderNotDeployer();\n                }\n            }\n            if ($.baseERC20 != address(0)) revert AlreadyLinked();\n            $.baseERC20 = msg.sender;\n            /// @solidity memory-safe-assembly\n            assembly {\n                mstore(0x00, 0x01)\n                return(0x00, 0x20)\n            }\n        }\n        _;\n    }\n\n    /// @dev Fallback function for calls from base DN404 contract.\n    /// Override this if you need to implement your custom\n    /// fallback with utilities like Solady's `LibZip.cdFallback()`.\n    /// And always remember to always wrap the fallback with `dn404NFTFallback`.\n    fallback() external payable virtual dn404NFTFallback {\n        revert FnSelectorNotRecognized(); // Not mandatory. Just for quality of life.\n    }\n\n    /// @dev This is to silence the compiler warning.\n    /// Override and remove the revert if you want your contract to receive ETH via receive.\n    receive() external payable virtual {\n        if (msg.value != 0) revert();\n    }\n\n    /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/\n    /*                      PRIVATE HELPERS                       */\n    /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/\n\n    /// @dev Helper to read a string from the base DN404 contract.\n    function _readString(uint256 fnSelector, uint256 arg0)\n        private\n        view\n        returns (string memory result)\n    {\n        address base = baseERC20();\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := mload(0x40)\n            mstore(0x00, fnSelector)\n            mstore(0x20, arg0)\n            if iszero(staticcall(gas(), base, 0x1c, 0x24, 0x00, 0x00)) {\n                returndatacopy(result, 0x00, returndatasize())\n                revert(result, returndatasize())\n            }\n            returndatacopy(0x00, 0x00, 0x20) // Copy the offset of the string in returndata.\n            returndatacopy(result, mload(0x00), 0x20) // Copy the length of the string.\n            returndatacopy(add(result, 0x20), add(mload(0x00), 0x20), mload(result)) // Copy the string.\n            mstore(0x40, add(add(result, 0x20), mload(result))) // Allocate memory.\n        }\n    }\n\n    /// @dev Helper to read a word from the base DN404 contract.\n    function _readWord(uint256 fnSelector, uint256 arg0, uint256 arg1)\n        private\n        view\n        returns (uint256 result)\n    {\n        address base = baseERC20();\n        /// @solidity memory-safe-assembly\n        assembly {\n            let m := mload(0x40)\n            mstore(0x00, fnSelector)\n            mstore(0x20, arg0)\n            mstore(0x40, arg1)\n            if iszero(\n                and(gt(returndatasize(), 0x1f), staticcall(gas(), base, 0x1c, 0x44, 0x00, 0x20))\n            ) {\n                returndatacopy(m, 0x00, returndatasize())\n                revert(m, returndatasize())\n            }\n            mstore(0x40, m) // Restore the free memory pointer.\n            result := mload(0x00)\n        }\n    }\n\n    /// @dev Returns the calldata value at `offset`.\n    function _calldataload(uint256 offset) private pure returns (uint256 value) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            value := calldataload(offset)\n        }\n    }\n\n    /// @dev Returns if `a` has bytecode of non-zero length.\n    function _hasCode(address a) private view returns (bool result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := extcodesize(a) // Can handle dirty upper bits.\n        }\n    }\n\n    /// @dev Perform a call to invoke {IERC721Receiver-onERC721Received} on `to`.\n    /// Reverts if the target does not support the function correctly.\n    function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data)\n        private\n    {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Prepare the calldata.\n            let m := mload(0x40)\n            let onERC721ReceivedSelector := 0x150b7a02\n            mstore(m, onERC721ReceivedSelector)\n            mstore(add(m, 0x20), caller()) // The `operator`, which is always `msg.sender`.\n            mstore(add(m, 0x40), shr(96, shl(96, from)))\n            mstore(add(m, 0x60), id)\n            mstore(add(m, 0x80), 0x80)\n            let n := mload(data)\n            mstore(add(m, 0xa0), n)\n            if n { pop(staticcall(gas(), 4, add(data, 0x20), n, add(m, 0xc0), n)) }\n            // Revert if the call reverts.\n            if iszero(call(gas(), to, 0, add(m, 0x1c), add(n, 0xa4), m, 0x20)) {\n                if returndatasize() {\n                    // Bubble up the revert if the call reverts.\n                    returndatacopy(m, 0x00, returndatasize())\n                    revert(m, returndatasize())\n                }\n            }\n            // Load the returndata and compare it.\n            if iszero(eq(mload(m), shl(224, onERC721ReceivedSelector))) {\n                mstore(0x00, 0xd1a57ed6) // `TransferToNonERC721ReceiverImplementer()`.\n                revert(0x1c, 0x04)\n            }\n        }\n    }\n}\n"
      },
      "solady/src/utils/ECDSA.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Gas optimized ECDSA wrapper.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol)\nlibrary ECDSA {\n    function recover(bytes32 hash, bytes calldata signature) internal view returns (address result) {\n        assembly {\n            if eq(signature.length, 65) {\n                // Copy the free memory pointer so that we can restore it later.\n                let m := mload(0x40)\n                // Directly copy `r` and `s` from the calldata.\n                calldatacopy(0x40, signature.offset, 0x40)\n\n                // If `s` in lower half order, such that the signature is not malleable.\n                // prettier-ignore\n                if iszero(gt(mload(0x60), 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) {\n                    mstore(0x00, hash)\n                    // Compute `v` and store it in the scratch space.\n                    mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40))))\n                    pop(\n                        staticcall(\n                            gas(), // Amount of gas left for the transaction.\n                            0x01, // Address of `ecrecover`.\n                            0x00, // Start of input.\n                            0x80, // Size of input.\n                            0x40, // Start of output.\n                            0x20 // Size of output.\n                        )\n                    )\n                    // Restore the zero slot.\n                    mstore(0x60, 0)\n                    // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.\n                    result := mload(sub(0x60, returndatasize()))\n                }\n                // Restore the free memory pointer.\n                mstore(0x40, m)\n            }\n        }\n    }\n\n    function recover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal view returns (address result) {\n        assembly {\n            // Copy the free memory pointer so that we can restore it later.\n            let m := mload(0x40)\n            // prettier-ignore\n            let s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n\n            // If `s` in lower half order, such that the signature is not malleable.\n            // prettier-ignore\n            if iszero(gt(s, 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) {\n                mstore(0x00, hash)\n                mstore(0x20, add(shr(255, vs), 27))\n                mstore(0x40, r)\n                mstore(0x60, s)\n                pop(\n                    staticcall(\n                        gas(), // Amount of gas left for the transaction.\n                        0x01, // Address of `ecrecover`.\n                        0x00, // Start of input.\n                        0x80, // Size of input.\n                        0x40, // Start of output.\n                        0x20 // Size of output.\n                    )\n                )\n                // Restore the zero slot.\n                mstore(0x60, 0)\n                // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.\n                result := mload(sub(0x60, returndatasize()))\n            }\n            // Restore the free memory pointer.\n            mstore(0x40, m)\n        }\n    }\n\n    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {\n        assembly {\n            // Store into scratch space for keccak256.\n            mstore(0x20, hash)\n            mstore(0x00, \"\\x00\\x00\\x00\\x00\\x19Ethereum Signed Message:\\n32\")\n            // 0x40 - 0x04 = 0x3c\n            result := keccak256(0x04, 0x3c)\n        }\n    }\n\n    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {\n        assembly {\n            // We need at most 128 bytes for Ethereum signed message header.\n            // The max length of the ASCII reprenstation of a uint256 is 78 bytes.\n            // The length of \"\\x19Ethereum Signed Message:\\n\" is 26 bytes (i.e. 0x1a).\n            // The next multiple of 32 above 78 + 26 is 128 (i.e. 0x80).\n\n            // Instead of allocating, we temporarily copy the 128 bytes before the\n            // start of `s` data to some variables.\n            let m3 := mload(sub(s, 0x60))\n            let m2 := mload(sub(s, 0x40))\n            let m1 := mload(sub(s, 0x20))\n            // The length of `s` is in bytes.\n            let sLength := mload(s)\n\n            let ptr := add(s, 0x20)\n\n            // `end` marks the end of the memory which we will compute the keccak256 of.\n            let end := add(ptr, sLength)\n\n            // Convert the length of the bytes to ASCII decimal representation\n            // and store it into the memory.\n            // prettier-ignore\n            for { let temp := sLength } 1 {} {\n                ptr := sub(ptr, 1)\n                mstore8(ptr, add(48, mod(temp, 10)))\n                temp := div(temp, 10)\n                // prettier-ignore\n                if iszero(temp) { break }\n            }\n\n            // Copy the header over to the memory.\n            mstore(sub(ptr, 0x20), \"\\x00\\x00\\x00\\x00\\x00\\x00\\x19Ethereum Signed Message:\\n\")\n            // Compute the keccak256 of the memory.\n            result := keccak256(sub(ptr, 0x1a), sub(end, sub(ptr, 0x1a)))\n\n            // Restore the previous memory.\n            mstore(s, sLength)\n            mstore(sub(s, 0x20), m1)\n            mstore(sub(s, 0x40), m2)\n            mstore(sub(s, 0x60), m3)\n        }\n    }\n}\n"
      },
      "solady/src/utils/LibString.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Library for converting numbers into strings and other string operations.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)\nlibrary LibString {\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                        CUSTOM ERRORS                       */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    error HexLengthInsufficient();\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                     DECIMAL OPERATIONS                     */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    function toString(uint256 value) internal pure returns (string memory str) {\n        assembly {\n            // The maximum value of a uint256 contains 78 digits (1 byte per digit), but\n            // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.\n            // We will need 1 word for the trailing zeros padding, 1 word for the length,\n            // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.\n            let m := add(mload(0x40), 0xa0)\n            // Update the free memory pointer to allocate.\n            mstore(0x40, m)\n            // Assign the `str` to the end.\n            str := sub(m, 0x20)\n            // Zeroize the slot after the string.\n            mstore(str, 0)\n\n            // Cache the end of the memory to calculate the length later.\n            let end := str\n\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            // prettier-ignore\n            for { let temp := value } 1 {} {\n                str := sub(str, 1)\n                // Write the character to the pointer.\n                // The ASCII index of the '0' character is 48.\n                mstore8(str, add(48, mod(temp, 10)))\n                // Keep dividing `temp` until zero.\n                temp := div(temp, 10)\n                // prettier-ignore\n                if iszero(temp) { break }\n            }\n\n            let length := sub(end, str)\n            // Move the pointer 32 bytes leftwards to make room for the length.\n            str := sub(str, 0x20)\n            // Store the length.\n            mstore(str, length)\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                   HEXADECIMAL OPERATIONS                   */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {\n        assembly {\n            let start := mload(0x40)\n            // We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes\n            // for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.\n            // We add 0x20 to the total and round down to a multiple of 0x20.\n            // (0x20 + 0x20 + 0x02 + 0x20) = 0x62.\n            let m := add(start, and(add(shl(1, length), 0x62), not(0x1f)))\n            // Allocate the memory.\n            mstore(0x40, m)\n            // Assign the `str` to the end.\n            str := sub(m, 0x20)\n            // Zeroize the slot after the string.\n            mstore(str, 0)\n\n            // Cache the end to calculate the length later.\n            let end := str\n            // Store \"0123456789abcdef\" in scratch space.\n            mstore(0x0f, 0x30313233343536373839616263646566)\n\n            let temp := value\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            // prettier-ignore\n            for {} 1 {} {\n                str := sub(str, 2)\n                mstore8(add(str, 1), mload(and(temp, 15)))\n                mstore8(str, mload(and(shr(4, temp), 15)))\n                temp := shr(8, temp)\n                length := sub(length, 1)\n                // prettier-ignore\n                if iszero(length) { break }\n            }\n\n            if temp {\n                // Store the function selector of `HexLengthInsufficient()`.\n                mstore(0x00, 0x2194895a)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n\n            // Compute the string's length.\n            let strLength := add(sub(end, str), 2)\n            // Move the pointer and write the \"0x\" prefix.\n            str := sub(str, 0x20)\n            mstore(str, 0x3078)\n            // Move the pointer and write the length.\n            str := sub(str, 2)\n            mstore(str, strLength)\n        }\n    }\n\n    function toHexString(uint256 value) internal pure returns (string memory str) {\n        assembly {\n            let start := mload(0x40)\n            // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,\n            // 0x02 bytes for the prefix, and 0x40 bytes for the digits.\n            // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.\n            let m := add(start, 0xa0)\n            // Allocate the memory.\n            mstore(0x40, m)\n            // Assign the `str` to the end.\n            str := sub(m, 0x20)\n            // Zeroize the slot after the string.\n            mstore(str, 0)\n\n            // Cache the end to calculate the length later.\n            let end := str\n            // Store \"0123456789abcdef\" in scratch space.\n            mstore(0x0f, 0x30313233343536373839616263646566)\n\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            // prettier-ignore\n            for { let temp := value } 1 {} {\n                str := sub(str, 2)\n                mstore8(add(str, 1), mload(and(temp, 15)))\n                mstore8(str, mload(and(shr(4, temp), 15)))\n                temp := shr(8, temp)\n                // prettier-ignore\n                if iszero(temp) { break }\n            }\n\n            // Compute the string's length.\n            let strLength := add(sub(end, str), 2)\n            // Move the pointer and write the \"0x\" prefix.\n            str := sub(str, 0x20)\n            mstore(str, 0x3078)\n            // Move the pointer and write the length.\n            str := sub(str, 2)\n            mstore(str, strLength)\n        }\n    }\n\n    function toHexString(address value) internal pure returns (string memory str) {\n        assembly {\n            let start := mload(0x40)\n            // We need 0x20 bytes for the length, 0x02 bytes for the prefix,\n            // and 0x28 bytes for the digits.\n            // The next multiple of 0x20 above (0x20 + 0x02 + 0x28) is 0x60.\n            str := add(start, 0x60)\n\n            // Allocate the memory.\n            mstore(0x40, str)\n            // Store \"0123456789abcdef\" in scratch space.\n            mstore(0x0f, 0x30313233343536373839616263646566)\n\n            let length := 20\n            // We write the string from rightmost digit to leftmost digit.\n            // The following is essentially a do-while loop that also handles the zero case.\n            // prettier-ignore\n            for { let temp := value } 1 {} {\n                str := sub(str, 2)\n                mstore8(add(str, 1), mload(and(temp, 15)))\n                mstore8(str, mload(and(shr(4, temp), 15)))\n                temp := shr(8, temp)\n                length := sub(length, 1)\n                // prettier-ignore\n                if iszero(length) { break }\n            }\n\n            // Move the pointer and write the \"0x\" prefix.\n            str := sub(str, 32)\n            mstore(str, 0x3078)\n            // Move the pointer and write the length.\n            str := sub(str, 2)\n            mstore(str, 42)\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                   OTHER STRING OPERATIONS                  */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    function replace(\n        string memory subject,\n        string memory search,\n        string memory replacement\n    ) internal pure returns (string memory result) {\n        assembly {\n            let subjectLength := mload(subject)\n            let searchLength := mload(search)\n            let replacementLength := mload(replacement)\n\n            subject := add(subject, 0x20)\n            search := add(search, 0x20)\n            replacement := add(replacement, 0x20)\n            result := add(mload(0x40), 0x20)\n\n            let subjectEnd := add(subject, subjectLength)\n            if iszero(gt(searchLength, subjectLength)) {\n                let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)\n                let h := 0\n                if iszero(lt(searchLength, 32)) {\n                    h := keccak256(search, searchLength)\n                }\n                let m := shl(3, sub(32, and(searchLength, 31)))\n                let s := mload(search)\n                // prettier-ignore\n                for {} 1 {} {\n                    let t := mload(subject)\n                    // Whether the first `searchLength % 32` bytes of \n                    // `subject` and `search` matches.\n                    if iszero(shr(m, xor(t, s))) {\n                        if h {\n                            if iszero(eq(keccak256(subject, searchLength), h)) {\n                                mstore(result, t)\n                                result := add(result, 1)\n                                subject := add(subject, 1)\n                                // prettier-ignore\n                                if iszero(lt(subject, subjectSearchEnd)) { break }\n                                continue\n                            }\n                        }\n                        // Copy the `replacement` one word at a time.\n                        // prettier-ignore\n                        for { let o := 0 } 1 {} {\n                            mstore(add(result, o), mload(add(replacement, o)))\n                            o := add(o, 0x20)\n                            // prettier-ignore\n                            if iszero(lt(o, replacementLength)) { break }\n                        }\n                        result := add(result, replacementLength)\n                        subject := add(subject, searchLength)    \n                        if iszero(searchLength) {\n                            mstore(result, t)\n                            result := add(result, 1)\n                            subject := add(subject, 1)\n                        }\n                        // prettier-ignore\n                        if iszero(lt(subject, subjectSearchEnd)) { break }\n                        continue\n                    }\n                    mstore(result, t)\n                    result := add(result, 1)\n                    subject := add(subject, 1)\n                    // prettier-ignore\n                    if iszero(lt(subject, subjectSearchEnd)) { break }\n                }\n            }\n\n            let resultRemainder := result\n            result := add(mload(0x40), 0x20)\n            let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))\n            // Copy the rest of the string one word at a time.\n            // prettier-ignore\n            for {} lt(subject, subjectEnd) {} {\n                mstore(resultRemainder, mload(subject))\n                resultRemainder := add(resultRemainder, 0x20)\n                subject := add(subject, 0x20)\n            }\n            // Allocate memory for the length and the bytes,\n            // rounded up to a multiple of 32.\n            mstore(0x40, add(result, and(add(k, 0x40), not(0x1f))))\n            result := sub(result, 0x20)\n            mstore(result, k)\n        }\n    }\n}\n"
      },
      "solady/src/utils/MerkleProofLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol)\nlibrary MerkleProofLib {\n    function verify(\n        bytes32[] calldata proof,\n        bytes32 root,\n        bytes32 leaf\n    ) internal pure returns (bool isValid) {\n        assembly {\n            if proof.length {\n                // Left shift by 5 is equivalent to multiplying by 0x20.\n                let end := add(proof.offset, shl(5, proof.length))\n                // Initialize `offset` to the offset of `proof` in the calldata.\n                let offset := proof.offset\n                // Iterate over proof elements to compute root hash.\n                // prettier-ignore\n                for {} 1 {} {\n                    // Slot of `leaf` in scratch space.\n                    // If the condition is true: 0x20, otherwise: 0x00.\n                    let scratch := shl(5, gt(leaf, calldataload(offset)))\n                    // Store elements to hash contiguously in scratch space.\n                    // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.\n                    mstore(scratch, leaf)\n                    mstore(xor(scratch, 0x20), calldataload(offset))\n                    // Reuse `leaf` to store the hash to reduce stack operations.\n                    leaf := keccak256(0x00, 0x40)\n                    offset := add(offset, 0x20)\n                    // prettier-ignore\n                    if iszero(lt(offset, end)) { break }\n                }\n            }\n            isValid := eq(leaf, root)\n        }\n    }\n\n    function verifyMultiProof(\n        bytes32[] calldata proof,\n        bytes32 root,\n        bytes32[] calldata leafs,\n        bool[] calldata flags\n    ) internal pure returns (bool isValid) {\n        // Rebuilds the root by consuming and producing values on a queue.\n        // The queue starts with the `leafs` array, and goes into a `hashes` array.\n        // After the process, the last element on the queue is verified\n        // to be equal to the `root`.\n        //\n        // The `flags` array denotes whether the sibling\n        // should be popped from the queue (`flag == true`), or\n        // should be popped from the `proof` (`flag == false`).\n        assembly {\n            // If the number of flags is correct.\n            // prettier-ignore\n            for {} eq(add(leafs.length, proof.length), add(flags.length, 1)) {} {\n                // Left shift by 5 is equivalent to multiplying by 0x20.\n                // Compute the end calldata offset of `leafs`.\n                let leafsEnd := add(leafs.offset, shl(5, leafs.length))\n                // These are the calldata offsets.\n                let leafsOffset := leafs.offset\n                let flagsOffset := flags.offset\n                let proofOffset := proof.offset\n\n                // We can use the free memory space for the queue.\n                // We don't need to allocate, since the queue is temporary.\n                let hashesFront := mload(0x40)\n                let hashesBack := hashesFront\n                // This is the end of the memory for the queue.\n                let end := add(hashesBack, shl(5, flags.length))\n\n                // For the case where `proof.length + leafs.length == 1`.\n                if iszero(flags.length) {\n                    // If `proof.length` is zero, `leafs.length` is 1.\n                    if iszero(proof.length) {\n                        isValid := eq(calldataload(leafsOffset), root)\n                        break\n                    }\n                    // If `leafs.length` is zero, `proof.length` is 1.\n                    if iszero(leafs.length) {\n                        isValid := eq(calldataload(proofOffset), root)\n                        break\n                    }\n                }\n\n                // prettier-ignore\n                for {} 1 {} {\n                    let a := 0\n                    // Pops a value from the queue into `a`.\n                    switch lt(leafsOffset, leafsEnd)\n                    case 0 {\n                        // Pop from `hashes` if there are no more leafs.\n                        a := mload(hashesFront)\n                        hashesFront := add(hashesFront, 0x20)\n                    }\n                    default {\n                        // Otherwise, pop from `leafs`.\n                        a := calldataload(leafsOffset)\n                        leafsOffset := add(leafsOffset, 0x20)\n                    }\n\n                    let b := 0\n                    // If the flag is false, load the next proof,\n                    // else, pops from the queue.\n                    switch calldataload(flagsOffset)\n                    case 0 {\n                        // Loads the next proof.\n                        b := calldataload(proofOffset)\n                        proofOffset := add(proofOffset, 0x20)\n                    }\n                    default {\n                        // Pops a value from the queue into `a`.\n                        switch lt(leafsOffset, leafsEnd)\n                        case 0 {\n                            // Pop from `hashes` if there are no more leafs.\n                            b := mload(hashesFront)\n                            hashesFront := add(hashesFront, 0x20)\n                        }\n                        default {\n                            // Otherwise, pop from `leafs`.\n                            b := calldataload(leafsOffset)\n                            leafsOffset := add(leafsOffset, 0x20)\n                        }\n                    }\n                    // Advance to the next flag offset.\n                    flagsOffset := add(flagsOffset, 0x20)\n\n                    // Slot of `a` in scratch space.\n                    // If the condition is true: 0x20, otherwise: 0x00.\n                    let scratch := shl(5, gt(a, b))\n                    // Hash the scratch space and push the result onto the queue.\n                    mstore(scratch, a)\n                    mstore(xor(scratch, 0x20), b)\n                    mstore(hashesBack, keccak256(0x00, 0x40))\n                    hashesBack := add(hashesBack, 0x20)\n                    // prettier-ignore\n                    if iszero(lt(hashesBack, end)) { break }\n                }\n                // Checks if the last value in the queue is same as the root.\n                isValid := eq(mload(sub(hashesBack, 0x20)), root)\n                break\n            }\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}