ETH Price: $2,561.02 (+1.59%)

Transaction Decoder

Block:
22854028 at Jul-05-2025 03:51:59 PM +UTC
Transaction Fee:
0.000101610266192673 ETH $0.26
Gas Used:
104,531 Gas / 0.972058683 Gwei

Emitted Events:

117 Archetype.Transfer( from=Sproto_Gremlins_Proxy, to=0xff130f62...Ce244ef50, tokenId=379 )
118 Sproto_Gremlins_Proxy.ONFTReceived( guid=41E84674D6FD77887D56514CFCB88934B5FF38EAFFB0EC91436046838EBC099D, srcEid=30362, toAddress=0xff130f62...Ce244ef50, tokenId=379 )
119 EndpointV2.PacketDelivered( origin=[{name:srcEid, type:uint32, order:1, indexed:false, value:30362, valueString:30362}, {name:sender, type:bytes32, order:2, indexed:false, value:000000000000000000000000A23B2641ED799955A53DA001A925508C75EEFFE8, valueString:000000000000000000000000A23B2641ED799955A53DA001A925508C75EEFFE8}, {name:nonce, type:uint64, order:3, indexed:false, value:6, valueString:6}], receiver=Sproto_Gremlins_Proxy )

Account State Difference:

  Address   Before After State Difference Code
0x1a440760...c50fE728c
(LayerZero: EndpointV2)
(Titan Builder)
19.01888023478813529 Eth19.018929261379316109 Eth0.000049026591180819
0xe93685f3...95988D950
(Layer Zero: Executor)
44.870311574002161378 Eth
Nonce: 2177322
44.870209963735968705 Eth
Nonce: 2177323
0.000101610266192673
0xEeca64ea...6e8D54925

Execution Trace

OptimizedTransparentUpgradeableProxy.cfc32570( )
  • 0xfe9ab78ed4f9f3dbb168d9f5e5213d78605c9805.cfc32570( )
    • EndpointV2.lzReceive( _origin=[{name:srcEid, type:uint32, order:1, indexed:false, value:30362, valueString:30362}, {name:sender, type:bytes32, order:2, indexed:false, value:000000000000000000000000A23B2641ED799955A53DA001A925508C75EEFFE8, valueString:000000000000000000000000A23B2641ED799955A53DA001A925508C75EEFFE8}, {name:nonce, type:uint64, order:3, indexed:false, value:6, valueString:6}], _receiver=0xfdCeC6b311bdd78255606FB7932ea42cFD012e8F, _guid=41E84674D6FD77887D56514CFCB88934B5FF38EAFFB0EC91436046838EBC099D, _message=0x000000000000000000000000FF130F62568496AC83FDEE22FD18FF7CE244EF50000000000000000000000000000000000000000000000000000000000000017B, _extraData=0x )
      • Sproto_Gremlins_Proxy.lzReceive( _origin=[{name:srcEid, type:uint32, order:1, indexed:false, value:30362, valueString:30362}, {name:sender, type:bytes32, order:2, indexed:false, value:000000000000000000000000A23B2641ED799955A53DA001A925508C75EEFFE8, valueString:000000000000000000000000A23B2641ED799955A53DA001A925508C75EEFFE8}, {name:nonce, type:uint64, order:3, indexed:false, value:6, valueString:6}], _guid=41E84674D6FD77887D56514CFCB88934B5FF38EAFFB0EC91436046838EBC099D, _message=0x000000000000000000000000FF130F62568496AC83FDEE22FD18FF7CE244EF50000000000000000000000000000000000000000000000000000000000000017B, _executor=0x173272739Bd7Aa6e4e214714048a9fE699453059, _extraData=0x )
        • Archetype.transferFrom( from=0xfdCeC6b311bdd78255606FB7932ea42cFD012e8F, to=0xff130f62568496ac83FdeE22fd18fF7Ce244ef50, tokenId=379 )
          • Archetype.transferFrom( from=0xfdCeC6b311bdd78255606FB7932ea42cFD012e8F, to=0xff130f62568496ac83FdeE22fd18fF7Ce244ef50, tokenId=379 )
            File 1 of 5: OptimizedTransparentUpgradeableProxy
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (interfaces/draft-IERC1822.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
             * proxy whose upgrades are fully controlled by the current implementation.
             */
            interface IERC1822Proxiable {
                /**
                 * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
                 * address.
                 *
                 * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
                 * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
                 * function revert if invoked through a proxy.
                 */
                function proxiableUUID() external view returns (bytes32);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)
            pragma solidity ^0.8.0;
            import "../Proxy.sol";
            import "./ERC1967Upgrade.sol";
            /**
             * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
             * implementation address that can be changed. This address is stored in storage in the location specified by
             * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
             * implementation behind the proxy.
             */
            contract ERC1967Proxy is Proxy, ERC1967Upgrade {
                /**
                 * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
                 *
                 * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
                 * function call, and allows initializating the storage of the proxy like a Solidity constructor.
                 */
                constructor(address _logic, bytes memory _data) payable {
                    assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                    _upgradeToAndCall(_logic, _data, false);
                }
                /**
                 * @dev Returns the current implementation address.
                 */
                function _implementation() internal view virtual override returns (address impl) {
                    return ERC1967Upgrade._getImplementation();
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/ERC1967/ERC1967Upgrade.sol)
            pragma solidity ^0.8.2;
            import "../beacon/IBeacon.sol";
            import "../../interfaces/draft-IERC1822.sol";
            import "../../utils/Address.sol";
            import "../../utils/StorageSlot.sol";
            /**
             * @dev This abstract contract provides getters and event emitting update functions for
             * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
             *
             * _Available since v4.1._
             *
             * @custom:oz-upgrades-unsafe-allow delegatecall
             */
            abstract contract ERC1967Upgrade {
                // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
                bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
                /**
                 * @dev Storage slot with the address of the current implementation.
                 * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
                 * validated in the constructor.
                 */
                bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                /**
                 * @dev Emitted when the implementation is upgraded.
                 */
                event Upgraded(address indexed implementation);
                /**
                 * @dev Returns the current implementation address.
                 */
                function _getImplementation() internal view returns (address) {
                    return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                }
                /**
                 * @dev Stores a new address in the EIP1967 implementation slot.
                 */
                function _setImplementation(address newImplementation) private {
                    require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                    StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                }
                /**
                 * @dev Perform implementation upgrade
                 *
                 * Emits an {Upgraded} event.
                 */
                function _upgradeTo(address newImplementation) internal {
                    _setImplementation(newImplementation);
                    emit Upgraded(newImplementation);
                }
                /**
                 * @dev Perform implementation upgrade with additional setup call.
                 *
                 * Emits an {Upgraded} event.
                 */
                function _upgradeToAndCall(
                    address newImplementation,
                    bytes memory data,
                    bool forceCall
                ) internal {
                    _upgradeTo(newImplementation);
                    if (data.length > 0 || forceCall) {
                        Address.functionDelegateCall(newImplementation, data);
                    }
                }
                /**
                 * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
                 *
                 * Emits an {Upgraded} event.
                 */
                function _upgradeToAndCallUUPS(
                    address newImplementation,
                    bytes memory data,
                    bool forceCall
                ) internal {
                    // Upgrades from old implementations will perform a rollback test. This test requires the new
                    // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
                    // this special case will break upgrade paths from old UUPS implementation to new ones.
                    if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
                        _setImplementation(newImplementation);
                    } else {
                        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                            require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
                        } catch {
                            revert("ERC1967Upgrade: new implementation is not UUPS");
                        }
                        _upgradeToAndCall(newImplementation, data, forceCall);
                    }
                }
                /**
                 * @dev Storage slot with the admin of the contract.
                 * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
                 * validated in the constructor.
                 */
                bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                /**
                 * @dev Emitted when the admin account has changed.
                 */
                event AdminChanged(address previousAdmin, address newAdmin);
                /**
                 * @dev Returns the current admin.
                 */
                function _getAdmin() internal view virtual returns (address) {
                    return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
                }
                /**
                 * @dev Stores a new address in the EIP1967 admin slot.
                 */
                function _setAdmin(address newAdmin) private {
                    require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                    StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
                }
                /**
                 * @dev Changes the admin of the proxy.
                 *
                 * Emits an {AdminChanged} event.
                 */
                function _changeAdmin(address newAdmin) internal {
                    emit AdminChanged(_getAdmin(), newAdmin);
                    _setAdmin(newAdmin);
                }
                /**
                 * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                 * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
                 */
                bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                /**
                 * @dev Emitted when the beacon is upgraded.
                 */
                event BeaconUpgraded(address indexed beacon);
                /**
                 * @dev Returns the current beacon.
                 */
                function _getBeacon() internal view returns (address) {
                    return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
                }
                /**
                 * @dev Stores a new beacon in the EIP1967 beacon slot.
                 */
                function _setBeacon(address newBeacon) private {
                    require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                    require(Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract");
                    StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
                }
                /**
                 * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
                 * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
                 *
                 * Emits a {BeaconUpgraded} event.
                 */
                function _upgradeBeaconToAndCall(
                    address newBeacon,
                    bytes memory data,
                    bool forceCall
                ) internal {
                    _setBeacon(newBeacon);
                    emit BeaconUpgraded(newBeacon);
                    if (data.length > 0 || forceCall) {
                        Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/Proxy.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
             * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
             * be specified by overriding the virtual {_implementation} function.
             *
             * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
             * different contract through the {_delegate} function.
             *
             * The success and return data of the delegated call will be returned back to the caller of the proxy.
             */
            abstract contract Proxy {
                /**
                 * @dev Delegates the current call to `implementation`.
                 *
                 * This function does not return to its internal call site, it will return directly to the external caller.
                 */
                function _delegate(address implementation) internal virtual {
                    assembly {
                        // Copy msg.data. We take full control of memory in this inline assembly
                        // block because it will not return to Solidity code. We overwrite the
                        // Solidity scratch pad at memory position 0.
                        calldatacopy(0, 0, calldatasize())
                        // Call the implementation.
                        // out and outsize are 0 because we don't know the size yet.
                        let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                        // Copy the returned data.
                        returndatacopy(0, 0, returndatasize())
                        switch result
                        // delegatecall returns 0 on error.
                        case 0 {
                            revert(0, returndatasize())
                        }
                        default {
                            return(0, returndatasize())
                        }
                    }
                }
                /**
                 * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
                 * and {_fallback} should delegate.
                 */
                function _implementation() internal view virtual returns (address);
                /**
                 * @dev Delegates the current call to the address returned by `_implementation()`.
                 *
                 * This function does not return to its internall call site, it will return directly to the external caller.
                 */
                function _fallback() internal virtual {
                    _beforeFallback();
                    _delegate(_implementation());
                }
                /**
                 * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
                 * function in the contract matches the call data.
                 */
                fallback() external payable virtual {
                    _fallback();
                }
                /**
                 * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                 * is empty.
                 */
                receive() external payable virtual {
                    _fallback();
                }
                /**
                 * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
                 * call, or as part of the Solidity `fallback` or `receive` functions.
                 *
                 * If overriden should call `super._beforeFallback()`.
                 */
                function _beforeFallback() internal virtual {}
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev This is the interface that {BeaconProxy} expects of its beacon.
             */
            interface IBeacon {
                /**
                 * @dev Must return an address that can be used as a delegate call target.
                 *
                 * {BeaconProxy} will check that this address is a contract.
                 */
                function implementation() external view returns (address);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol)
            pragma solidity ^0.8.1;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 * ====
                 *
                 * [IMPORTANT]
                 * ====
                 * You shouldn't rely on `isContract` to protect against flash loan attacks!
                 *
                 * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                 * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                 * constructor.
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize/address.code.length, which returns 0
                    // for contracts in construction, since the code is only stored at the end
                    // of the constructor execution.
                    return account.code.length > 0;
                }
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    (bool success, ) = recipient.call{value: amount}("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
                /**
                 * @dev Performs a Solidity function call using a low level `call`. A
                 * plain `call` is an unsafe replacement for a function call: use this
                 * function instead.
                 *
                 * If `target` reverts with a revert reason, it is bubbled up by this
                 * function (like regular Solidity function calls).
                 *
                 * Returns the raw returned data. To convert to the expected return value,
                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                 *
                 * Requirements:
                 *
                 * - `target` must be a contract.
                 * - calling `target` with `data` must not revert.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCall(target, data, "Address: low-level call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                 * `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but also transferring `value` wei to `target`.
                 *
                 * Requirements:
                 *
                 * - the calling contract must have an ETH balance of at least `value`.
                 * - the called Solidity function must be `payable`.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(address(this).balance >= value, "Address: insufficient balance for call");
                    require(isContract(target), "Address: call to non-contract");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    return functionStaticCall(target, data, "Address: low-level static call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    require(isContract(target), "Address: static call to non-contract");
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(isContract(target), "Address: delegate call to non-contract");
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        // Look for revert reason and bubble it up if present
                        if (returndata.length > 0) {
                            // The easiest way to bubble the revert reason is using memory via assembly
                            assembly {
                                let returndata_size := mload(returndata)
                                revert(add(32, returndata), returndata_size)
                            }
                        } else {
                            revert(errorMessage);
                        }
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Library for reading and writing primitive types to specific storage slots.
             *
             * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
             * This library helps with reading and writing to such slots without the need for inline assembly.
             *
             * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
             *
             * Example usage to set ERC1967 implementation slot:
             * ```
             * contract ERC1967 {
             *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
             *
             *     function _getImplementation() internal view returns (address) {
             *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
             *     }
             *
             *     function _setImplementation(address newImplementation) internal {
             *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
             *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
             *     }
             * }
             * ```
             *
             * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
             */
            library StorageSlot {
                struct AddressSlot {
                    address value;
                }
                struct BooleanSlot {
                    bool value;
                }
                struct Bytes32Slot {
                    bytes32 value;
                }
                struct Uint256Slot {
                    uint256 value;
                }
                /**
                 * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                 */
                function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                 */
                function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                 */
                function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                    assembly {
                        r.slot := slot
                    }
                }
                /**
                 * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                 */
                function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                    assembly {
                        r.slot := slot
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)
            pragma solidity ^0.8.0;
            import "../openzeppelin/proxy/ERC1967/ERC1967Proxy.sol";
            /**
             * @dev This contract implements a proxy that is upgradeable by an admin.
             *
             * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
             * clashing], which can potentially be used in an attack, this contract uses the
             * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
             * things that go hand in hand:
             *
             * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
             * that call matches one of the admin functions exposed by the proxy itself.
             * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
             * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
             * "admin cannot fallback to proxy target".
             *
             * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
             * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
             * to sudden errors when trying to call a function from the proxy implementation.
             *
             * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
             * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
             */
            contract OptimizedTransparentUpgradeableProxy is ERC1967Proxy {
                address internal immutable _ADMIN;
                /**
                 * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
                 * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
                 */
                constructor(
                    address _logic,
                    address admin_,
                    bytes memory _data
                ) payable ERC1967Proxy(_logic, _data) {
                    assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                    _ADMIN = admin_;
                    // still store it to work with EIP-1967
                    bytes32 slot = _ADMIN_SLOT;
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        sstore(slot, admin_)
                    }
                    emit AdminChanged(address(0), admin_);
                }
                /**
                 * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
                 */
                modifier ifAdmin() {
                    if (msg.sender == _getAdmin()) {
                        _;
                    } else {
                        _fallback();
                    }
                }
                /**
                 * @dev Returns the current admin.
                 *
                 * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
                 *
                 * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                 * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                 * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
                 */
                function admin() external ifAdmin returns (address admin_) {
                    admin_ = _getAdmin();
                }
                /**
                 * @dev Returns the current implementation.
                 *
                 * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
                 *
                 * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                 * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                 * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
                 */
                function implementation() external ifAdmin returns (address implementation_) {
                    implementation_ = _implementation();
                }
                /**
                 * @dev Upgrade the implementation of the proxy.
                 *
                 * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
                 */
                function upgradeTo(address newImplementation) external ifAdmin {
                    _upgradeToAndCall(newImplementation, bytes(""), false);
                }
                /**
                 * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
                 * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
                 * proxied contract.
                 *
                 * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
                 */
                function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
                    _upgradeToAndCall(newImplementation, data, true);
                }
                /**
                 * @dev Returns the current admin.
                 */
                function _admin() internal view virtual returns (address) {
                    return _getAdmin();
                }
                /**
                 * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
                 */
                function _beforeFallback() internal virtual override {
                    require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                    super._beforeFallback();
                }
                function _getAdmin() internal view virtual override returns (address) {
                    return _ADMIN;
                }
            }
            

            File 2 of 5: Archetype
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
            pragma solidity ^0.8.0;
            import "../utils/introspection/IERC165Upgradeable.sol";
            /**
             * @dev Interface for the NFT Royalty Standard.
             *
             * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
             * support for royalty payments across all NFT marketplaces and ecosystem participants.
             *
             * _Available since v4.5._
             */
            interface IERC2981Upgradeable is IERC165Upgradeable {
                /**
                 * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
                 * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
                 */
                function royaltyInfo(uint256 tokenId, uint256 salePrice)
                    external
                    view
                    returns (address receiver, uint256 royaltyAmount);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
            pragma solidity ^0.8.2;
            import "../../utils/AddressUpgradeable.sol";
            /**
             * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
             * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
             * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
             * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
             *
             * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
             * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
             * case an upgrade adds a module that needs to be initialized.
             *
             * For example:
             *
             * [.hljs-theme-light.nopadding]
             * ```
             * contract MyToken is ERC20Upgradeable {
             *     function initialize() initializer public {
             *         __ERC20_init("MyToken", "MTK");
             *     }
             * }
             * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
             *     function initializeV2() reinitializer(2) public {
             *         __ERC20Permit_init("MyToken");
             *     }
             * }
             * ```
             *
             * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
             * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
             *
             * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
             * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
             *
             * [CAUTION]
             * ====
             * Avoid leaving a contract uninitialized.
             *
             * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
             * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
             * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
             *
             * [.hljs-theme-light.nopadding]
             * ```
             * /// @custom:oz-upgrades-unsafe-allow constructor
             * constructor() {
             *     _disableInitializers();
             * }
             * ```
             * ====
             */
            abstract contract Initializable {
                /**
                 * @dev Indicates that the contract has been initialized.
                 * @custom:oz-retyped-from bool
                 */
                uint8 private _initialized;
                /**
                 * @dev Indicates that the contract is in the process of being initialized.
                 */
                bool private _initializing;
                /**
                 * @dev Triggered when the contract has been initialized or reinitialized.
                 */
                event Initialized(uint8 version);
                /**
                 * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
                 * `onlyInitializing` functions can be used to initialize parent contracts.
                 *
                 * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
                 * constructor.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier initializer() {
                    bool isTopLevelCall = !_initializing;
                    require(
                        (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                        "Initializable: contract is already initialized"
                    );
                    _initialized = 1;
                    if (isTopLevelCall) {
                        _initializing = true;
                    }
                    _;
                    if (isTopLevelCall) {
                        _initializing = false;
                        emit Initialized(1);
                    }
                }
                /**
                 * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
                 * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
                 * used to initialize parent contracts.
                 *
                 * A reinitializer may be used after the original initialization step. This is essential to configure modules that
                 * are added through upgrades and that require initialization.
                 *
                 * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
                 * cannot be nested. If one is invoked in the context of another, execution will revert.
                 *
                 * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
                 * a contract, executing them in the right order is up to the developer or operator.
                 *
                 * WARNING: setting the version to 255 will prevent any future reinitialization.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier reinitializer(uint8 version) {
                    require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                    _initialized = version;
                    _initializing = true;
                    _;
                    _initializing = false;
                    emit Initialized(version);
                }
                /**
                 * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                 * {initializer} and {reinitializer} modifiers, directly or indirectly.
                 */
                modifier onlyInitializing() {
                    require(_initializing, "Initializable: contract is not initializing");
                    _;
                }
                /**
                 * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
                 * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
                 * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
                 * through proxies.
                 *
                 * Emits an {Initialized} event the first time it is successfully executed.
                 */
                function _disableInitializers() internal virtual {
                    require(!_initializing, "Initializable: contract is initializing");
                    if (_initialized < type(uint8).max) {
                        _initialized = type(uint8).max;
                        emit Initialized(type(uint8).max);
                    }
                }
                /**
                 * @dev Internal function that returns the initialized version. Returns `_initialized`
                 */
                function _getInitializedVersion() internal view returns (uint8) {
                    return _initialized;
                }
                /**
                 * @dev Internal function that returns the initialized version. Returns `_initializing`
                 */
                function _isInitializing() internal view returns (bool) {
                    return _initializing;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
            pragma solidity ^0.8.0;
            import "../../interfaces/IERC2981Upgradeable.sol";
            import "../../utils/introspection/ERC165Upgradeable.sol";
            import "../../proxy/utils/Initializable.sol";
            /**
             * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
             *
             * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
             * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
             *
             * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
             * fee is specified in basis points by default.
             *
             * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
             * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
             * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
             *
             * _Available since v4.5._
             */
            abstract contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {
                function __ERC2981_init() internal onlyInitializing {
                }
                function __ERC2981_init_unchained() internal onlyInitializing {
                }
                struct RoyaltyInfo {
                    address receiver;
                    uint96 royaltyFraction;
                }
                RoyaltyInfo private _defaultRoyaltyInfo;
                mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
                /**
                 * @dev See {IERC165-supportsInterface}.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) {
                    return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId);
                }
                /**
                 * @inheritdoc IERC2981Upgradeable
                 */
                function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
                    RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
                    if (royalty.receiver == address(0)) {
                        royalty = _defaultRoyaltyInfo;
                    }
                    uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
                    return (royalty.receiver, royaltyAmount);
                }
                /**
                 * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
                 * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
                 * override.
                 */
                function _feeDenominator() internal pure virtual returns (uint96) {
                    return 10000;
                }
                /**
                 * @dev Sets the royalty information that all ids in this contract will default to.
                 *
                 * Requirements:
                 *
                 * - `receiver` cannot be the zero address.
                 * - `feeNumerator` cannot be greater than the fee denominator.
                 */
                function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
                    require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                    require(receiver != address(0), "ERC2981: invalid receiver");
                    _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
                }
                /**
                 * @dev Removes default royalty information.
                 */
                function _deleteDefaultRoyalty() internal virtual {
                    delete _defaultRoyaltyInfo;
                }
                /**
                 * @dev Sets the royalty information for a specific token id, overriding the global default.
                 *
                 * Requirements:
                 *
                 * - `receiver` cannot be the zero address.
                 * - `feeNumerator` cannot be greater than the fee denominator.
                 */
                function _setTokenRoyalty(
                    uint256 tokenId,
                    address receiver,
                    uint96 feeNumerator
                ) internal virtual {
                    require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                    require(receiver != address(0), "ERC2981: Invalid parameters");
                    _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
                }
                /**
                 * @dev Resets royalty information for the token id back to the global default.
                 */
                function _resetTokenRoyalty(uint256 tokenId) internal virtual {
                    delete _tokenRoyaltyInfo[tokenId];
                }
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[48] private __gap;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            interface IERC20Upgradeable {
                /**
                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                 * another (`to`).
                 *
                 * Note that `value` may be zero.
                 */
                event Transfer(address indexed from, address indexed to, uint256 value);
                /**
                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                 * a call to {approve}. `value` is the new allowance.
                 */
                event Approval(address indexed owner, address indexed spender, uint256 value);
                /**
                 * @dev Returns the amount of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
                /**
                 * @dev Returns the amount of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
                /**
                 * @dev Moves `amount` tokens from the caller's account to `to`.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transfer(address to, uint256 amount) external returns (bool);
                /**
                 * @dev Returns the remaining number of tokens that `spender` will be
                 * allowed to spend on behalf of `owner` through {transferFrom}. This is
                 * zero by default.
                 *
                 * This value changes when {approve} or {transferFrom} are called.
                 */
                function allowance(address owner, address spender) external view returns (uint256);
                /**
                 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * IMPORTANT: Beware that changing an allowance with this method brings the risk
                 * that someone may use both the old and the new allowance by unfortunate
                 * transaction ordering. One possible solution to mitigate this race
                 * condition is to first reduce the spender's allowance to 0 and set the
                 * desired value afterwards:
                 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address spender, uint256 amount) external returns (bool);
                /**
                 * @dev Moves `amount` tokens from `from` to `to` using the
                 * allowance mechanism. `amount` is then deducted from the caller's
                 * allowance.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 amount
                ) external returns (bool);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
            pragma solidity ^0.8.1;
            /**
             * @dev Collection of functions related to the address type
             */
            library AddressUpgradeable {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 * ====
                 *
                 * [IMPORTANT]
                 * ====
                 * You shouldn't rely on `isContract` to protect against flash loan attacks!
                 *
                 * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                 * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                 * constructor.
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize/address.code.length, which returns 0
                    // for contracts in construction, since the code is only stored at the end
                    // of the constructor execution.
                    return account.code.length > 0;
                }
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    (bool success, ) = recipient.call{value: amount}("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
                /**
                 * @dev Performs a Solidity function call using a low level `call`. A
                 * plain `call` is an unsafe replacement for a function call: use this
                 * function instead.
                 *
                 * If `target` reverts with a revert reason, it is bubbled up by this
                 * function (like regular Solidity function calls).
                 *
                 * Returns the raw returned data. To convert to the expected return value,
                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                 *
                 * Requirements:
                 *
                 * - `target` must be a contract.
                 * - calling `target` with `data` must not revert.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                 * `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but also transferring `value` wei to `target`.
                 *
                 * Requirements:
                 *
                 * - the calling contract must have an ETH balance of at least `value`.
                 * - the called Solidity function must be `payable`.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(address(this).balance >= value, "Address: insufficient balance for call");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    return functionStaticCall(target, data, "Address: low-level static call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                 * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                 *
                 * _Available since v4.8._
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    if (success) {
                        if (returndata.length == 0) {
                            // only check isContract if the call was successful and the return data is empty
                            // otherwise we already know that it was a contract
                            require(isContract(target), "Address: call to non-contract");
                        }
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason or using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                function _revert(bytes memory returndata, string memory errorMessage) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
            pragma solidity ^0.8.0;
            import "./IERC165Upgradeable.sol";
            import "../../proxy/utils/Initializable.sol";
            /**
             * @dev Implementation of the {IERC165} interface.
             *
             * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
             * for the additional interface id that will be supported. For example:
             *
             * ```solidity
             * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
             *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
             * }
             * ```
             *
             * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
             */
            abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
                function __ERC165_init() internal onlyInitializing {
                }
                function __ERC165_init_unchained() internal onlyInitializing {
                }
                /**
                 * @dev See {IERC165-supportsInterface}.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                    return interfaceId == type(IERC165Upgradeable).interfaceId;
                }
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[50] private __gap;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC165 standard, as defined in the
             * https://eips.ethereum.org/EIPS/eip-165[EIP].
             *
             * Implementers can declare support of contract interfaces, which can then be
             * queried by others ({ERC165Checker}).
             *
             * For an implementation, see {ERC165}.
             */
            interface IERC165Upgradeable {
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30 000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) external view returns (bool);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Optimized and flexible operator filterer to abide to OpenSea's
            /// mandatory on-chain royalty enforcement in order for new collections to
            /// receive royalties.
            /// For more information, see:
            /// See: https://github.com/ProjectOpenSea/operator-filter-registry
            abstract contract OperatorFilterer {
                /// @dev The default OpenSea operator blocklist subscription.
                address internal constant _DEFAULT_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6;
                /// @dev The OpenSea operator filter registry.
                address internal constant _OPERATOR_FILTER_REGISTRY = 0x000000000000AAeB6D7670E522A718067333cd4E;
                /// @dev Registers the current contract to OpenSea's operator filter,
                /// and subscribe to the default OpenSea operator blocklist.
                /// Note: Will not revert nor update existing settings for repeated registration.
                function _registerForOperatorFiltering() internal virtual {
                    _registerForOperatorFiltering(_DEFAULT_SUBSCRIPTION, true);
                }
                /// @dev Registers the current contract to OpenSea's operator filter.
                /// Note: Will not revert nor update existing settings for repeated registration.
                function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe)
                    internal
                    virtual
                {
                    /// @solidity memory-safe-assembly
                    assembly {
                        let functionSelector := 0x7d3e3dbe // `registerAndSubscribe(address,address)`.
                        // Clean the upper 96 bits of `subscriptionOrRegistrantToCopy` in case they are dirty.
                        subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy))
                        for {} iszero(subscribe) {} {
                            if iszero(subscriptionOrRegistrantToCopy) {
                                functionSelector := 0x4420e486 // `register(address)`.
                                break
                            }
                            functionSelector := 0xa0af2903 // `registerAndCopyEntries(address,address)`.
                            break
                        }
                        // Store the function selector.
                        mstore(0x00, shl(224, functionSelector))
                        // Store the `address(this)`.
                        mstore(0x04, address())
                        // Store the `subscriptionOrRegistrantToCopy`.
                        mstore(0x24, subscriptionOrRegistrantToCopy)
                        // Register into the registry.
                        if iszero(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x04)) {
                            // If the function selector has not been overwritten,
                            // it is an out-of-gas error.
                            if eq(shr(224, mload(0x00)), functionSelector) {
                                // To prevent gas under-estimation.
                                revert(0, 0)
                            }
                        }
                        // Restore the part of the free memory pointer that was overwritten,
                        // which is guaranteed to be zero, because of Solidity's memory size limits.
                        mstore(0x24, 0)
                    }
                }
                /// @dev Modifier to guard a function and revert if the caller is a blocked operator.
                modifier onlyAllowedOperator(address from) virtual {
                    if (from != msg.sender) {
                        if (!_isPriorityOperator(msg.sender)) {
                            if (_operatorFilteringEnabled()) _revertIfBlocked(msg.sender);
                        }
                    }
                    _;
                }
                /// @dev Modifier to guard a function from approving a blocked operator..
                modifier onlyAllowedOperatorApproval(address operator) virtual {
                    if (!_isPriorityOperator(operator)) {
                        if (_operatorFilteringEnabled()) _revertIfBlocked(operator);
                    }
                    _;
                }
                /// @dev Helper function that reverts if the `operator` is blocked by the registry.
                function _revertIfBlocked(address operator) private view {
                    /// @solidity memory-safe-assembly
                    assembly {
                        // Store the function selector of `isOperatorAllowed(address,address)`,
                        // shifted left by 6 bytes, which is enough for 8tb of memory.
                        // We waste 6-3 = 3 bytes to save on 6 runtime gas (PUSH1 0x224 SHL).
                        mstore(0x00, 0xc6171134001122334455)
                        // Store the `address(this)`.
                        mstore(0x1a, address())
                        // Store the `operator`.
                        mstore(0x3a, operator)
                        // `isOperatorAllowed` always returns true if it does not revert.
                        if iszero(staticcall(gas(), _OPERATOR_FILTER_REGISTRY, 0x16, 0x44, 0x00, 0x00)) {
                            // Bubble up the revert if the staticcall reverts.
                            returndatacopy(0x00, 0x00, returndatasize())
                            revert(0x00, returndatasize())
                        }
                        // We'll skip checking if `from` is inside the blacklist.
                        // Even though that can block transferring out of wrapper contracts,
                        // we don't want tokens to be stuck.
                        // Restore the part of the free memory pointer that was overwritten,
                        // which is guaranteed to be zero, if less than 8tb of memory is used.
                        mstore(0x3a, 0)
                    }
                }
                /// @dev For deriving contracts to override, so that operator filtering
                /// can be turned on / off.
                /// Returns true by default.
                function _operatorFilteringEnabled() internal view virtual returns (bool) {
                    return true;
                }
                /// @dev For deriving contracts to override, so that preferred marketplaces can
                /// skip operator filtering, helping users save gas.
                /// Returns false for all inputs by default.
                function _isPriorityOperator(address) internal view virtual returns (bool) {
                    return false;
                }
            }
            // SPDX-License-Identifier: MIT
            // Archetype v0.5.1
            //
            //        d8888                 888               888
            //       d88888                 888               888
            //      d88P888                 888               888
            //     d88P 888 888d888 .d8888b 88888b.   .d88b.  888888 888  888 88888b.   .d88b.
            //    d88P  888 888P"  d88P"    888 "88b d8P  Y8b 888    888  888 888 "88b d8P  Y8b
            //   d88P   888 888    888      888  888 88888888 888    888  888 888  888 88888888
            //  d8888888888 888    Y88b.    888  888 Y8b.     Y88b.  Y88b 888 888 d88P Y8b.
            // d88P     888 888     "Y8888P 888  888  "Y8888   "Y888  "Y88888 88888P"   "Y8888
            //                                                            888 888
            //                                                       Y8b d88P 888
            //                                                        "Y88P"  888
            pragma solidity ^0.8.4;
            import "./ArchetypeLogic.sol";
            import "erc721a-upgradeable/contracts/ERC721AUpgradeable.sol";
            import "erc721a-upgradeable/contracts/ERC721A__Initializable.sol";
            import "./ERC721A__OwnableUpgradeable.sol";
            import "solady/src/utils/LibString.sol";
            import "closedsea/src/OperatorFilterer.sol";
            import "@openzeppelin/contracts-upgradeable/token/common/ERC2981Upgradeable.sol";
            contract Archetype is
              ERC721A__Initializable,
              ERC721AUpgradeable,
              OperatorFilterer,
              ERC721A__OwnableUpgradeable,
              ERC2981Upgradeable
            {
              //
              // EVENTS
              //
              event Invited(bytes32 indexed key, bytes32 indexed cid);
              event Referral(address indexed affiliate, address token, uint128 wad, uint256 numMints);
              event Withdrawal(address indexed src, address token, uint128 wad);
              //
              // VARIABLES
              //
              mapping(bytes32 => DutchInvite) public invites;
              mapping(address => mapping(bytes32 => uint256)) private _minted;
              mapping(bytes32 => uint256) private _listSupply;
              mapping(address => OwnerBalance) private _ownerBalance;
              mapping(address => mapping(address => uint128)) private _affiliateBalance;
              mapping(uint256 => bytes) private _tokenMsg;
              Config public config;
              BurnConfig public burnConfig;
              Options public options;
              string public provenance;
              //
              // METHODS
              //
              function initialize(
                string memory name,
                string memory symbol,
                Config calldata config_,
                address _receiver
              ) external initializerERC721A {
                __ERC721A_init(name, symbol);
                // check max bps not reached and min platform fee.
                if (
                  config_.affiliateFee > MAXBPS ||
                  config_.platformFee > MAXBPS ||
                  config_.platformFee < 500 ||
                  config_.discounts.affiliateDiscount > MAXBPS ||
                  config_.affiliateSigner == address(0) ||
                  config_.maxBatchSize == 0
                ) {
                  revert InvalidConfig();
                }
                // ensure mint tiers are correctly ordered from highest to lowest.
                for (uint256 i = 1; i < config_.discounts.mintTiers.length; i++) {
                  if (
                    config_.discounts.mintTiers[i].mintDiscount > MAXBPS ||
                    config_.discounts.mintTiers[i].numMints > config_.discounts.mintTiers[i - 1].numMints
                  ) {
                    revert InvalidConfig();
                  }
                }
                config = config_;
                __Ownable_init();
                if (config.ownerAltPayout != address(0)) {
                  setDefaultRoyalty(config.ownerAltPayout, config.defaultRoyalty);
                } else {
                  setDefaultRoyalty(_receiver, config.defaultRoyalty);
                }
              }
              //
              // PUBLIC
              //
              function mint(
                Auth calldata auth,
                uint256 quantity,
                address affiliate,
                bytes calldata signature
              ) external payable {
                mintTo(auth, quantity, msg.sender, affiliate, signature);
              }
              function batchMintTo(
                Auth calldata auth,
                address[] calldata toList,
                uint256[] calldata quantityList,
                address affiliate,
                bytes calldata signature
              ) external payable {
                if (quantityList.length != toList.length) {
                  revert InvalidConfig();
                }
                DutchInvite storage invite = invites[auth.key];
                uint256 quantity = 0;
                {
                  uint32 unitSize = invite.unitSize;
                  for (uint256 i = 0; i < quantityList.length; i++) {
                    if (unitSize > 1) {
                      quantity += quantityList[i] * unitSize;
                    } else {
                      quantity += quantityList[i];
                    }
                  }
                }
                uint256 curSupply = _totalMinted();
                ArchetypeLogic.validateMint(
                  invite,
                  config,
                  auth,
                  quantity,
                  owner(),
                  affiliate,
                  curSupply,
                  _minted,
                  _listSupply,
                  signature
                );
                {
                  uint32 unitSize = invite.unitSize;
                  for (uint256 i = 0; i < toList.length; i++) {
                    if (unitSize > 1) {
                      _mint(toList[i], quantityList[i] * unitSize);
                    } else {
                      _mint(toList[i], quantityList[i]);
                    }
                  }
                }
                if (invite.limit < invite.maxSupply) {
                  _minted[msg.sender][auth.key] += quantity;
                }
                if (invite.maxSupply < config.maxSupply) {
                  _listSupply[auth.key] += quantity;
                }
                ArchetypeLogic.updateBalances(
                  invite,
                  config,
                  _ownerBalance,
                  _affiliateBalance,
                  affiliate,
                  quantity
                );
              }
              function mintTo(
                Auth calldata auth,
                uint256 quantity,
                address to,
                address affiliate,
                bytes calldata signature
              ) public payable {
                DutchInvite storage i = invites[auth.key];
                if (i.unitSize > 1) {
                  quantity = quantity * i.unitSize;
                }
                uint256 curSupply = _totalMinted();
                ArchetypeLogic.validateMint(
                  i,
                  config,
                  auth,
                  quantity,
                  owner(),
                  affiliate,
                  curSupply,
                  _minted,
                  _listSupply,
                  signature
                );
                _mint(to, quantity);
                if (i.limit < i.maxSupply) {
                  _minted[msg.sender][auth.key] += quantity;
                }
                if (i.maxSupply < config.maxSupply) {
                  _listSupply[auth.key] += quantity;
                }
                ArchetypeLogic.updateBalances(i, config, _ownerBalance, _affiliateBalance, affiliate, quantity);
              }
              function burnToMint(uint256[] calldata tokenIds) external {
                uint256 curSupply = _totalMinted();
                ArchetypeLogic.validateBurnToMint(config, burnConfig, tokenIds, curSupply, _minted);
                for (uint256 i = 0; i < tokenIds.length; i++) {
                  burnConfig.archetype.transferFrom(
                    msg.sender,
                    address(0x000000000000000000000000000000000000dEaD),
                    tokenIds[i]
                  );
                }
                uint256 quantity = burnConfig.reversed
                  ? tokenIds.length * burnConfig.ratio
                  : tokenIds.length / burnConfig.ratio;
                _mint(msg.sender, quantity);
                if (burnConfig.limit < config.maxSupply) {
                  _minted[msg.sender][bytes32("burn")] += quantity;
                }
              }
              function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                return
                  bytes(config.baseUri).length != 0
                    ? string(abi.encodePacked(config.baseUri, LibString.toString(tokenId)))
                    : "";
              }
              function withdraw() external {
                address[] memory tokens = new address[](1);
                tokens[0] = address(0);
                withdrawTokens(tokens);
              }
              function withdrawTokens(address[] memory tokens) public {
                ArchetypeLogic.withdrawTokens(config, _ownerBalance, _affiliateBalance, owner(), tokens);
              }
              function setTokenMsg(uint256 tokenId, string calldata message) external {
                if (msg.sender != ownerOf(tokenId)) {
                  revert NotTokenOwner();
                }
                _tokenMsg[tokenId] = bytes(message);
              }
              function getTokenMsg(uint256 tokenId) external view returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                return string(_tokenMsg[tokenId]);
              }
              function ownerBalance() external view returns (OwnerBalance memory) {
                return _ownerBalance[address(0)];
              }
              function ownerBalanceToken(address token) external view returns (OwnerBalance memory) {
                return _ownerBalance[token];
              }
              function affiliateBalance(address affiliate) external view returns (uint128) {
                return _affiliateBalance[affiliate][address(0)];
              }
              function affiliateBalanceToken(address affiliate, address token) external view returns (uint128) {
                return _affiliateBalance[affiliate][token];
              }
              function minted(address minter, bytes32 key) external view returns (uint256) {
                return _minted[minter][key];
              }
              function listSupply(bytes32 key) external view returns (uint256) {
                return _listSupply[key];
              }
              function platform() external pure returns (address) {
                return PLATFORM;
              }
              //
              // OWNER ONLY
              //
              function setBaseURI(string memory baseUri) external onlyOwner {
                if (options.uriLocked) {
                  revert LockedForever();
                }
                config.baseUri = baseUri;
              }
              /// @notice the password is "forever"
              function lockURI(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.uriLocked = true;
              }
              /// @notice the password is "forever"
              // max supply cannot subceed total supply. Be careful changing.
              function setMaxSupply(uint32 maxSupply, string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                if (options.maxSupplyLocked) {
                  revert LockedForever();
                }
                if (maxSupply < _totalMinted()) {
                  revert MaxSupplyExceeded();
                }
                config.maxSupply = maxSupply;
              }
              /// @notice the password is "forever"
              function lockMaxSupply(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.maxSupplyLocked = true;
              }
              function setAffiliateFee(uint16 affiliateFee) external onlyOwner {
                if (options.affiliateFeeLocked) {
                  revert LockedForever();
                }
                if (affiliateFee > MAXBPS) {
                  revert InvalidConfig();
                }
                config.affiliateFee = affiliateFee;
              }
              /// @notice the password is "forever"
              function lockAffiliateFee(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.affiliateFeeLocked = true;
              }
              function setDiscounts(Discount calldata discounts) external onlyOwner {
                if (options.discountsLocked) {
                  revert LockedForever();
                }
                if (discounts.affiliateDiscount > MAXBPS) {
                  revert InvalidConfig();
                }
                // ensure mint tiers are correctly ordered from highest to lowest.
                for (uint256 i = 1; i < discounts.mintTiers.length; i++) {
                  if (
                    discounts.mintTiers[i].mintDiscount > MAXBPS ||
                    discounts.mintTiers[i].numMints > discounts.mintTiers[i - 1].numMints
                  ) {
                    revert InvalidConfig();
                  }
                }
                config.discounts = discounts;
              }
              /// @notice the password is "forever"
              function lockDiscounts(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.discountsLocked = true;
              }
              /// @notice Set BAYC-style provenance once it's calculated
              function setProvenanceHash(string memory provenanceHash) external onlyOwner {
                if (options.provenanceHashLocked) {
                  revert LockedForever();
                }
                provenance = provenanceHash;
              }
              /// @notice the password is "forever"
              function lockProvenanceHash(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.provenanceHashLocked = true;
              }
              function setOwnerAltPayout(address ownerAltPayout) external onlyOwner {
                if (options.ownerAltPayoutLocked) {
                  revert LockedForever();
                }
                config.ownerAltPayout = ownerAltPayout;
              }
              /// @notice the password is "forever"
              function lockOwnerAltPayout(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.ownerAltPayoutLocked = true;
              }
              function setMaxBatchSize(uint32 maxBatchSize) external onlyOwner {
                config.maxBatchSize = maxBatchSize;
              }
              function setInvite(
                bytes32 _key,
                bytes32 _cid,
                Invite calldata _invite
              ) external onlyOwner {
                invites[_key] = DutchInvite({
                  price: _invite.price,
                  reservePrice: _invite.price,
                  delta: 0,
                  start: _invite.start,
                  end: _invite.end,
                  limit: _invite.limit,
                  maxSupply: _invite.maxSupply,
                  interval: 0,
                  unitSize: _invite.unitSize,
                  tokenAddress: _invite.tokenAddress
                });
                emit Invited(_key, _cid);
              }
              function setDutchInvite(
                bytes32 _key,
                bytes32 _cid,
                DutchInvite memory _dutchInvite
              ) external onlyOwner {
                if (_dutchInvite.start < block.timestamp) {
                  _dutchInvite.start = uint32(block.timestamp);
                }
                invites[_key] = _dutchInvite;
                emit Invited(_key, _cid);
              }
              function enableBurnToMint(
                address archetype,
                bool reversed,
                uint16 ratio,
                uint64 start,
                uint64 limit
              ) external onlyOwner {
                burnConfig = BurnConfig({
                  archetype: IERC721AUpgradeable(archetype),
                  enabled: true,
                  reversed: reversed,
                  ratio: ratio,
                  start: start,
                  limit: limit
                });
              }
              function disableBurnToMint() external onlyOwner {
                burnConfig = BurnConfig({
                  enabled: false,
                  reversed: false,
                  ratio: 0,
                  archetype: IERC721AUpgradeable(address(0)),
                  start: 0,
                  limit: 0
                });
              }
              //
              // PLATFORM ONLY
              //
              function setSuperAffiliatePayout(address superAffiliatePayout) external onlyPlatform {
                config.superAffiliatePayout = superAffiliatePayout;
              }
              //
              // INTERNAL
              //
              function _startTokenId() internal view virtual override returns (uint256) {
                return 1;
              }
              modifier onlyPlatform() {
                if (msg.sender != PLATFORM) {
                  revert NotPlatform();
                }
                _;
              }
              // OPTIONAL ROYALTY ENFORCEMENT WITH OPENSEA
              function enableRoyaltyEnforcement() external onlyOwner {
                if (options.royaltyEnforcementLocked) {
                  revert LockedForever();
                }
                _registerForOperatorFiltering();
                options.royaltyEnforcementEnabled = true;
              }
              function disableRoyaltyEnforcement() external onlyOwner {
                if (options.royaltyEnforcementLocked) {
                  revert LockedForever();
                }
                options.royaltyEnforcementEnabled = false;
              }
              /// @notice the password is "forever"
              function lockRoyaltyEnforcement(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.royaltyEnforcementLocked = true;
              }
              function setApprovalForAll(address operator, bool approved)
                public
                override
                onlyAllowedOperatorApproval(operator)
              {
                super.setApprovalForAll(operator, approved);
              }
              function approve(address operator, uint256 tokenId)
                public
                payable
                override
                onlyAllowedOperatorApproval(operator)
              {
                super.approve(operator, tokenId);
              }
              function transferFrom(
                address from,
                address to,
                uint256 tokenId
              ) public payable override onlyAllowedOperator(from) {
                super.transferFrom(from, to, tokenId);
              }
              function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
              ) public payable override onlyAllowedOperator(from) {
                super.safeTransferFrom(from, to, tokenId);
              }
              function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId,
                bytes memory data
              ) public payable override onlyAllowedOperator(from) {
                super.safeTransferFrom(from, to, tokenId, data);
              }
              function _operatorFilteringEnabled() internal view override returns (bool) {
                return options.royaltyEnforcementEnabled;
              }
              //ERC2981 ROYALTY
              function supportsInterface(bytes4 interfaceId)
                public
                view
                virtual
                override(ERC721AUpgradeable, ERC2981Upgradeable)
                returns (bool)
              {
                // Supports the following `interfaceId`s:
                // - IERC165: 0x01ffc9a7
                // - IERC721: 0x80ac58cd
                // - IERC721Metadata: 0x5b5e139f
                // - IERC2981: 0x2a55205a
                return
                  ERC721AUpgradeable.supportsInterface(interfaceId) ||
                  ERC2981Upgradeable.supportsInterface(interfaceId);
              }
              function setDefaultRoyalty(address receiver, uint16 feeNumerator) public onlyOwner {
                config.defaultRoyalty = feeNumerator;
                _setDefaultRoyalty(receiver, feeNumerator);
              }
            }
            // SPDX-License-Identifier: MIT
            // ArchetypeLogic v0.5.1
            //
            //        d8888                 888               888
            //       d88888                 888               888
            //      d88P888                 888               888
            //     d88P 888 888d888 .d8888b 88888b.   .d88b.  888888 888  888 88888b.   .d88b.
            //    d88P  888 888P"  d88P"    888 "88b d8P  Y8b 888    888  888 888 "88b d8P  Y8b
            //   d88P   888 888    888      888  888 88888888 888    888  888 888  888 88888888
            //  d8888888888 888    Y88b.    888  888 Y8b.     Y88b.  Y88b 888 888 d88P Y8b.
            // d88P     888 888     "Y8888P 888  888  "Y8888   "Y888  "Y88888 88888P"   "Y8888
            //                                                            888 888
            //                                                       Y8b d88P 888
            //                                                        "Y88P"  888
            pragma solidity ^0.8.4;
            import "erc721a-upgradeable/contracts/ERC721AUpgradeable.sol";
            import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
            import "solady/src/utils/MerkleProofLib.sol";
            import "solady/src/utils/ECDSA.sol";
            error InvalidConfig();
            error MintNotYetStarted();
            error MintEnded();
            error WalletUnauthorizedToMint();
            error InsufficientEthSent();
            error ExcessiveEthSent();
            error Erc20BalanceTooLow();
            error MaxSupplyExceeded();
            error ListMaxSupplyExceeded();
            error NumberOfMintsExceeded();
            error MintingPaused();
            error InvalidReferral();
            error InvalidSignature();
            error BalanceEmpty();
            error TransferFailed();
            error MaxBatchSizeExceeded();
            error BurnToMintDisabled();
            error NotTokenOwner();
            error NotPlatform();
            error NotApprovedToTransfer();
            error InvalidAmountOfTokens();
            error WrongPassword();
            error LockedForever();
            //
            // STRUCTS
            //
            struct Auth {
              bytes32 key;
              bytes32[] proof;
            }
            struct MintTier {
              uint16 numMints;
              uint16 mintDiscount; //BPS
            }
            struct Discount {
              uint16 affiliateDiscount; //BPS
              MintTier[] mintTiers;
            }
            struct Config {
              string baseUri;
              address affiliateSigner;
              address ownerAltPayout; // optional alternative address for owner withdrawals.
              address superAffiliatePayout; // optional super affiliate address, will receive half of platform fee if set.
              uint32 maxSupply;
              uint32 maxBatchSize;
              uint16 affiliateFee; //BPS
              uint16 platformFee; //BPS
              uint16 defaultRoyalty; //BPS
              Discount discounts;
            }
            struct Options {
              bool uriLocked;
              bool maxSupplyLocked;
              bool affiliateFeeLocked;
              bool discountsLocked;
              bool ownerAltPayoutLocked;
              bool royaltyEnforcementEnabled;
              bool royaltyEnforcementLocked;
              bool provenanceHashLocked;
            }
            struct DutchInvite {
              uint128 price;
              uint128 reservePrice;
              uint128 delta;
              uint32 start;
              uint32 end;
              uint32 limit;
              uint32 maxSupply;
              uint32 interval;
              uint32 unitSize; // mint 1 get x
              address tokenAddress;
            }
            struct Invite {
              uint128 price;
              uint32 start;
              uint32 end;
              uint32 limit;
              uint32 maxSupply;
              uint32 unitSize; // mint 1 get x
              address tokenAddress;
            }
            struct OwnerBalance {
              uint128 owner;
              uint128 platform;
            }
            struct BurnConfig {
              IERC721AUpgradeable archetype;
              bool enabled;
              bool reversed; // side of the ratio (false=burn {ratio} get 1, true=burn 1 get {ratio})
              uint16 ratio;
              uint64 start;
              uint64 limit;
            }
            // address constant PLATFORM = 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC; // TEST (account[2])
            address constant PLATFORM = 0x86B82972282Dd22348374bC63fd21620F7ED847B;
            uint16 constant MAXBPS = 5000; // max fee or discount is 50%
            library ArchetypeLogic {
              //
              // EVENTS
              //
              event Invited(bytes32 indexed key, bytes32 indexed cid);
              event Referral(address indexed affiliate, address token, uint128 wad, uint256 numMints);
              event Withdrawal(address indexed src, address token, uint128 wad);
              // calculate price based on affiliate usage and mint discounts
              function computePrice(
                DutchInvite storage invite,
                Discount storage discounts,
                uint256 numTokens,
                bool affiliateUsed
              ) public view returns (uint256) {
                uint256 price = invite.price;
                if (invite.interval != 0) {
                  uint256 diff = (((block.timestamp - invite.start) / invite.interval) * invite.delta);
                  if (price > invite.reservePrice) {
                    if (diff > price - invite.reservePrice) {
                      price = invite.reservePrice;
                    } else {
                      price = price - diff;
                    }
                  } else if (price < invite.reservePrice) {
                    if (diff > invite.reservePrice - price) {
                      price = invite.reservePrice;
                    } else {
                      price = price + diff;
                    }
                  }
                }
                uint256 cost = price * numTokens;
                if (affiliateUsed) {
                  cost = cost - ((cost * discounts.affiliateDiscount) / 10000);
                }
                for (uint256 i = 0; i < discounts.mintTiers.length; i++) {
                  if (numTokens >= discounts.mintTiers[i].numMints) {
                    return cost = cost - ((cost * discounts.mintTiers[i].mintDiscount) / 10000);
                  }
                }
                return cost;
              }
              function validateMint(
                DutchInvite storage i,
                Config storage config,
                Auth calldata auth,
                uint256 quantity,
                address owner,
                address affiliate,
                uint256 curSupply,
                mapping(address => mapping(bytes32 => uint256)) storage minted,
                mapping(bytes32 => uint256) storage listSupply,
                bytes calldata signature
              ) public view {
                if (affiliate != address(0)) {
                  if (affiliate == PLATFORM || affiliate == owner || affiliate == msg.sender) {
                    revert InvalidReferral();
                  }
                  validateAffiliate(affiliate, signature, config.affiliateSigner);
                }
                if (i.limit == 0) {
                  revert MintingPaused();
                }
                if (!verify(auth, i.tokenAddress, msg.sender)) {
                  revert WalletUnauthorizedToMint();
                }
                if (block.timestamp < i.start) {
                  revert MintNotYetStarted();
                }
                if (i.end > i.start && block.timestamp > i.end) {
                  revert MintEnded();
                }
                if (i.limit < i.maxSupply) {
                  uint256 totalAfterMint = minted[msg.sender][auth.key] + quantity;
                  if (totalAfterMint > i.limit) {
                    revert NumberOfMintsExceeded();
                  }
                }
                if (i.maxSupply < config.maxSupply) {
                  uint256 totalAfterMint = listSupply[auth.key] + quantity;
                  if (totalAfterMint > i.maxSupply) {
                    revert ListMaxSupplyExceeded();
                  }
                }
                if (quantity > config.maxBatchSize) {
                  revert MaxBatchSizeExceeded();
                }
                if ((curSupply + quantity) > config.maxSupply) {
                  revert MaxSupplyExceeded();
                }
                uint256 cost = computePrice(i, config.discounts, quantity, affiliate != address(0));
                if (i.tokenAddress != address(0)) {
                  IERC20Upgradeable erc20Token = IERC20Upgradeable(i.tokenAddress);
                  if (erc20Token.allowance(msg.sender, address(this)) < cost) {
                    revert NotApprovedToTransfer();
                  }
                  if (erc20Token.balanceOf(msg.sender) < cost) {
                    revert Erc20BalanceTooLow();
                  }
                  if (msg.value != 0) {
                    revert ExcessiveEthSent();
                  }
                } else {
                  if (msg.value < cost) {
                    revert InsufficientEthSent();
                  }
                  if (msg.value > cost) {
                    revert ExcessiveEthSent();
                  }
                }
              }
              function validateBurnToMint(
                Config storage config,
                BurnConfig storage burnConfig,
                uint256[] calldata tokenIds,
                uint256 curSupply,
                mapping(address => mapping(bytes32 => uint256)) storage minted
              ) public view {
                if (!burnConfig.enabled) {
                  revert BurnToMintDisabled();
                }
                if (block.timestamp < burnConfig.start) {
                  revert MintNotYetStarted();
                }
                // check if msg.sender owns tokens and has correct approvals
                for (uint256 i = 0; i < tokenIds.length; i++) {
                  if (burnConfig.archetype.ownerOf(tokenIds[i]) != msg.sender) {
                    revert NotTokenOwner();
                  }
                }
                if (!burnConfig.archetype.isApprovedForAll(msg.sender, address(this))) {
                  revert NotApprovedToTransfer();
                }
                uint256 quantity;
                if (burnConfig.reversed) {
                  quantity = tokenIds.length * burnConfig.ratio;
                } else {
                  if (tokenIds.length % burnConfig.ratio != 0) {
                    revert InvalidAmountOfTokens();
                  }
                  quantity = tokenIds.length / burnConfig.ratio;
                }
                if (quantity > config.maxBatchSize) {
                  revert MaxBatchSizeExceeded();
                }
                if (burnConfig.limit < config.maxSupply) {
                  uint256 totalAfterMint = minted[msg.sender][bytes32("burn")] + quantity;
                  if (totalAfterMint > burnConfig.limit) {
                    revert NumberOfMintsExceeded();
                  }
                }
                if ((curSupply + quantity) > config.maxSupply) {
                  revert MaxSupplyExceeded();
                }
              }
              function updateBalances(
                DutchInvite storage i,
                Config storage config,
                mapping(address => OwnerBalance) storage _ownerBalance,
                mapping(address => mapping(address => uint128)) storage _affiliateBalance,
                address affiliate,
                uint256 quantity
              ) public {
                address tokenAddress = i.tokenAddress;
                uint128 value = uint128(msg.value);
                if (tokenAddress != address(0)) {
                  value = uint128(computePrice(i, config.discounts, quantity, affiliate != address(0)));
                }
                uint128 affiliateWad = 0;
                if (affiliate != address(0)) {
                  affiliateWad = (value * config.affiliateFee) / 10000;
                  _affiliateBalance[affiliate][tokenAddress] += affiliateWad;
                  emit Referral(affiliate, tokenAddress, affiliateWad, quantity);
                }
                uint128 superAffiliateWad = 0;
                if (config.superAffiliatePayout != address(0)) {
                  superAffiliateWad = ((value * config.platformFee) / 2) / 10000;
                  _affiliateBalance[config.superAffiliatePayout][tokenAddress] += superAffiliateWad;
                }
                OwnerBalance memory balance = _ownerBalance[tokenAddress];
                uint128 platformWad = ((value * config.platformFee) / 10000) - superAffiliateWad;
                uint128 ownerWad = value - affiliateWad - platformWad - superAffiliateWad;
                _ownerBalance[tokenAddress] = OwnerBalance({
                  owner: balance.owner + ownerWad,
                  platform: balance.platform + platformWad
                });
                if (tokenAddress != address(0)) {
                  IERC20Upgradeable erc20Token = IERC20Upgradeable(tokenAddress);
                  erc20Token.transferFrom(msg.sender, address(this), value);
                }
              }
              function withdrawTokens(
                Config storage config,
                mapping(address => OwnerBalance) storage _ownerBalance,
                mapping(address => mapping(address => uint128)) storage _affiliateBalance,
                address owner,
                address[] calldata tokens
              ) public {
                for (uint256 i = 0; i < tokens.length; i++) {
                  address tokenAddress = tokens[i];
                  uint128 wad = 0;
                  if (msg.sender == owner || msg.sender == config.ownerAltPayout || msg.sender == PLATFORM) {
                    OwnerBalance storage balance = _ownerBalance[tokenAddress];
                    if (msg.sender == owner || msg.sender == config.ownerAltPayout) {
                      wad = balance.owner;
                      balance.owner = 0;
                    } else {
                      wad = balance.platform;
                      balance.platform = 0;
                    }
                  } else {
                    wad = _affiliateBalance[msg.sender][tokenAddress];
                    _affiliateBalance[msg.sender][tokenAddress] = 0;
                  }
                  if (wad == 0) {
                    revert BalanceEmpty();
                  }
                  if (tokenAddress == address(0)) {
                    bool success = false;
                    // send to ownerAltPayout if set and owner is withdrawing
                    if (msg.sender == owner && config.ownerAltPayout != address(0)) {
                      (success, ) = payable(config.ownerAltPayout).call{ value: wad }("");
                    } else {
                      (success, ) = msg.sender.call{ value: wad }("");
                    }
                    if (!success) {
                      revert TransferFailed();
                    }
                  } else {
                    IERC20Upgradeable erc20Token = IERC20Upgradeable(tokenAddress);
                    if (msg.sender == owner && config.ownerAltPayout != address(0)) {
                      erc20Token.transfer(config.ownerAltPayout, wad);
                    } else {
                      erc20Token.transfer(msg.sender, wad);
                    }
                  }
                  emit Withdrawal(msg.sender, tokenAddress, wad);
                }
              }
              function validateAffiliate(
                address affiliate,
                bytes calldata signature,
                address affiliateSigner
              ) public view {
                bytes32 signedMessagehash = ECDSA.toEthSignedMessageHash(
                  keccak256(abi.encodePacked(affiliate))
                );
                address signer = ECDSA.recover(signedMessagehash, signature);
                if (signer != affiliateSigner) {
                  revert InvalidSignature();
                }
              }
              function verify(
                Auth calldata auth,
                address tokenAddress,
                address account
              ) public pure returns (bool) {
                // keys 0-255 and tokenAddress are public
                if (uint256(auth.key) <= 0xff || auth.key == keccak256(abi.encodePacked(tokenAddress))) {
                  return true;
                }
                return MerkleProofLib.verify(auth.proof, auth.key, keccak256(abi.encodePacked(account)));
              }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
            import 'erc721a-upgradeable/contracts/ERC721A__Initializable.sol';
            import 'erc721a-upgradeable/contracts/ERC721AUpgradeable.sol';
            pragma solidity ^0.8.4;
            /**
             * @dev Contract module which provides a basic access control mechanism, where
             * there is an account (an owner) that can be granted exclusive access to
             * specific functions.
             *
             * By default, the owner account will be the one that deploys the contract. This
             * can later be changed with {transferOwnership}.
             *
             * This module is used through inheritance. It will make available the modifier
             * `onlyOwner`, which can be applied to your functions to restrict their use to
             * the owner.
             */
            abstract contract ERC721A__OwnableUpgradeable is ERC721A__Initializable, ERC721AUpgradeable {
                address private _owner;
                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                /**
                 * @dev Initializes the contract setting the deployer as the initial owner.
                 */
                function __Ownable_init() internal onlyInitializingERC721A {
                    __Ownable_init_unchained();
                }
                function __Ownable_init_unchained() internal onlyInitializingERC721A {
                    _transferOwnership(_msgSenderERC721A());
                }
                /**
                 * @dev Returns the address of the current owner.
                 */
                function owner() public view virtual returns (address) {
                    return _owner;
                }
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                    _isOwner();
                    _;
                }
                function _isOwner() internal view {
                    require(owner() == _msgSenderERC721A(), "Ownable: caller is not the owner");
                }
                /**
                 * @dev Leaves the contract without owner. It will not be possible to call
                 * `onlyOwner` functions anymore. Can only be called by the current owner.
                 *
                 * NOTE: Renouncing ownership will leave the contract without an owner,
                 * thereby removing any functionality that is only available to the owner.
                 */
                function renounceOwnership() public virtual onlyOwner {
                    _transferOwnership(address(0));
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Can only be called by the current owner.
                 */
                function transferOwnership(address newOwner) public virtual onlyOwner {
                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                    _transferOwnership(newOwner);
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Internal function without access restriction.
                 */
                function _transferOwnership(address newOwner) internal virtual {
                    address oldOwner = _owner;
                    _owner = newOwner;
                    emit OwnershipTransferred(oldOwner, newOwner);
                }
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[49] private __gap;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /**
             * @dev This is a base contract to aid in writing upgradeable diamond facet contracts, or any kind of contract that will be deployed
             * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
             * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
             * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
             *
             * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
             * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
             *
             * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
             * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
             */
            import {ERC721A__InitializableStorage} from './ERC721A__InitializableStorage.sol';
            abstract contract ERC721A__Initializable {
                using ERC721A__InitializableStorage for ERC721A__InitializableStorage.Layout;
                /**
                 * @dev Modifier to protect an initializer function from being invoked twice.
                 */
                modifier initializerERC721A() {
                    // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                    // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                    // contract may have been reentered.
                    require(
                        ERC721A__InitializableStorage.layout()._initializing
                            ? _isConstructor()
                            : !ERC721A__InitializableStorage.layout()._initialized,
                        'ERC721A__Initializable: contract is already initialized'
                    );
                    bool isTopLevelCall = !ERC721A__InitializableStorage.layout()._initializing;
                    if (isTopLevelCall) {
                        ERC721A__InitializableStorage.layout()._initializing = true;
                        ERC721A__InitializableStorage.layout()._initialized = true;
                    }
                    _;
                    if (isTopLevelCall) {
                        ERC721A__InitializableStorage.layout()._initializing = false;
                    }
                }
                /**
                 * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                 * {initializer} modifier, directly or indirectly.
                 */
                modifier onlyInitializingERC721A() {
                    require(
                        ERC721A__InitializableStorage.layout()._initializing,
                        'ERC721A__Initializable: contract is not initializing'
                    );
                    _;
                }
                /// @dev Returns true if and only if the function is running in the constructor
                function _isConstructor() private view returns (bool) {
                    // extcodesize checks the size of the code stored in an address, and
                    // address returns the current address. Since the code is still not
                    // deployed when running a constructor, any checks on its code size will
                    // yield zero, making it an effective way to detect if a contract is
                    // under construction or not.
                    address self = address(this);
                    uint256 cs;
                    assembly {
                        cs := extcodesize(self)
                    }
                    return cs == 0;
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /**
             * @dev This is a base storage for the  initialization function for upgradeable diamond facet contracts
             **/
            library ERC721A__InitializableStorage {
                struct Layout {
                    /*
                     * Indicates that the contract has been initialized.
                     */
                    bool _initialized;
                    /*
                     * Indicates that the contract is in the process of being initialized.
                     */
                    bool _initializing;
                }
                bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.initializable.facet');
                function layout() internal pure returns (Layout storage l) {
                    bytes32 slot = STORAGE_SLOT;
                    assembly {
                        l.slot := slot
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            library ERC721AStorage {
                // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
                struct TokenApprovalRef {
                    address value;
                }
                struct Layout {
                    // =============================================================
                    //                            STORAGE
                    // =============================================================
                    // The next token ID to be minted.
                    uint256 _currentIndex;
                    // The number of tokens burned.
                    uint256 _burnCounter;
                    // Token name
                    string _name;
                    // Token symbol
                    string _symbol;
                    // Mapping from token ID to ownership details
                    // An empty struct value does not necessarily mean the token is unowned.
                    // See {_packedOwnershipOf} implementation for details.
                    //
                    // Bits Layout:
                    // - [0..159]   `addr`
                    // - [160..223] `startTimestamp`
                    // - [224]      `burned`
                    // - [225]      `nextInitialized`
                    // - [232..255] `extraData`
                    mapping(uint256 => uint256) _packedOwnerships;
                    // Mapping owner address to address data.
                    //
                    // Bits Layout:
                    // - [0..63]    `balance`
                    // - [64..127]  `numberMinted`
                    // - [128..191] `numberBurned`
                    // - [192..255] `aux`
                    mapping(address => uint256) _packedAddressData;
                    // Mapping from token ID to approved address.
                    mapping(uint256 => ERC721AStorage.TokenApprovalRef) _tokenApprovals;
                    // Mapping from owner to operator approvals
                    mapping(address => mapping(address => bool)) _operatorApprovals;
                }
                bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.ERC721A');
                function layout() internal pure returns (Layout storage l) {
                    bytes32 slot = STORAGE_SLOT;
                    assembly {
                        l.slot := slot
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // ERC721A Contracts v4.2.3
            // Creator: Chiru Labs
            pragma solidity ^0.8.4;
            import './IERC721AUpgradeable.sol';
            import {ERC721AStorage} from './ERC721AStorage.sol';
            import './ERC721A__Initializable.sol';
            /**
             * @dev Interface of ERC721 token receiver.
             */
            interface ERC721A__IERC721ReceiverUpgradeable {
                function onERC721Received(
                    address operator,
                    address from,
                    uint256 tokenId,
                    bytes calldata data
                ) external returns (bytes4);
            }
            /**
             * @title ERC721A
             *
             * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
             * Non-Fungible Token Standard, including the Metadata extension.
             * Optimized for lower gas during batch mints.
             *
             * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
             * starting from `_startTokenId()`.
             *
             * Assumptions:
             *
             * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
             * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
             */
            contract ERC721AUpgradeable is ERC721A__Initializable, IERC721AUpgradeable {
                using ERC721AStorage for ERC721AStorage.Layout;
                // =============================================================
                //                           CONSTANTS
                // =============================================================
                // Mask of an entry in packed address data.
                uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
                // The bit position of `numberMinted` in packed address data.
                uint256 private constant _BITPOS_NUMBER_MINTED = 64;
                // The bit position of `numberBurned` in packed address data.
                uint256 private constant _BITPOS_NUMBER_BURNED = 128;
                // The bit position of `aux` in packed address data.
                uint256 private constant _BITPOS_AUX = 192;
                // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
                uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
                // The bit position of `startTimestamp` in packed ownership.
                uint256 private constant _BITPOS_START_TIMESTAMP = 160;
                // The bit mask of the `burned` bit in packed ownership.
                uint256 private constant _BITMASK_BURNED = 1 << 224;
                // The bit position of the `nextInitialized` bit in packed ownership.
                uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
                // The bit mask of the `nextInitialized` bit in packed ownership.
                uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
                // The bit position of `extraData` in packed ownership.
                uint256 private constant _BITPOS_EXTRA_DATA = 232;
                // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
                uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
                // The mask of the lower 160 bits for addresses.
                uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
                // The maximum `quantity` that can be minted with {_mintERC2309}.
                // This limit is to prevent overflows on the address data entries.
                // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
                // is required to cause an overflow, which is unrealistic.
                uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
                // The `Transfer` event signature is given by:
                // `keccak256(bytes("Transfer(address,address,uint256)"))`.
                bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
                    0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
                // =============================================================
                //                          CONSTRUCTOR
                // =============================================================
                function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                    __ERC721A_init_unchained(name_, symbol_);
                }
                function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                    ERC721AStorage.layout()._name = name_;
                    ERC721AStorage.layout()._symbol = symbol_;
                    ERC721AStorage.layout()._currentIndex = _startTokenId();
                }
                // =============================================================
                //                   TOKEN COUNTING OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the starting token ID.
                 * To change the starting token ID, please override this function.
                 */
                function _startTokenId() internal view virtual returns (uint256) {
                    return 0;
                }
                /**
                 * @dev Returns the next token ID to be minted.
                 */
                function _nextTokenId() internal view virtual returns (uint256) {
                    return ERC721AStorage.layout()._currentIndex;
                }
                /**
                 * @dev Returns the total number of tokens in existence.
                 * Burned tokens will reduce the count.
                 * To get the total number of tokens minted, please see {_totalMinted}.
                 */
                function totalSupply() public view virtual override returns (uint256) {
                    // Counter underflow is impossible as _burnCounter cannot be incremented
                    // more than `_currentIndex - _startTokenId()` times.
                    unchecked {
                        return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId();
                    }
                }
                /**
                 * @dev Returns the total amount of tokens minted in the contract.
                 */
                function _totalMinted() internal view virtual returns (uint256) {
                    // Counter underflow is impossible as `_currentIndex` does not decrement,
                    // and it is initialized to `_startTokenId()`.
                    unchecked {
                        return ERC721AStorage.layout()._currentIndex - _startTokenId();
                    }
                }
                /**
                 * @dev Returns the total number of tokens burned.
                 */
                function _totalBurned() internal view virtual returns (uint256) {
                    return ERC721AStorage.layout()._burnCounter;
                }
                // =============================================================
                //                    ADDRESS DATA OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the number of tokens in `owner`'s account.
                 */
                function balanceOf(address owner) public view virtual override returns (uint256) {
                    if (owner == address(0)) revert BalanceQueryForZeroAddress();
                    return ERC721AStorage.layout()._packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
                }
                /**
                 * Returns the number of tokens minted by `owner`.
                 */
                function _numberMinted(address owner) internal view returns (uint256) {
                    return
                        (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
                }
                /**
                 * Returns the number of tokens burned by or on behalf of `owner`.
                 */
                function _numberBurned(address owner) internal view returns (uint256) {
                    return
                        (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
                }
                /**
                 * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
                 */
                function _getAux(address owner) internal view returns (uint64) {
                    return uint64(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_AUX);
                }
                /**
                 * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
                 * If there are multiple variables, please pack them into a uint64.
                 */
                function _setAux(address owner, uint64 aux) internal virtual {
                    uint256 packed = ERC721AStorage.layout()._packedAddressData[owner];
                    uint256 auxCasted;
                    // Cast `aux` with assembly to avoid redundant masking.
                    assembly {
                        auxCasted := aux
                    }
                    packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
                    ERC721AStorage.layout()._packedAddressData[owner] = packed;
                }
                // =============================================================
                //                            IERC165
                // =============================================================
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                    // The interface IDs are constants representing the first 4 bytes
                    // of the XOR of all function selectors in the interface.
                    // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
                    // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
                    return
                        interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
                        interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
                        interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
                }
                // =============================================================
                //                        IERC721Metadata
                // =============================================================
                /**
                 * @dev Returns the token collection name.
                 */
                function name() public view virtual override returns (string memory) {
                    return ERC721AStorage.layout()._name;
                }
                /**
                 * @dev Returns the token collection symbol.
                 */
                function symbol() public view virtual override returns (string memory) {
                    return ERC721AStorage.layout()._symbol;
                }
                /**
                 * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
                 */
                function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                    if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                    string memory baseURI = _baseURI();
                    return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
                }
                /**
                 * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
                 * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
                 * by default, it can be overridden in child contracts.
                 */
                function _baseURI() internal view virtual returns (string memory) {
                    return '';
                }
                // =============================================================
                //                     OWNERSHIPS OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the owner of the `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function ownerOf(uint256 tokenId) public view virtual override returns (address) {
                    return address(uint160(_packedOwnershipOf(tokenId)));
                }
                /**
                 * @dev Gas spent here starts off proportional to the maximum mint batch size.
                 * It gradually moves to O(1) as tokens get transferred around over time.
                 */
                function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
                    return _unpackedOwnership(_packedOwnershipOf(tokenId));
                }
                /**
                 * @dev Returns the unpacked `TokenOwnership` struct at `index`.
                 */
                function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
                    return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]);
                }
                /**
                 * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
                 */
                function _initializeOwnershipAt(uint256 index) internal virtual {
                    if (ERC721AStorage.layout()._packedOwnerships[index] == 0) {
                        ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(index);
                    }
                }
                /**
                 * Returns the packed ownership data of `tokenId`.
                 */
                function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
                    if (_startTokenId() <= tokenId) {
                        packed = ERC721AStorage.layout()._packedOwnerships[tokenId];
                        // If not burned.
                        if (packed & _BITMASK_BURNED == 0) {
                            // If the data at the starting slot does not exist, start the scan.
                            if (packed == 0) {
                                if (tokenId >= ERC721AStorage.layout()._currentIndex) revert OwnerQueryForNonexistentToken();
                                // Invariant:
                                // There will always be an initialized ownership slot
                                // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                                // before an unintialized ownership slot
                                // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                                // Hence, `tokenId` will not underflow.
                                //
                                // We can directly compare the packed value.
                                // If the address is zero, packed will be zero.
                                for (;;) {
                                    unchecked {
                                        packed = ERC721AStorage.layout()._packedOwnerships[--tokenId];
                                    }
                                    if (packed == 0) continue;
                                    return packed;
                                }
                            }
                            // Otherwise, the data exists and is not burned. We can skip the scan.
                            // This is possible because we have already achieved the target condition.
                            // This saves 2143 gas on transfers of initialized tokens.
                            return packed;
                        }
                    }
                    revert OwnerQueryForNonexistentToken();
                }
                /**
                 * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
                 */
                function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
                    ownership.addr = address(uint160(packed));
                    ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
                    ownership.burned = packed & _BITMASK_BURNED != 0;
                    ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
                }
                /**
                 * @dev Packs ownership data into a single uint256.
                 */
                function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
                    assembly {
                        // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        owner := and(owner, _BITMASK_ADDRESS)
                        // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
                        result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
                    }
                }
                /**
                 * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
                 */
                function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
                    // For branchless setting of the `nextInitialized` flag.
                    assembly {
                        // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
                        result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
                    }
                }
                // =============================================================
                //                      APPROVAL OPERATIONS
                // =============================================================
                /**
                 * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
                 *
                 * Requirements:
                 *
                 * - The caller must own the token or be an approved operator.
                 */
                function approve(address to, uint256 tokenId) public payable virtual override {
                    _approve(to, tokenId, true);
                }
                /**
                 * @dev Returns the account approved for `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function getApproved(uint256 tokenId) public view virtual override returns (address) {
                    if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
                    return ERC721AStorage.layout()._tokenApprovals[tokenId].value;
                }
                /**
                 * @dev Approve or remove `operator` as an operator for the caller.
                 * Operators can call {transferFrom} or {safeTransferFrom}
                 * for any token owned by the caller.
                 *
                 * Requirements:
                 *
                 * - The `operator` cannot be the caller.
                 *
                 * Emits an {ApprovalForAll} event.
                 */
                function setApprovalForAll(address operator, bool approved) public virtual override {
                    ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][operator] = approved;
                    emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
                }
                /**
                 * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
                 *
                 * See {setApprovalForAll}.
                 */
                function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
                    return ERC721AStorage.layout()._operatorApprovals[owner][operator];
                }
                /**
                 * @dev Returns whether `tokenId` exists.
                 *
                 * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
                 *
                 * Tokens start existing when they are minted. See {_mint}.
                 */
                function _exists(uint256 tokenId) internal view virtual returns (bool) {
                    return
                        _startTokenId() <= tokenId &&
                        tokenId < ERC721AStorage.layout()._currentIndex && // If within bounds,
                        ERC721AStorage.layout()._packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
                }
                /**
                 * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
                 */
                function _isSenderApprovedOrOwner(
                    address approvedAddress,
                    address owner,
                    address msgSender
                ) private pure returns (bool result) {
                    assembly {
                        // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        owner := and(owner, _BITMASK_ADDRESS)
                        // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        msgSender := and(msgSender, _BITMASK_ADDRESS)
                        // `msgSender == owner || msgSender == approvedAddress`.
                        result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
                    }
                }
                /**
                 * @dev Returns the storage slot and value for the approved address of `tokenId`.
                 */
                function _getApprovedSlotAndAddress(uint256 tokenId)
                    private
                    view
                    returns (uint256 approvedAddressSlot, address approvedAddress)
                {
                    ERC721AStorage.TokenApprovalRef storage tokenApproval = ERC721AStorage.layout()._tokenApprovals[tokenId];
                    // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
                    assembly {
                        approvedAddressSlot := tokenApproval.slot
                        approvedAddress := sload(approvedAddressSlot)
                    }
                }
                // =============================================================
                //                      TRANSFER OPERATIONS
                // =============================================================
                /**
                 * @dev Transfers `tokenId` from `from` to `to`.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token
                 * by either {approve} or {setApprovalForAll}.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) public payable virtual override {
                    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                    if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
                    (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                    // The nested ifs save around 20+ gas over a compound boolean condition.
                    if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                        if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                    if (to == address(0)) revert TransferToZeroAddress();
                    _beforeTokenTransfers(from, to, tokenId, 1);
                    // Clear approvals from the previous owner.
                    assembly {
                        if approvedAddress {
                            // This is equivalent to `delete _tokenApprovals[tokenId]`.
                            sstore(approvedAddressSlot, 0)
                        }
                    }
                    // Underflow of the sender's balance is impossible because we check for
                    // ownership above and the recipient's balance can't realistically overflow.
                    // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                    unchecked {
                        // We can directly increment and decrement the balances.
                        --ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`.
                        ++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`.
                        // Updates:
                        // - `address` to the next owner.
                        // - `startTimestamp` to the timestamp of transfering.
                        // - `burned` to `false`.
                        // - `nextInitialized` to `true`.
                        ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                            to,
                            _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
                        );
                        // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                        if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                            uint256 nextTokenId = tokenId + 1;
                            // If the next slot's address is zero and not burned (i.e. packed value is zero).
                            if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                                // If the next slot is within bounds.
                                if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                    // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                    ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                                }
                            }
                        }
                    }
                    emit Transfer(from, to, tokenId);
                    _afterTokenTransfers(from, to, tokenId, 1);
                }
                /**
                 * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) public payable virtual override {
                    safeTransferFrom(from, to, tokenId, '');
                }
                /**
                 * @dev Safely transfers `tokenId` token from `from` to `to`.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must exist and be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token
                 * by either {approve} or {setApprovalForAll}.
                 * - If `to` refers to a smart contract, it must implement
                 * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                 *
                 * Emits a {Transfer} event.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                ) public payable virtual override {
                    transferFrom(from, to, tokenId);
                    if (to.code.length != 0)
                        if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                            revert TransferToNonERC721ReceiverImplementer();
                        }
                }
                /**
                 * @dev Hook that is called before a set of serially-ordered token IDs
                 * are about to be transferred. This includes minting.
                 * And also called before burning one token.
                 *
                 * `startTokenId` - the first token ID to be transferred.
                 * `quantity` - the amount to be transferred.
                 *
                 * Calling conditions:
                 *
                 * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
                 * transferred to `to`.
                 * - When `from` is zero, `tokenId` will be minted for `to`.
                 * - When `to` is zero, `tokenId` will be burned by `from`.
                 * - `from` and `to` are never both zero.
                 */
                function _beforeTokenTransfers(
                    address from,
                    address to,
                    uint256 startTokenId,
                    uint256 quantity
                ) internal virtual {}
                /**
                 * @dev Hook that is called after a set of serially-ordered token IDs
                 * have been transferred. This includes minting.
                 * And also called after one token has been burned.
                 *
                 * `startTokenId` - the first token ID to be transferred.
                 * `quantity` - the amount to be transferred.
                 *
                 * Calling conditions:
                 *
                 * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
                 * transferred to `to`.
                 * - When `from` is zero, `tokenId` has been minted for `to`.
                 * - When `to` is zero, `tokenId` has been burned by `from`.
                 * - `from` and `to` are never both zero.
                 */
                function _afterTokenTransfers(
                    address from,
                    address to,
                    uint256 startTokenId,
                    uint256 quantity
                ) internal virtual {}
                /**
                 * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
                 *
                 * `from` - Previous owner of the given token ID.
                 * `to` - Target address that will receive the token.
                 * `tokenId` - Token ID to be transferred.
                 * `_data` - Optional data to send along with the call.
                 *
                 * Returns whether the call correctly returned the expected magic value.
                 */
                function _checkContractOnERC721Received(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                ) private returns (bool) {
                    try
                        ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data)
                    returns (bytes4 retval) {
                        return retval == ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received.selector;
                    } catch (bytes memory reason) {
                        if (reason.length == 0) {
                            revert TransferToNonERC721ReceiverImplementer();
                        } else {
                            assembly {
                                revert(add(32, reason), mload(reason))
                            }
                        }
                    }
                }
                // =============================================================
                //                        MINT OPERATIONS
                // =============================================================
                /**
                 * @dev Mints `quantity` tokens and transfers them to `to`.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - `quantity` must be greater than 0.
                 *
                 * Emits a {Transfer} event for each mint.
                 */
                function _mint(address to, uint256 quantity) internal virtual {
                    uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                    if (quantity == 0) revert MintZeroQuantity();
                    _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                    // Overflows are incredibly unrealistic.
                    // `balance` and `numberMinted` have a maximum limit of 2**64.
                    // `tokenId` has a maximum limit of 2**256.
                    unchecked {
                        // Updates:
                        // - `balance += quantity`.
                        // - `numberMinted += quantity`.
                        //
                        // We can directly add to the `balance` and `numberMinted`.
                        ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                        // Updates:
                        // - `address` to the owner.
                        // - `startTimestamp` to the timestamp of minting.
                        // - `burned` to `false`.
                        // - `nextInitialized` to `quantity == 1`.
                        ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                            to,
                            _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                        );
                        uint256 toMasked;
                        uint256 end = startTokenId + quantity;
                        // Use assembly to loop and emit the `Transfer` event for gas savings.
                        // The duplicated `log4` removes an extra check and reduces stack juggling.
                        // The assembly, together with the surrounding Solidity code, have been
                        // delicately arranged to nudge the compiler into producing optimized opcodes.
                        assembly {
                            // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                            toMasked := and(to, _BITMASK_ADDRESS)
                            // Emit the `Transfer` event.
                            log4(
                                0, // Start of data (0, since no data).
                                0, // End of data (0, since no data).
                                _TRANSFER_EVENT_SIGNATURE, // Signature.
                                0, // `address(0)`.
                                toMasked, // `to`.
                                startTokenId // `tokenId`.
                            )
                            // The `iszero(eq(,))` check ensures that large values of `quantity`
                            // that overflows uint256 will make the loop run out of gas.
                            // The compiler will optimize the `iszero` away for performance.
                            for {
                                let tokenId := add(startTokenId, 1)
                            } iszero(eq(tokenId, end)) {
                                tokenId := add(tokenId, 1)
                            } {
                                // Emit the `Transfer` event. Similar to above.
                                log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                            }
                        }
                        if (toMasked == 0) revert MintToZeroAddress();
                        ERC721AStorage.layout()._currentIndex = end;
                    }
                    _afterTokenTransfers(address(0), to, startTokenId, quantity);
                }
                /**
                 * @dev Mints `quantity` tokens and transfers them to `to`.
                 *
                 * This function is intended for efficient minting only during contract creation.
                 *
                 * It emits only one {ConsecutiveTransfer} as defined in
                 * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
                 * instead of a sequence of {Transfer} event(s).
                 *
                 * Calling this function outside of contract creation WILL make your contract
                 * non-compliant with the ERC721 standard.
                 * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
                 * {ConsecutiveTransfer} event is only permissible during contract creation.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - `quantity` must be greater than 0.
                 *
                 * Emits a {ConsecutiveTransfer} event.
                 */
                function _mintERC2309(address to, uint256 quantity) internal virtual {
                    uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                    if (to == address(0)) revert MintToZeroAddress();
                    if (quantity == 0) revert MintZeroQuantity();
                    if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
                    _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                    // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
                    unchecked {
                        // Updates:
                        // - `balance += quantity`.
                        // - `numberMinted += quantity`.
                        //
                        // We can directly add to the `balance` and `numberMinted`.
                        ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                        // Updates:
                        // - `address` to the owner.
                        // - `startTimestamp` to the timestamp of minting.
                        // - `burned` to `false`.
                        // - `nextInitialized` to `quantity == 1`.
                        ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                            to,
                            _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                        );
                        emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
                        ERC721AStorage.layout()._currentIndex = startTokenId + quantity;
                    }
                    _afterTokenTransfers(address(0), to, startTokenId, quantity);
                }
                /**
                 * @dev Safely mints `quantity` tokens and transfers them to `to`.
                 *
                 * Requirements:
                 *
                 * - If `to` refers to a smart contract, it must implement
                 * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
                 * - `quantity` must be greater than 0.
                 *
                 * See {_mint}.
                 *
                 * Emits a {Transfer} event for each mint.
                 */
                function _safeMint(
                    address to,
                    uint256 quantity,
                    bytes memory _data
                ) internal virtual {
                    _mint(to, quantity);
                    unchecked {
                        if (to.code.length != 0) {
                            uint256 end = ERC721AStorage.layout()._currentIndex;
                            uint256 index = end - quantity;
                            do {
                                if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                                    revert TransferToNonERC721ReceiverImplementer();
                                }
                            } while (index < end);
                            // Reentrancy protection.
                            if (ERC721AStorage.layout()._currentIndex != end) revert();
                        }
                    }
                }
                /**
                 * @dev Equivalent to `_safeMint(to, quantity, '')`.
                 */
                function _safeMint(address to, uint256 quantity) internal virtual {
                    _safeMint(to, quantity, '');
                }
                // =============================================================
                //                       APPROVAL OPERATIONS
                // =============================================================
                /**
                 * @dev Equivalent to `_approve(to, tokenId, false)`.
                 */
                function _approve(address to, uint256 tokenId) internal virtual {
                    _approve(to, tokenId, false);
                }
                /**
                 * @dev Gives permission to `to` to transfer `tokenId` token to another account.
                 * The approval is cleared when the token is transferred.
                 *
                 * Only a single account can be approved at a time, so approving the
                 * zero address clears previous approvals.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 *
                 * Emits an {Approval} event.
                 */
                function _approve(
                    address to,
                    uint256 tokenId,
                    bool approvalCheck
                ) internal virtual {
                    address owner = ownerOf(tokenId);
                    if (approvalCheck)
                        if (_msgSenderERC721A() != owner)
                            if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                                revert ApprovalCallerNotOwnerNorApproved();
                            }
                    ERC721AStorage.layout()._tokenApprovals[tokenId].value = to;
                    emit Approval(owner, to, tokenId);
                }
                // =============================================================
                //                        BURN OPERATIONS
                // =============================================================
                /**
                 * @dev Equivalent to `_burn(tokenId, false)`.
                 */
                function _burn(uint256 tokenId) internal virtual {
                    _burn(tokenId, false);
                }
                /**
                 * @dev Destroys `tokenId`.
                 * The approval is cleared when the token is burned.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 *
                 * Emits a {Transfer} event.
                 */
                function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
                    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                    address from = address(uint160(prevOwnershipPacked));
                    (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                    if (approvalCheck) {
                        // The nested ifs save around 20+ gas over a compound boolean condition.
                        if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                            if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                    }
                    _beforeTokenTransfers(from, address(0), tokenId, 1);
                    // Clear approvals from the previous owner.
                    assembly {
                        if approvedAddress {
                            // This is equivalent to `delete _tokenApprovals[tokenId]`.
                            sstore(approvedAddressSlot, 0)
                        }
                    }
                    // Underflow of the sender's balance is impossible because we check for
                    // ownership above and the recipient's balance can't realistically overflow.
                    // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                    unchecked {
                        // Updates:
                        // - `balance -= 1`.
                        // - `numberBurned += 1`.
                        //
                        // We can directly decrement the balance, and increment the number burned.
                        // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
                        ERC721AStorage.layout()._packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
                        // Updates:
                        // - `address` to the last owner.
                        // - `startTimestamp` to the timestamp of burning.
                        // - `burned` to `true`.
                        // - `nextInitialized` to `true`.
                        ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                            from,
                            (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
                        );
                        // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                        if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                            uint256 nextTokenId = tokenId + 1;
                            // If the next slot's address is zero and not burned (i.e. packed value is zero).
                            if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                                // If the next slot is within bounds.
                                if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                    // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                    ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                                }
                            }
                        }
                    }
                    emit Transfer(from, address(0), tokenId);
                    _afterTokenTransfers(from, address(0), tokenId, 1);
                    // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
                    unchecked {
                        ERC721AStorage.layout()._burnCounter++;
                    }
                }
                // =============================================================
                //                     EXTRA DATA OPERATIONS
                // =============================================================
                /**
                 * @dev Directly sets the extra data for the ownership data `index`.
                 */
                function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
                    uint256 packed = ERC721AStorage.layout()._packedOwnerships[index];
                    if (packed == 0) revert OwnershipNotInitializedForExtraData();
                    uint256 extraDataCasted;
                    // Cast `extraData` with assembly to avoid redundant masking.
                    assembly {
                        extraDataCasted := extraData
                    }
                    packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
                    ERC721AStorage.layout()._packedOwnerships[index] = packed;
                }
                /**
                 * @dev Called during each token transfer to set the 24bit `extraData` field.
                 * Intended to be overridden by the cosumer contract.
                 *
                 * `previousExtraData` - the value of `extraData` before transfer.
                 *
                 * Calling conditions:
                 *
                 * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
                 * transferred to `to`.
                 * - When `from` is zero, `tokenId` will be minted for `to`.
                 * - When `to` is zero, `tokenId` will be burned by `from`.
                 * - `from` and `to` are never both zero.
                 */
                function _extraData(
                    address from,
                    address to,
                    uint24 previousExtraData
                ) internal view virtual returns (uint24) {}
                /**
                 * @dev Returns the next extra data for the packed ownership data.
                 * The returned result is shifted into position.
                 */
                function _nextExtraData(
                    address from,
                    address to,
                    uint256 prevOwnershipPacked
                ) private view returns (uint256) {
                    uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
                    return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
                }
                // =============================================================
                //                       OTHER OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the message sender (defaults to `msg.sender`).
                 *
                 * If you are writing GSN compatible contracts, you need to override this function.
                 */
                function _msgSenderERC721A() internal view virtual returns (address) {
                    return msg.sender;
                }
                /**
                 * @dev Converts a uint256 to its ASCII string decimal representation.
                 */
                function _toString(uint256 value) internal pure virtual returns (string memory str) {
                    assembly {
                        // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                        // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                        // We will need 1 word for the trailing zeros padding, 1 word for the length,
                        // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                        let m := add(mload(0x40), 0xa0)
                        // Update the free memory pointer to allocate.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end of the memory to calculate the length later.
                        let end := str
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 1)
                            // Write the character to the pointer.
                            // The ASCII index of the '0' character is 48.
                            mstore8(str, add(48, mod(temp, 10)))
                            // Keep dividing `temp` until zero.
                            temp := div(temp, 10)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        let length := sub(end, str)
                        // Move the pointer 32 bytes leftwards to make room for the length.
                        str := sub(str, 0x20)
                        // Store the length.
                        mstore(str, length)
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // ERC721A Contracts v4.2.3
            // Creator: Chiru Labs
            pragma solidity ^0.8.4;
            /**
             * @dev Interface of ERC721A.
             */
            interface IERC721AUpgradeable {
                /**
                 * The caller must own the token or be an approved operator.
                 */
                error ApprovalCallerNotOwnerNorApproved();
                /**
                 * The token does not exist.
                 */
                error ApprovalQueryForNonexistentToken();
                /**
                 * Cannot query the balance for the zero address.
                 */
                error BalanceQueryForZeroAddress();
                /**
                 * Cannot mint to the zero address.
                 */
                error MintToZeroAddress();
                /**
                 * The quantity of tokens minted must be more than zero.
                 */
                error MintZeroQuantity();
                /**
                 * The token does not exist.
                 */
                error OwnerQueryForNonexistentToken();
                /**
                 * The caller must own the token or be an approved operator.
                 */
                error TransferCallerNotOwnerNorApproved();
                /**
                 * The token must be owned by `from`.
                 */
                error TransferFromIncorrectOwner();
                /**
                 * Cannot safely transfer to a contract that does not implement the
                 * ERC721Receiver interface.
                 */
                error TransferToNonERC721ReceiverImplementer();
                /**
                 * Cannot transfer to the zero address.
                 */
                error TransferToZeroAddress();
                /**
                 * The token does not exist.
                 */
                error URIQueryForNonexistentToken();
                /**
                 * The `quantity` minted with ERC2309 exceeds the safety limit.
                 */
                error MintERC2309QuantityExceedsLimit();
                /**
                 * The `extraData` cannot be set on an unintialized ownership slot.
                 */
                error OwnershipNotInitializedForExtraData();
                // =============================================================
                //                            STRUCTS
                // =============================================================
                struct TokenOwnership {
                    // The address of the owner.
                    address addr;
                    // Stores the start time of ownership with minimal overhead for tokenomics.
                    uint64 startTimestamp;
                    // Whether the token has been burned.
                    bool burned;
                    // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
                    uint24 extraData;
                }
                // =============================================================
                //                         TOKEN COUNTERS
                // =============================================================
                /**
                 * @dev Returns the total number of tokens in existence.
                 * Burned tokens will reduce the count.
                 * To get the total number of tokens minted, please see {_totalMinted}.
                 */
                function totalSupply() external view returns (uint256);
                // =============================================================
                //                            IERC165
                // =============================================================
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) external view returns (bool);
                // =============================================================
                //                            IERC721
                // =============================================================
                /**
                 * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
                 */
                event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
                /**
                 * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
                 */
                event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
                /**
                 * @dev Emitted when `owner` enables or disables
                 * (`approved`) `operator` to manage all of its assets.
                 */
                event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
                /**
                 * @dev Returns the number of tokens in `owner`'s account.
                 */
                function balanceOf(address owner) external view returns (uint256 balance);
                /**
                 * @dev Returns the owner of the `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function ownerOf(uint256 tokenId) external view returns (address owner);
                /**
                 * @dev Safely transfers `tokenId` token from `from` to `to`,
                 * checking first that contract recipients are aware of the ERC721 protocol
                 * to prevent tokens from being forever locked.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must exist and be owned by `from`.
                 * - If the caller is not `from`, it must be have been allowed to move
                 * this token by either {approve} or {setApprovalForAll}.
                 * - If `to` refers to a smart contract, it must implement
                 * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                 *
                 * Emits a {Transfer} event.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes calldata data
                ) external payable;
                /**
                 * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) external payable;
                /**
                 * @dev Transfers `tokenId` from `from` to `to`.
                 *
                 * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
                 * whenever possible.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token
                 * by either {approve} or {setApprovalForAll}.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) external payable;
                /**
                 * @dev Gives permission to `to` to transfer `tokenId` token to another account.
                 * The approval is cleared when the token is transferred.
                 *
                 * Only a single account can be approved at a time, so approving the
                 * zero address clears previous approvals.
                 *
                 * Requirements:
                 *
                 * - The caller must own the token or be an approved operator.
                 * - `tokenId` must exist.
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address to, uint256 tokenId) external payable;
                /**
                 * @dev Approve or remove `operator` as an operator for the caller.
                 * Operators can call {transferFrom} or {safeTransferFrom}
                 * for any token owned by the caller.
                 *
                 * Requirements:
                 *
                 * - The `operator` cannot be the caller.
                 *
                 * Emits an {ApprovalForAll} event.
                 */
                function setApprovalForAll(address operator, bool _approved) external;
                /**
                 * @dev Returns the account approved for `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function getApproved(uint256 tokenId) external view returns (address operator);
                /**
                 * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
                 *
                 * See {setApprovalForAll}.
                 */
                function isApprovedForAll(address owner, address operator) external view returns (bool);
                // =============================================================
                //                        IERC721Metadata
                // =============================================================
                /**
                 * @dev Returns the token collection name.
                 */
                function name() external view returns (string memory);
                /**
                 * @dev Returns the token collection symbol.
                 */
                function symbol() external view returns (string memory);
                /**
                 * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
                 */
                function tokenURI(uint256 tokenId) external view returns (string memory);
                // =============================================================
                //                           IERC2309
                // =============================================================
                /**
                 * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
                 * (inclusive) is transferred from `from` to `to`, as defined in the
                 * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
                 *
                 * See {_mintERC2309} for more details.
                 */
                event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Gas optimized ECDSA wrapper.
            /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol)
            /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol)
            /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol)
            library ECDSA {
                function recover(bytes32 hash, bytes calldata signature) internal view returns (address result) {
                    assembly {
                        if eq(signature.length, 65) {
                            // Copy the free memory pointer so that we can restore it later.
                            let m := mload(0x40)
                            // Directly copy `r` and `s` from the calldata.
                            calldatacopy(0x40, signature.offset, 0x40)
                            // If `s` in lower half order, such that the signature is not malleable.
                            // prettier-ignore
                            if iszero(gt(mload(0x60), 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) {
                                mstore(0x00, hash)
                                // Compute `v` and store it in the scratch space.
                                mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40))))
                                pop(
                                    staticcall(
                                        gas(), // Amount of gas left for the transaction.
                                        0x01, // Address of `ecrecover`.
                                        0x00, // Start of input.
                                        0x80, // Size of input.
                                        0x40, // Start of output.
                                        0x20 // Size of output.
                                    )
                                )
                                // Restore the zero slot.
                                mstore(0x60, 0)
                                // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
                                result := mload(sub(0x60, returndatasize()))
                            }
                            // Restore the free memory pointer.
                            mstore(0x40, m)
                        }
                    }
                }
                function recover(
                    bytes32 hash,
                    bytes32 r,
                    bytes32 vs
                ) internal view returns (address result) {
                    assembly {
                        // Copy the free memory pointer so that we can restore it later.
                        let m := mload(0x40)
                        // prettier-ignore
                        let s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                        // If `s` in lower half order, such that the signature is not malleable.
                        // prettier-ignore
                        if iszero(gt(s, 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) {
                            mstore(0x00, hash)
                            mstore(0x20, add(shr(255, vs), 27))
                            mstore(0x40, r)
                            mstore(0x60, s)
                            pop(
                                staticcall(
                                    gas(), // Amount of gas left for the transaction.
                                    0x01, // Address of `ecrecover`.
                                    0x00, // Start of input.
                                    0x80, // Size of input.
                                    0x40, // Start of output.
                                    0x20 // Size of output.
                                )
                            )
                            // Restore the zero slot.
                            mstore(0x60, 0)
                            // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
                            result := mload(sub(0x60, returndatasize()))
                        }
                        // Restore the free memory pointer.
                        mstore(0x40, m)
                    }
                }
                function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
                    assembly {
                        // Store into scratch space for keccak256.
                        mstore(0x20, hash)
                        mstore(0x00, "\\x00\\x00\\x00\\x00\\x19Ethereum Signed Message:\
            32")
                        // 0x40 - 0x04 = 0x3c
                        result := keccak256(0x04, 0x3c)
                    }
                }
                function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
                    assembly {
                        // We need at most 128 bytes for Ethereum signed message header.
                        // The max length of the ASCII reprenstation of a uint256 is 78 bytes.
                        // The length of "\\x19Ethereum Signed Message:\
            " is 26 bytes (i.e. 0x1a).
                        // The next multiple of 32 above 78 + 26 is 128 (i.e. 0x80).
                        // Instead of allocating, we temporarily copy the 128 bytes before the
                        // start of `s` data to some variables.
                        let m3 := mload(sub(s, 0x60))
                        let m2 := mload(sub(s, 0x40))
                        let m1 := mload(sub(s, 0x20))
                        // The length of `s` is in bytes.
                        let sLength := mload(s)
                        let ptr := add(s, 0x20)
                        // `end` marks the end of the memory which we will compute the keccak256 of.
                        let end := add(ptr, sLength)
                        // Convert the length of the bytes to ASCII decimal representation
                        // and store it into the memory.
                        // prettier-ignore
                        for { let temp := sLength } 1 {} {
                            ptr := sub(ptr, 1)
                            mstore8(ptr, add(48, mod(temp, 10)))
                            temp := div(temp, 10)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        // Copy the header over to the memory.
                        mstore(sub(ptr, 0x20), "\\x00\\x00\\x00\\x00\\x00\\x00\\x19Ethereum Signed Message:\
            ")
                        // Compute the keccak256 of the memory.
                        result := keccak256(sub(ptr, 0x1a), sub(end, sub(ptr, 0x1a)))
                        // Restore the previous memory.
                        mstore(s, sLength)
                        mstore(sub(s, 0x20), m1)
                        mstore(sub(s, 0x40), m2)
                        mstore(sub(s, 0x60), m3)
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Library for converting numbers into strings and other string operations.
            /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
            /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
            library LibString {
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                        CUSTOM ERRORS                       */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                error HexLengthInsufficient();
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                     DECIMAL OPERATIONS                     */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                function toString(uint256 value) internal pure returns (string memory str) {
                    assembly {
                        // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                        // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                        // We will need 1 word for the trailing zeros padding, 1 word for the length,
                        // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                        let m := add(mload(0x40), 0xa0)
                        // Update the free memory pointer to allocate.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end of the memory to calculate the length later.
                        let end := str
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 1)
                            // Write the character to the pointer.
                            // The ASCII index of the '0' character is 48.
                            mstore8(str, add(48, mod(temp, 10)))
                            // Keep dividing `temp` until zero.
                            temp := div(temp, 10)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        let length := sub(end, str)
                        // Move the pointer 32 bytes leftwards to make room for the length.
                        str := sub(str, 0x20)
                        // Store the length.
                        mstore(str, length)
                    }
                }
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                   HEXADECIMAL OPERATIONS                   */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {
                    assembly {
                        let start := mload(0x40)
                        // We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes
                        // for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
                        // We add 0x20 to the total and round down to a multiple of 0x20.
                        // (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
                        let m := add(start, and(add(shl(1, length), 0x62), not(0x1f)))
                        // Allocate the memory.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end to calculate the length later.
                        let end := str
                        // Store "0123456789abcdef" in scratch space.
                        mstore(0x0f, 0x30313233343536373839616263646566)
                        let temp := value
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for {} 1 {} {
                            str := sub(str, 2)
                            mstore8(add(str, 1), mload(and(temp, 15)))
                            mstore8(str, mload(and(shr(4, temp), 15)))
                            temp := shr(8, temp)
                            length := sub(length, 1)
                            // prettier-ignore
                            if iszero(length) { break }
                        }
                        if temp {
                            // Store the function selector of `HexLengthInsufficient()`.
                            mstore(0x00, 0x2194895a)
                            // Revert with (offset, size).
                            revert(0x1c, 0x04)
                        }
                        // Compute the string's length.
                        let strLength := add(sub(end, str), 2)
                        // Move the pointer and write the "0x" prefix.
                        str := sub(str, 0x20)
                        mstore(str, 0x3078)
                        // Move the pointer and write the length.
                        str := sub(str, 2)
                        mstore(str, strLength)
                    }
                }
                function toHexString(uint256 value) internal pure returns (string memory str) {
                    assembly {
                        let start := mload(0x40)
                        // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
                        // 0x02 bytes for the prefix, and 0x40 bytes for the digits.
                        // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
                        let m := add(start, 0xa0)
                        // Allocate the memory.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end to calculate the length later.
                        let end := str
                        // Store "0123456789abcdef" in scratch space.
                        mstore(0x0f, 0x30313233343536373839616263646566)
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 2)
                            mstore8(add(str, 1), mload(and(temp, 15)))
                            mstore8(str, mload(and(shr(4, temp), 15)))
                            temp := shr(8, temp)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        // Compute the string's length.
                        let strLength := add(sub(end, str), 2)
                        // Move the pointer and write the "0x" prefix.
                        str := sub(str, 0x20)
                        mstore(str, 0x3078)
                        // Move the pointer and write the length.
                        str := sub(str, 2)
                        mstore(str, strLength)
                    }
                }
                function toHexString(address value) internal pure returns (string memory str) {
                    assembly {
                        let start := mload(0x40)
                        // We need 0x20 bytes for the length, 0x02 bytes for the prefix,
                        // and 0x28 bytes for the digits.
                        // The next multiple of 0x20 above (0x20 + 0x02 + 0x28) is 0x60.
                        str := add(start, 0x60)
                        // Allocate the memory.
                        mstore(0x40, str)
                        // Store "0123456789abcdef" in scratch space.
                        mstore(0x0f, 0x30313233343536373839616263646566)
                        let length := 20
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 2)
                            mstore8(add(str, 1), mload(and(temp, 15)))
                            mstore8(str, mload(and(shr(4, temp), 15)))
                            temp := shr(8, temp)
                            length := sub(length, 1)
                            // prettier-ignore
                            if iszero(length) { break }
                        }
                        // Move the pointer and write the "0x" prefix.
                        str := sub(str, 32)
                        mstore(str, 0x3078)
                        // Move the pointer and write the length.
                        str := sub(str, 2)
                        mstore(str, 42)
                    }
                }
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                   OTHER STRING OPERATIONS                  */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                function replace(
                    string memory subject,
                    string memory search,
                    string memory replacement
                ) internal pure returns (string memory result) {
                    assembly {
                        let subjectLength := mload(subject)
                        let searchLength := mload(search)
                        let replacementLength := mload(replacement)
                        subject := add(subject, 0x20)
                        search := add(search, 0x20)
                        replacement := add(replacement, 0x20)
                        result := add(mload(0x40), 0x20)
                        let subjectEnd := add(subject, subjectLength)
                        if iszero(gt(searchLength, subjectLength)) {
                            let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
                            let h := 0
                            if iszero(lt(searchLength, 32)) {
                                h := keccak256(search, searchLength)
                            }
                            let m := shl(3, sub(32, and(searchLength, 31)))
                            let s := mload(search)
                            // prettier-ignore
                            for {} 1 {} {
                                let t := mload(subject)
                                // Whether the first `searchLength % 32` bytes of 
                                // `subject` and `search` matches.
                                if iszero(shr(m, xor(t, s))) {
                                    if h {
                                        if iszero(eq(keccak256(subject, searchLength), h)) {
                                            mstore(result, t)
                                            result := add(result, 1)
                                            subject := add(subject, 1)
                                            // prettier-ignore
                                            if iszero(lt(subject, subjectSearchEnd)) { break }
                                            continue
                                        }
                                    }
                                    // Copy the `replacement` one word at a time.
                                    // prettier-ignore
                                    for { let o := 0 } 1 {} {
                                        mstore(add(result, o), mload(add(replacement, o)))
                                        o := add(o, 0x20)
                                        // prettier-ignore
                                        if iszero(lt(o, replacementLength)) { break }
                                    }
                                    result := add(result, replacementLength)
                                    subject := add(subject, searchLength)    
                                    if iszero(searchLength) {
                                        mstore(result, t)
                                        result := add(result, 1)
                                        subject := add(subject, 1)
                                    }
                                    // prettier-ignore
                                    if iszero(lt(subject, subjectSearchEnd)) { break }
                                    continue
                                }
                                mstore(result, t)
                                result := add(result, 1)
                                subject := add(subject, 1)
                                // prettier-ignore
                                if iszero(lt(subject, subjectSearchEnd)) { break }
                            }
                        }
                        let resultRemainder := result
                        result := add(mload(0x40), 0x20)
                        let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))
                        // Copy the rest of the string one word at a time.
                        // prettier-ignore
                        for {} lt(subject, subjectEnd) {} {
                            mstore(resultRemainder, mload(subject))
                            resultRemainder := add(resultRemainder, 0x20)
                            subject := add(subject, 0x20)
                        }
                        // Allocate memory for the length and the bytes,
                        // rounded up to a multiple of 32.
                        mstore(0x40, add(result, and(add(k, 0x40), not(0x1f))))
                        result := sub(result, 0x20)
                        mstore(result, k)
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree.
            /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)
            /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)
            /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol)
            library MerkleProofLib {
                function verify(
                    bytes32[] calldata proof,
                    bytes32 root,
                    bytes32 leaf
                ) internal pure returns (bool isValid) {
                    assembly {
                        if proof.length {
                            // Left shift by 5 is equivalent to multiplying by 0x20.
                            let end := add(proof.offset, shl(5, proof.length))
                            // Initialize `offset` to the offset of `proof` in the calldata.
                            let offset := proof.offset
                            // Iterate over proof elements to compute root hash.
                            // prettier-ignore
                            for {} 1 {} {
                                // Slot of `leaf` in scratch space.
                                // If the condition is true: 0x20, otherwise: 0x00.
                                let scratch := shl(5, gt(leaf, calldataload(offset)))
                                // Store elements to hash contiguously in scratch space.
                                // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
                                mstore(scratch, leaf)
                                mstore(xor(scratch, 0x20), calldataload(offset))
                                // Reuse `leaf` to store the hash to reduce stack operations.
                                leaf := keccak256(0x00, 0x40)
                                offset := add(offset, 0x20)
                                // prettier-ignore
                                if iszero(lt(offset, end)) { break }
                            }
                        }
                        isValid := eq(leaf, root)
                    }
                }
                function verifyMultiProof(
                    bytes32[] calldata proof,
                    bytes32 root,
                    bytes32[] calldata leafs,
                    bool[] calldata flags
                ) internal pure returns (bool isValid) {
                    // Rebuilds the root by consuming and producing values on a queue.
                    // The queue starts with the `leafs` array, and goes into a `hashes` array.
                    // After the process, the last element on the queue is verified
                    // to be equal to the `root`.
                    //
                    // The `flags` array denotes whether the sibling
                    // should be popped from the queue (`flag == true`), or
                    // should be popped from the `proof` (`flag == false`).
                    assembly {
                        // If the number of flags is correct.
                        // prettier-ignore
                        for {} eq(add(leafs.length, proof.length), add(flags.length, 1)) {} {
                            // Left shift by 5 is equivalent to multiplying by 0x20.
                            // Compute the end calldata offset of `leafs`.
                            let leafsEnd := add(leafs.offset, shl(5, leafs.length))
                            // These are the calldata offsets.
                            let leafsOffset := leafs.offset
                            let flagsOffset := flags.offset
                            let proofOffset := proof.offset
                            // We can use the free memory space for the queue.
                            // We don't need to allocate, since the queue is temporary.
                            let hashesFront := mload(0x40)
                            let hashesBack := hashesFront
                            // This is the end of the memory for the queue.
                            let end := add(hashesBack, shl(5, flags.length))
                            // For the case where `proof.length + leafs.length == 1`.
                            if iszero(flags.length) {
                                // If `proof.length` is zero, `leafs.length` is 1.
                                if iszero(proof.length) {
                                    isValid := eq(calldataload(leafsOffset), root)
                                    break
                                }
                                // If `leafs.length` is zero, `proof.length` is 1.
                                if iszero(leafs.length) {
                                    isValid := eq(calldataload(proofOffset), root)
                                    break
                                }
                            }
                            // prettier-ignore
                            for {} 1 {} {
                                let a := 0
                                // Pops a value from the queue into `a`.
                                switch lt(leafsOffset, leafsEnd)
                                case 0 {
                                    // Pop from `hashes` if there are no more leafs.
                                    a := mload(hashesFront)
                                    hashesFront := add(hashesFront, 0x20)
                                }
                                default {
                                    // Otherwise, pop from `leafs`.
                                    a := calldataload(leafsOffset)
                                    leafsOffset := add(leafsOffset, 0x20)
                                }
                                let b := 0
                                // If the flag is false, load the next proof,
                                // else, pops from the queue.
                                switch calldataload(flagsOffset)
                                case 0 {
                                    // Loads the next proof.
                                    b := calldataload(proofOffset)
                                    proofOffset := add(proofOffset, 0x20)
                                }
                                default {
                                    // Pops a value from the queue into `a`.
                                    switch lt(leafsOffset, leafsEnd)
                                    case 0 {
                                        // Pop from `hashes` if there are no more leafs.
                                        b := mload(hashesFront)
                                        hashesFront := add(hashesFront, 0x20)
                                    }
                                    default {
                                        // Otherwise, pop from `leafs`.
                                        b := calldataload(leafsOffset)
                                        leafsOffset := add(leafsOffset, 0x20)
                                    }
                                }
                                // Advance to the next flag offset.
                                flagsOffset := add(flagsOffset, 0x20)
                                // Slot of `a` in scratch space.
                                // If the condition is true: 0x20, otherwise: 0x00.
                                let scratch := shl(5, gt(a, b))
                                // Hash the scratch space and push the result onto the queue.
                                mstore(scratch, a)
                                mstore(xor(scratch, 0x20), b)
                                mstore(hashesBack, keccak256(0x00, 0x40))
                                hashesBack := add(hashesBack, 0x20)
                                // prettier-ignore
                                if iszero(lt(hashesBack, end)) { break }
                            }
                            // Checks if the last value in the queue is same as the root.
                            isValid := eq(mload(sub(hashesBack, 0x20)), root)
                            break
                        }
                    }
                }
            }
            

            File 3 of 5: Sproto_Gremlins_Proxy
            // Sources flattened with hardhat v2.22.13 https://hardhat.org
            
            // SPDX-License-Identifier: Apache-2.0 AND LZBL-1.2 AND MIT AND UNLICENSED
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            struct SetConfigParam {
                uint32 eid;
                uint32 configType;
                bytes config;
            }
            
            interface IMessageLibManager {
                struct Timeout {
                    address lib;
                    uint256 expiry;
                }
            
                event LibraryRegistered(address newLib);
                event DefaultSendLibrarySet(uint32 eid, address newLib);
                event DefaultReceiveLibrarySet(uint32 eid, address newLib);
                event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
                event SendLibrarySet(address sender, uint32 eid, address newLib);
                event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
                event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
            
                function registerLibrary(address _lib) external;
            
                function isRegisteredLibrary(address _lib) external view returns (bool);
            
                function getRegisteredLibraries() external view returns (address[] memory);
            
                function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
            
                function defaultSendLibrary(uint32 _eid) external view returns (address);
            
                function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external;
            
                function defaultReceiveLibrary(uint32 _eid) external view returns (address);
            
                function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
            
                function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
            
                function isSupportedEid(uint32 _eid) external view returns (bool);
            
                function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
            
                /// ------------------- OApp interfaces -------------------
                function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
            
                function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
            
                function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
            
                function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
            
                function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
            
                function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external;
            
                function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
            
                function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
            
                function getConfig(
                    address _oapp,
                    address _lib,
                    uint32 _eid,
                    uint32 _configType
                ) external view returns (bytes memory config);
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            interface IMessagingChannel {
                event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
                event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
                event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
            
                function eid() external view returns (uint32);
            
                // this is an emergency function if a message cannot be verified for some reasons
                // required to provide _nextNonce to avoid race condition
                function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
            
                function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
            
                function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
            
                function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
            
                function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
            
                function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
            
                function inboundPayloadHash(
                    address _receiver,
                    uint32 _srcEid,
                    bytes32 _sender,
                    uint64 _nonce
                ) external view returns (bytes32);
            
                function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            interface IMessagingComposer {
                event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
                event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
                event LzComposeAlert(
                    address indexed from,
                    address indexed to,
                    address indexed executor,
                    bytes32 guid,
                    uint16 index,
                    uint256 gas,
                    uint256 value,
                    bytes message,
                    bytes extraData,
                    bytes reason
                );
            
                function composeQueue(
                    address _from,
                    address _to,
                    bytes32 _guid,
                    uint16 _index
                ) external view returns (bytes32 messageHash);
            
                function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
            
                function lzCompose(
                    address _from,
                    address _to,
                    bytes32 _guid,
                    uint16 _index,
                    bytes calldata _message,
                    bytes calldata _extraData
                ) external payable;
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            interface IMessagingContext {
                function isSendingMessage() external view returns (bool);
            
                function getSendContext() external view returns (uint32 dstEid, address sender);
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            
            
            
            struct MessagingParams {
                uint32 dstEid;
                bytes32 receiver;
                bytes message;
                bytes options;
                bool payInLzToken;
            }
            
            struct MessagingReceipt {
                bytes32 guid;
                uint64 nonce;
                MessagingFee fee;
            }
            
            struct MessagingFee {
                uint256 nativeFee;
                uint256 lzTokenFee;
            }
            
            struct Origin {
                uint32 srcEid;
                bytes32 sender;
                uint64 nonce;
            }
            
            interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
                event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
            
                event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
            
                event PacketDelivered(Origin origin, address receiver);
            
                event LzReceiveAlert(
                    address indexed receiver,
                    address indexed executor,
                    Origin origin,
                    bytes32 guid,
                    uint256 gas,
                    uint256 value,
                    bytes message,
                    bytes extraData,
                    bytes reason
                );
            
                event LzTokenSet(address token);
            
                event DelegateSet(address sender, address delegate);
            
                function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
            
                function send(
                    MessagingParams calldata _params,
                    address _refundAddress
                ) external payable returns (MessagingReceipt memory);
            
                function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
            
                function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
            
                function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
            
                function lzReceive(
                    Origin calldata _origin,
                    address _receiver,
                    bytes32 _guid,
                    bytes calldata _message,
                    bytes calldata _extraData
                ) external payable;
            
                // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
                function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
            
                function setLzToken(address _lzToken) external;
            
                function lzToken() external view returns (address);
            
                function nativeToken() external view returns (address);
            
                function setDelegate(address _delegate) external;
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            interface ILayerZeroReceiver {
                function allowInitializePath(Origin calldata _origin) external view returns (bool);
            
                function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);
            
                function lzReceive(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) external payable;
            }
            
            
            // File @openzeppelin/contracts/utils/introspection/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Interface of the ERC-165 standard, as defined in the
             * https://eips.ethereum.org/EIPS/eip-165[ERC].
             *
             * Implementers can declare support of contract interfaces, which can then be
             * queried by others ({ERC165Checker}).
             *
             * For an implementation, see {ERC165}.
             */
            interface IERC165 {
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30 000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) external view returns (bool);
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            enum MessageLibType {
                Send,
                Receive,
                SendAndReceive
            }
            
            interface IMessageLib is IERC165 {
                function setConfig(address _oapp, SetConfigParam[] calldata _config) external;
            
                function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);
            
                function isSupportedEid(uint32 _eid) external view returns (bool);
            
                // message libs of same major version are compatible
                function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
            
                function messageLibType() external view returns (MessageLibType);
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity >=0.8.0;
            
            
            struct Packet {
                uint64 nonce;
                uint32 srcEid;
                address sender;
                uint32 dstEid;
                bytes32 receiver;
                bytes32 guid;
                bytes message;
            }
            
            interface ISendLib is IMessageLib {
                function send(
                    Packet calldata _packet,
                    bytes calldata _options,
                    bool _payInLzToken
                ) external returns (MessagingFee memory, bytes memory encodedPacket);
            
                function quote(
                    Packet calldata _packet,
                    bytes calldata _options,
                    bool _payInLzToken
                ) external view returns (MessagingFee memory);
            
                function setTreasury(address _treasury) external;
            
                function withdrawFee(address _to, uint256 _amount) external;
            
                function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/libs/[email protected]
            
            // Original license: SPDX_License_Identifier: LZBL-1.2
            
            pragma solidity ^0.8.20;
            
            library AddressCast {
                error AddressCast_InvalidSizeForAddress();
                error AddressCast_InvalidAddress();
            
                function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
                    if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
                    result = bytes32(_addressBytes);
                    unchecked {
                        uint256 offset = 32 - _addressBytes.length;
                        result = result >> (offset * 8);
                    }
                }
            
                function toBytes32(address _address) internal pure returns (bytes32 result) {
                    result = bytes32(uint256(uint160(_address)));
                }
            
                function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
                    if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
                    result = new bytes(_size);
                    unchecked {
                        uint256 offset = 256 - _size * 8;
                        assembly {
                            mstore(add(result, 32), shl(offset, _addressBytes32))
                        }
                    }
                }
            
                function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
                    result = address(uint160(uint256(_addressBytes32)));
                }
            
                function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
                    if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
                    result = address(bytes20(_addressBytes));
                }
            }
            
            
            // File @layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/[email protected]
            
            // Original license: SPDX_License_Identifier: LZBL-1.2
            
            pragma solidity ^0.8.20;
            
            
            library PacketV1Codec {
                using AddressCast for address;
                using AddressCast for bytes32;
            
                uint8 internal constant PACKET_VERSION = 1;
            
                // header (version + nonce + path)
                // version
                uint256 private constant PACKET_VERSION_OFFSET = 0;
                //    nonce
                uint256 private constant NONCE_OFFSET = 1;
                //    path
                uint256 private constant SRC_EID_OFFSET = 9;
                uint256 private constant SENDER_OFFSET = 13;
                uint256 private constant DST_EID_OFFSET = 45;
                uint256 private constant RECEIVER_OFFSET = 49;
                // payload (guid + message)
                uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path)
                uint256 private constant MESSAGE_OFFSET = 113;
            
                function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {
                    encodedPacket = abi.encodePacked(
                        PACKET_VERSION,
                        _packet.nonce,
                        _packet.srcEid,
                        _packet.sender.toBytes32(),
                        _packet.dstEid,
                        _packet.receiver,
                        _packet.guid,
                        _packet.message
                    );
                }
            
                function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) {
                    return
                        abi.encodePacked(
                            PACKET_VERSION,
                            _packet.nonce,
                            _packet.srcEid,
                            _packet.sender.toBytes32(),
                            _packet.dstEid,
                            _packet.receiver
                        );
                }
            
                function encodePayload(Packet memory _packet) internal pure returns (bytes memory) {
                    return abi.encodePacked(_packet.guid, _packet.message);
                }
            
                function header(bytes calldata _packet) internal pure returns (bytes calldata) {
                    return _packet[0:GUID_OFFSET];
                }
            
                function version(bytes calldata _packet) internal pure returns (uint8) {
                    return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET]));
                }
            
                function nonce(bytes calldata _packet) internal pure returns (uint64) {
                    return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET]));
                }
            
                function srcEid(bytes calldata _packet) internal pure returns (uint32) {
                    return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET]));
                }
            
                function sender(bytes calldata _packet) internal pure returns (bytes32) {
                    return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]);
                }
            
                function senderAddressB20(bytes calldata _packet) internal pure returns (address) {
                    return sender(_packet).toAddress();
                }
            
                function dstEid(bytes calldata _packet) internal pure returns (uint32) {
                    return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET]));
                }
            
                function receiver(bytes calldata _packet) internal pure returns (bytes32) {
                    return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]);
                }
            
                function receiverB20(bytes calldata _packet) internal pure returns (address) {
                    return receiver(_packet).toAddress();
                }
            
                function guid(bytes calldata _packet) internal pure returns (bytes32) {
                    return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]);
                }
            
                function message(bytes calldata _packet) internal pure returns (bytes calldata) {
                    return bytes(_packet[MESSAGE_OFFSET:]);
                }
            
                function payload(bytes calldata _packet) internal pure returns (bytes calldata) {
                    return bytes(_packet[GUID_OFFSET:]);
                }
            
                function payloadHash(bytes calldata _packet) internal pure returns (bytes32) {
                    return keccak256(payload(_packet));
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            /**
             * @title IOAppCore
             */
            interface IOAppCore {
                // Custom error messages
                error OnlyPeer(uint32 eid, bytes32 sender);
                error NoPeer(uint32 eid);
                error InvalidEndpointCall();
                error InvalidDelegate();
            
                // Event emitted when a peer (OApp) is set for a corresponding endpoint
                event PeerSet(uint32 eid, bytes32 peer);
            
                /**
                 * @notice Retrieves the OApp version information.
                 * @return senderVersion The version of the OAppSender.sol contract.
                 * @return receiverVersion The version of the OAppReceiver.sol contract.
                 */
                function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);
            
                /**
                 * @notice Retrieves the LayerZero endpoint associated with the OApp.
                 * @return iEndpoint The LayerZero endpoint as an interface.
                 */
                function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);
            
                /**
                 * @notice Retrieves the peer (OApp) associated with a corresponding endpoint.
                 * @param _eid The endpoint ID.
                 * @return peer The peer address (OApp instance) associated with the corresponding endpoint.
                 */
                function peers(uint32 _eid) external view returns (bytes32 peer);
            
                /**
                 * @notice Sets the peer address (OApp instance) for a corresponding endpoint.
                 * @param _eid The endpoint ID.
                 * @param _peer The address of the peer to be associated with the corresponding endpoint.
                 */
                function setPeer(uint32 _eid, bytes32 _peer) external;
            
                /**
                 * @notice Sets the delegate address for the OApp Core.
                 * @param _delegate The address of the delegate to be set.
                 */
                function setDelegate(address _delegate) external;
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            pragma solidity ^0.8.20;
            
            interface IOAppReceiver is ILayerZeroReceiver {
                /**
                 * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
                 * @param _origin The origin information containing the source endpoint and sender address.
                 *  - srcEid: The source chain endpoint ID.
                 *  - sender: The sender address on the src chain.
                 *  - nonce: The nonce of the message.
                 * @param _message The lzReceive payload.
                 * @param _sender The sender address.
                 * @return isSender Is a valid sender.
                 *
                 * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.
                 * @dev The default sender IS the OAppReceiver implementer.
                 */
                function isComposeMsgSender(
                    Origin calldata _origin,
                    bytes calldata _message,
                    address _sender
                ) external view returns (bool isSender);
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Struct representing enforced option parameters.
             */
            struct EnforcedOptionParam {
                uint32 eid; // Endpoint ID
                uint16 msgType; // Message Type
                bytes options; // Additional options
            }
            
            /**
             * @title IOAppOptionsType3
             * @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options.
             */
            interface IOAppOptionsType3 {
                // Custom error message for invalid options
                error InvalidOptions(bytes options);
            
                // Event emitted when enforced options are set
                event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions);
            
                /**
                 * @notice Sets enforced options for specific endpoint and message type combinations.
                 * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
                 */
                function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external;
            
                /**
                 * @notice Combines options for a given endpoint and message type.
                 * @param _eid The endpoint ID.
                 * @param _msgType The OApp message type.
                 * @param _extraOptions Additional options passed by the caller.
                 * @return options The combination of caller specified options AND enforced options.
                 */
                function combineOptions(
                    uint32 _eid,
                    uint16 _msgType,
                    bytes calldata _extraOptions
                ) external view returns (bytes memory options);
            }
            
            
            // File @openzeppelin/contracts/utils/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Provides information about the current execution context, including the
             * sender of the transaction and its data. While these are generally available
             * via msg.sender and msg.data, they should not be accessed in such a direct
             * manner, since when dealing with meta-transactions the account sending and
             * paying for execution may not be the actual sender (as far as an application
             * is concerned).
             *
             * This contract is only required for intermediate, library-like contracts.
             */
            abstract contract Context {
                function _msgSender() internal view virtual returns (address) {
                    return msg.sender;
                }
            
                function _msgData() internal view virtual returns (bytes calldata) {
                    return msg.data;
                }
            
                function _contextSuffixLength() internal view virtual returns (uint256) {
                    return 0;
                }
            }
            
            
            // File @openzeppelin/contracts/access/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Contract module which provides a basic access control mechanism, where
             * there is an account (an owner) that can be granted exclusive access to
             * specific functions.
             *
             * The initial owner is set to the address provided by the deployer. This can
             * later be changed with {transferOwnership}.
             *
             * This module is used through inheritance. It will make available the modifier
             * `onlyOwner`, which can be applied to your functions to restrict their use to
             * the owner.
             */
            abstract contract Ownable is Context {
                address private _owner;
            
                /**
                 * @dev The caller account is not authorized to perform an operation.
                 */
                error OwnableUnauthorizedAccount(address account);
            
                /**
                 * @dev The owner is not a valid owner account. (eg. `address(0)`)
                 */
                error OwnableInvalidOwner(address owner);
            
                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            
                /**
                 * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
                 */
                constructor(address initialOwner) {
                    if (initialOwner == address(0)) {
                        revert OwnableInvalidOwner(address(0));
                    }
                    _transferOwnership(initialOwner);
                }
            
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                    _checkOwner();
                    _;
                }
            
                /**
                 * @dev Returns the address of the current owner.
                 */
                function owner() public view virtual returns (address) {
                    return _owner;
                }
            
                /**
                 * @dev Throws if the sender is not the owner.
                 */
                function _checkOwner() internal view virtual {
                    if (owner() != _msgSender()) {
                        revert OwnableUnauthorizedAccount(_msgSender());
                    }
                }
            
                /**
                 * @dev Leaves the contract without owner. It will not be possible to call
                 * `onlyOwner` functions. Can only be called by the current owner.
                 *
                 * NOTE: Renouncing ownership will leave the contract without an owner,
                 * thereby disabling any functionality that is only available to the owner.
                 */
                function renounceOwnership() public virtual onlyOwner {
                    _transferOwnership(address(0));
                }
            
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Can only be called by the current owner.
                 */
                function transferOwnership(address newOwner) public virtual onlyOwner {
                    if (newOwner == address(0)) {
                        revert OwnableInvalidOwner(address(0));
                    }
                    _transferOwnership(newOwner);
                }
            
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Internal function without access restriction.
                 */
                function _transferOwnership(address newOwner) internal virtual {
                    address oldOwner = _owner;
                    _owner = newOwner;
                    emit OwnershipTransferred(oldOwner, newOwner);
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/libs/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            
            /**
             * @title OAppOptionsType3
             * @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.
             */
            abstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable {
                uint16 internal constant OPTION_TYPE_3 = 3;
            
                // @dev The "msgType" should be defined in the child contract.
                mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions;
            
                /**
                 * @dev Sets the enforced options for specific endpoint and message type combinations.
                 * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
                 *
                 * @dev Only the owner/admin of the OApp can call this function.
                 * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
                 * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
                 * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
                 * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
                 */
                function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner {
                    _setEnforcedOptions(_enforcedOptions);
                }
            
                /**
                 * @dev Sets the enforced options for specific endpoint and message type combinations.
                 * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
                 *
                 * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
                 * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
                 * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
                 * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
                 */
                function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual {
                    for (uint256 i = 0; i < _enforcedOptions.length; i++) {
                        // @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.
                        _assertOptionsType3(_enforcedOptions[i].options);
                        enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;
                    }
            
                    emit EnforcedOptionSet(_enforcedOptions);
                }
            
                /**
                 * @notice Combines options for a given endpoint and message type.
                 * @param _eid The endpoint ID.
                 * @param _msgType The OAPP message type.
                 * @param _extraOptions Additional options passed by the caller.
                 * @return options The combination of caller specified options AND enforced options.
                 *
                 * @dev If there is an enforced lzReceive option:
                 * - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}
                 * - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.
                 * @dev This presence of duplicated options is handled off-chain in the verifier/executor.
                 */
                function combineOptions(
                    uint32 _eid,
                    uint16 _msgType,
                    bytes calldata _extraOptions
                ) public view virtual returns (bytes memory) {
                    bytes memory enforced = enforcedOptions[_eid][_msgType];
            
                    // No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.
                    if (enforced.length == 0) return _extraOptions;
            
                    // No caller options, return enforced
                    if (_extraOptions.length == 0) return enforced;
            
                    // @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.
                    if (_extraOptions.length >= 2) {
                        _assertOptionsType3(_extraOptions);
                        // @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.
                        return bytes.concat(enforced, _extraOptions[2:]);
                    }
            
                    // No valid set of options was found.
                    revert InvalidOptions(_extraOptions);
                }
            
                /**
                 * @dev Internal function to assert that options are of type 3.
                 * @param _options The options to be checked.
                 */
                function _assertOptionsType3(bytes memory _options) internal pure virtual {
                    uint16 optionsType;
                    assembly {
                        optionsType := mload(add(_options, 2))
                    }
                    if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            
            /**
             * @title OAppCore
             * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.
             */
            abstract contract OAppCore is IOAppCore, Ownable {
                // The LayerZero endpoint associated with the given OApp
                ILayerZeroEndpointV2 public immutable endpoint;
            
                // Mapping to store peers associated with corresponding endpoints
                mapping(uint32 eid => bytes32 peer) public peers;
            
                /**
                 * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.
                 * @param _endpoint The address of the LOCAL Layer Zero endpoint.
                 * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
                 *
                 * @dev The delegate typically should be set as the owner of the contract.
                 */
                constructor(address _endpoint, address _delegate) {
                    endpoint = ILayerZeroEndpointV2(_endpoint);
            
                    if (_delegate == address(0)) revert InvalidDelegate();
                    endpoint.setDelegate(_delegate);
                }
            
                /**
                 * @notice Sets the peer address (OApp instance) for a corresponding endpoint.
                 * @param _eid The endpoint ID.
                 * @param _peer The address of the peer to be associated with the corresponding endpoint.
                 *
                 * @dev Only the owner/admin of the OApp can call this function.
                 * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
                 * @dev Set this to bytes32(0) to remove the peer address.
                 * @dev Peer is a bytes32 to accommodate non-evm chains.
                 */
                function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {
                    _setPeer(_eid, _peer);
                }
            
                /**
                 * @notice Sets the peer address (OApp instance) for a corresponding endpoint.
                 * @param _eid The endpoint ID.
                 * @param _peer The address of the peer to be associated with the corresponding endpoint.
                 *
                 * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
                 * @dev Set this to bytes32(0) to remove the peer address.
                 * @dev Peer is a bytes32 to accommodate non-evm chains.
                 */
                function _setPeer(uint32 _eid, bytes32 _peer) internal virtual {
                    peers[_eid] = _peer;
                    emit PeerSet(_eid, _peer);
                }
            
                /**
                 * @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.
                 * ie. the peer is set to bytes32(0).
                 * @param _eid The endpoint ID.
                 * @return peer The address of the peer associated with the specified endpoint.
                 */
                function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {
                    bytes32 peer = peers[_eid];
                    if (peer == bytes32(0)) revert NoPeer(_eid);
                    return peer;
                }
            
                /**
                 * @notice Sets the delegate address for the OApp.
                 * @param _delegate The address of the delegate to be set.
                 *
                 * @dev Only the owner/admin of the OApp can call this function.
                 * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.
                 */
                function setDelegate(address _delegate) public onlyOwner {
                    endpoint.setDelegate(_delegate);
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            
            /**
             * @title OAppReceiver
             * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.
             */
            abstract contract OAppReceiver is IOAppReceiver, OAppCore {
                // Custom error message for when the caller is not the registered endpoint/
                error OnlyEndpoint(address addr);
            
                // @dev The version of the OAppReceiver implementation.
                // @dev Version is bumped when changes are made to this contract.
                uint64 internal constant RECEIVER_VERSION = 2;
            
                /**
                 * @notice Retrieves the OApp version information.
                 * @return senderVersion The version of the OAppSender.sol contract.
                 * @return receiverVersion The version of the OAppReceiver.sol contract.
                 *
                 * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.
                 * ie. this is a RECEIVE only OApp.
                 * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.
                 */
                function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
                    return (0, RECEIVER_VERSION);
                }
            
                /**
                 * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
                 * @dev _origin The origin information containing the source endpoint and sender address.
                 *  - srcEid: The source chain endpoint ID.
                 *  - sender: The sender address on the src chain.
                 *  - nonce: The nonce of the message.
                 * @dev _message The lzReceive payload.
                 * @param _sender The sender address.
                 * @return isSender Is a valid sender.
                 *
                 * @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.
                 * @dev The default sender IS the OAppReceiver implementer.
                 */
                function isComposeMsgSender(
                    Origin calldata /*_origin*/,
                    bytes calldata /*_message*/,
                    address _sender
                ) public view virtual returns (bool) {
                    return _sender == address(this);
                }
            
                /**
                 * @notice Checks if the path initialization is allowed based on the provided origin.
                 * @param origin The origin information containing the source endpoint and sender address.
                 * @return Whether the path has been initialized.
                 *
                 * @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.
                 * @dev This defaults to assuming if a peer has been set, its initialized.
                 * Can be overridden by the OApp if there is other logic to determine this.
                 */
                function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {
                    return peers[origin.srcEid] == origin.sender;
                }
            
                /**
                 * @notice Retrieves the next nonce for a given source endpoint and sender address.
                 * @dev _srcEid The source endpoint ID.
                 * @dev _sender The sender address.
                 * @return nonce The next nonce.
                 *
                 * @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.
                 * @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.
                 * @dev This is also enforced by the OApp.
                 * @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
                 */
                function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {
                    return 0;
                }
            
                /**
                 * @dev Entry point for receiving messages or packets from the endpoint.
                 * @param _origin The origin information containing the source endpoint and sender address.
                 *  - srcEid: The source chain endpoint ID.
                 *  - sender: The sender address on the src chain.
                 *  - nonce: The nonce of the message.
                 * @param _guid The unique identifier for the received LayerZero message.
                 * @param _message The payload of the received message.
                 * @param _executor The address of the executor for the received message.
                 * @param _extraData Additional arbitrary data provided by the corresponding executor.
                 *
                 * @dev Entry point for receiving msg/packet from the LayerZero endpoint.
                 */
                function lzReceive(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) public payable virtual {
                    // Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.
                    if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);
            
                    // Ensure that the sender matches the expected peer for the source endpoint.
                    if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);
            
                    // Call the internal OApp implementation of lzReceive.
                    _lzReceive(_origin, _guid, _message, _executor, _extraData);
                }
            
                /**
                 * @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.
                 */
                function _lzReceive(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) internal virtual;
            }
            
            
            // File @openzeppelin/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
            
            pragma solidity ^0.8.20;
            
            
            // File @openzeppelin/contracts/token/ERC20/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Interface of the ERC-20 standard as defined in the ERC.
             */
            interface IERC20 {
                /**
                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                 * another (`to`).
                 *
                 * Note that `value` may be zero.
                 */
                event Transfer(address indexed from, address indexed to, uint256 value);
            
                /**
                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                 * a call to {approve}. `value` is the new allowance.
                 */
                event Approval(address indexed owner, address indexed spender, uint256 value);
            
                /**
                 * @dev Returns the value of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
            
                /**
                 * @dev Returns the value of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
            
                /**
                 * @dev Moves a `value` amount of tokens from the caller's account to `to`.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transfer(address to, uint256 value) external returns (bool);
            
                /**
                 * @dev Returns the remaining number of tokens that `spender` will be
                 * allowed to spend on behalf of `owner` through {transferFrom}. This is
                 * zero by default.
                 *
                 * This value changes when {approve} or {transferFrom} are called.
                 */
                function allowance(address owner, address spender) external view returns (uint256);
            
                /**
                 * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
                 * caller's tokens.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * IMPORTANT: Beware that changing an allowance with this method brings the risk
                 * that someone may use both the old and the new allowance by unfortunate
                 * transaction ordering. One possible solution to mitigate this race
                 * condition is to first reduce the spender's allowance to 0 and set the
                 * desired value afterwards:
                 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address spender, uint256 value) external returns (bool);
            
                /**
                 * @dev Moves a `value` amount of tokens from `from` to `to` using the
                 * allowance mechanism. `value` is then deducted from the caller's
                 * allowance.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(address from, address to, uint256 value) external returns (bool);
            }
            
            
            // File @openzeppelin/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
            
            pragma solidity ^0.8.20;
            
            
            // File @openzeppelin/contracts/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
            
            pragma solidity ^0.8.20;
            
            
            /**
             * @title IERC1363
             * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
             *
             * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
             * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
             */
            interface IERC1363 is IERC20, IERC165 {
                /*
                 * Note: the ERC-165 identifier for this interface is 0xb0202a11.
                 * 0xb0202a11 ===
                 *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
                 *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
                 *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
                 *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
                 *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
                 *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
                 */
            
                /**
                 * @dev Moves a `value` amount of tokens from the caller's account to `to`
                 * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
                 * @param to The address which you want to transfer to.
                 * @param value The amount of tokens to be transferred.
                 * @return A boolean value indicating whether the operation succeeded unless throwing.
                 */
                function transferAndCall(address to, uint256 value) external returns (bool);
            
                /**
                 * @dev Moves a `value` amount of tokens from the caller's account to `to`
                 * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
                 * @param to The address which you want to transfer to.
                 * @param value The amount of tokens to be transferred.
                 * @param data Additional data with no specified format, sent in call to `to`.
                 * @return A boolean value indicating whether the operation succeeded unless throwing.
                 */
                function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
            
                /**
                 * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
                 * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
                 * @param from The address which you want to send tokens from.
                 * @param to The address which you want to transfer to.
                 * @param value The amount of tokens to be transferred.
                 * @return A boolean value indicating whether the operation succeeded unless throwing.
                 */
                function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
            
                /**
                 * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
                 * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
                 * @param from The address which you want to send tokens from.
                 * @param to The address which you want to transfer to.
                 * @param value The amount of tokens to be transferred.
                 * @param data Additional data with no specified format, sent in call to `to`.
                 * @return A boolean value indicating whether the operation succeeded unless throwing.
                 */
                function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
            
                /**
                 * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
                 * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
                 * @param spender The address which will spend the funds.
                 * @param value The amount of tokens to be spent.
                 * @return A boolean value indicating whether the operation succeeded unless throwing.
                 */
                function approveAndCall(address spender, uint256 value) external returns (bool);
            
                /**
                 * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
                 * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
                 * @param spender The address which will spend the funds.
                 * @param value The amount of tokens to be spent.
                 * @param data Additional data with no specified format, sent in call to `spender`.
                 * @return A boolean value indicating whether the operation succeeded unless throwing.
                 */
                function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
            }
            
            
            // File @openzeppelin/contracts/utils/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Collection of common custom errors used in multiple contracts
             *
             * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
             * It is recommended to avoid relying on the error API for critical functionality.
             *
             * _Available since v5.1._
             */
            library Errors {
                /**
                 * @dev The ETH balance of the account is not enough to perform the operation.
                 */
                error InsufficientBalance(uint256 balance, uint256 needed);
            
                /**
                 * @dev A call to an address target failed. The target may have reverted.
                 */
                error FailedCall();
            
                /**
                 * @dev The deployment failed.
                 */
                error FailedDeployment();
            
                /**
                 * @dev A necessary precompile is missing.
                 */
                error MissingPrecompile(address);
            }
            
            
            // File @openzeppelin/contracts/utils/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev There's no code at `target` (it is not a contract).
                 */
                error AddressEmptyCode(address target);
            
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    if (address(this).balance < amount) {
                        revert Errors.InsufficientBalance(address(this).balance, amount);
                    }
            
                    (bool success, ) = recipient.call{value: amount}("");
                    if (!success) {
                        revert Errors.FailedCall();
                    }
                }
            
                /**
                 * @dev Performs a Solidity function call using a low level `call`. A
                 * plain `call` is an unsafe replacement for a function call: use this
                 * function instead.
                 *
                 * If `target` reverts with a revert reason or custom error, it is bubbled
                 * up by this function (like regular Solidity function calls). However, if
                 * the call reverted with no returned reason, this function reverts with a
                 * {Errors.FailedCall} error.
                 *
                 * Returns the raw returned data. To convert to the expected return value,
                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                 *
                 * Requirements:
                 *
                 * - `target` must be a contract.
                 * - calling `target` with `data` must not revert.
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0);
                }
            
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but also transferring `value` wei to `target`.
                 *
                 * Requirements:
                 *
                 * - the calling contract must have an ETH balance of at least `value`.
                 * - the called Solidity function must be `payable`.
                 */
                function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                    if (address(this).balance < value) {
                        revert Errors.InsufficientBalance(address(this).balance, value);
                    }
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
            
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
            
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResultFromTarget(target, success, returndata);
                }
            
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
                 * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
                 * of an unsuccessful call.
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata
                ) internal view returns (bytes memory) {
                    if (!success) {
                        _revert(returndata);
                    } else {
                        // only check if target is a contract if the call was successful and the return data is empty
                        // otherwise we already know that it was a contract
                        if (returndata.length == 0 && target.code.length == 0) {
                            revert AddressEmptyCode(target);
                        }
                        return returndata;
                    }
                }
            
                /**
                 * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
                 * revert reason or with a default {Errors.FailedCall} error.
                 */
                function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
                    if (!success) {
                        _revert(returndata);
                    } else {
                        return returndata;
                    }
                }
            
                /**
                 * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
                 */
                function _revert(bytes memory returndata) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        assembly ("memory-safe") {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert Errors.FailedCall();
                    }
                }
            }
            
            
            // File @openzeppelin/contracts/token/ERC20/utils/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
            
            pragma solidity ^0.8.20;
            
            
            
            /**
             * @title SafeERC20
             * @dev Wrappers around ERC-20 operations that throw on failure (when the token
             * contract returns false). Tokens that return no value (and instead revert or
             * throw on failure) are also supported, non-reverting calls are assumed to be
             * successful.
             * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
             * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
             */
            library SafeERC20 {
                /**
                 * @dev An operation with an ERC-20 token failed.
                 */
                error SafeERC20FailedOperation(address token);
            
                /**
                 * @dev Indicates a failed `decreaseAllowance` request.
                 */
                error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
            
                /**
                 * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
                 * non-reverting calls are assumed to be successful.
                 */
                function safeTransfer(IERC20 token, address to, uint256 value) internal {
                    _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
                }
            
                /**
                 * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
                 * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
                 */
                function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                    _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
                }
            
                /**
                 * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                 * non-reverting calls are assumed to be successful.
                 *
                 * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
                 * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
                 * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
                 * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
                 */
                function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                    uint256 oldAllowance = token.allowance(address(this), spender);
                    forceApprove(token, spender, oldAllowance + value);
                }
            
                /**
                 * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
                 * value, non-reverting calls are assumed to be successful.
                 *
                 * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
                 * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
                 * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
                 * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
                 */
                function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
                    unchecked {
                        uint256 currentAllowance = token.allowance(address(this), spender);
                        if (currentAllowance < requestedDecrease) {
                            revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
                        }
                        forceApprove(token, spender, currentAllowance - requestedDecrease);
                    }
                }
            
                /**
                 * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
                 * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
                 * to be set to zero before setting it to a non-zero value, such as USDT.
                 *
                 * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
                 * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
                 * set here.
                 */
                function forceApprove(IERC20 token, address spender, uint256 value) internal {
                    bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
            
                    if (!_callOptionalReturnBool(token, approvalCall)) {
                        _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
                        _callOptionalReturn(token, approvalCall);
                    }
                }
            
                /**
                 * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
                 * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
                 * targeting contracts.
                 *
                 * Reverts if the returned value is other than `true`.
                 */
                function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
                    if (to.code.length == 0) {
                        safeTransfer(token, to, value);
                    } else if (!token.transferAndCall(to, value, data)) {
                        revert SafeERC20FailedOperation(address(token));
                    }
                }
            
                /**
                 * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
                 * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
                 * targeting contracts.
                 *
                 * Reverts if the returned value is other than `true`.
                 */
                function transferFromAndCallRelaxed(
                    IERC1363 token,
                    address from,
                    address to,
                    uint256 value,
                    bytes memory data
                ) internal {
                    if (to.code.length == 0) {
                        safeTransferFrom(token, from, to, value);
                    } else if (!token.transferFromAndCall(from, to, value, data)) {
                        revert SafeERC20FailedOperation(address(token));
                    }
                }
            
                /**
                 * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
                 * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
                 * targeting contracts.
                 *
                 * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
                 * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
                 * once without retrying, and relies on the returned value to be true.
                 *
                 * Reverts if the returned value is other than `true`.
                 */
                function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
                    if (to.code.length == 0) {
                        forceApprove(token, to, value);
                    } else if (!token.approveAndCall(to, value, data)) {
                        revert SafeERC20FailedOperation(address(token));
                    }
                }
            
                /**
                 * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                 * on the return value: the return value is optional (but if data is returned, it must not be false).
                 * @param token The token targeted by the call.
                 * @param data The call data (encoded using abi.encode or one of its variants).
                 *
                 * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
                 */
                function _callOptionalReturn(IERC20 token, bytes memory data) private {
                    uint256 returnSize;
                    uint256 returnValue;
                    assembly ("memory-safe") {
                        let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
                        // bubble errors
                        if iszero(success) {
                            let ptr := mload(0x40)
                            returndatacopy(ptr, 0, returndatasize())
                            revert(ptr, returndatasize())
                        }
                        returnSize := returndatasize()
                        returnValue := mload(0)
                    }
            
                    if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
                        revert SafeERC20FailedOperation(address(token));
                    }
                }
            
                /**
                 * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                 * on the return value: the return value is optional (but if data is returned, it must not be false).
                 * @param token The token targeted by the call.
                 * @param data The call data (encoded using abi.encode or one of its variants).
                 *
                 * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
                 */
                function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                    bool success;
                    uint256 returnSize;
                    uint256 returnValue;
                    assembly ("memory-safe") {
                        success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
                        returnSize := returndatasize()
                        returnValue := mload(0)
                    }
                    return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            
            
            /**
             * @title OAppSender
             * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.
             */
            abstract contract OAppSender is OAppCore {
                using SafeERC20 for IERC20;
            
                // Custom error messages
                error NotEnoughNative(uint256 msgValue);
                error LzTokenUnavailable();
            
                // @dev The version of the OAppSender implementation.
                // @dev Version is bumped when changes are made to this contract.
                uint64 internal constant SENDER_VERSION = 1;
            
                /**
                 * @notice Retrieves the OApp version information.
                 * @return senderVersion The version of the OAppSender.sol contract.
                 * @return receiverVersion The version of the OAppReceiver.sol contract.
                 *
                 * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.
                 * ie. this is a SEND only OApp.
                 * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions
                 */
                function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
                    return (SENDER_VERSION, 0);
                }
            
                /**
                 * @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
                 * @param _dstEid The destination endpoint ID.
                 * @param _message The message payload.
                 * @param _options Additional options for the message.
                 * @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
                 * @return fee The calculated MessagingFee for the message.
                 *      - nativeFee: The native fee for the message.
                 *      - lzTokenFee: The LZ token fee for the message.
                 */
                function _quote(
                    uint32 _dstEid,
                    bytes memory _message,
                    bytes memory _options,
                    bool _payInLzToken
                ) internal view virtual returns (MessagingFee memory fee) {
                    return
                        endpoint.quote(
                            MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),
                            address(this)
                        );
                }
            
                /**
                 * @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.
                 * @param _dstEid The destination endpoint ID.
                 * @param _message The message payload.
                 * @param _options Additional options for the message.
                 * @param _fee The calculated LayerZero fee for the message.
                 *      - nativeFee: The native fee.
                 *      - lzTokenFee: The lzToken fee.
                 * @param _refundAddress The address to receive any excess fee values sent to the endpoint.
                 * @return receipt The receipt for the sent message.
                 *      - guid: The unique identifier for the sent message.
                 *      - nonce: The nonce of the sent message.
                 *      - fee: The LayerZero fee incurred for the message.
                 */
                function _lzSend(
                    uint32 _dstEid,
                    bytes memory _message,
                    bytes memory _options,
                    MessagingFee memory _fee,
                    address _refundAddress
                ) internal virtual returns (MessagingReceipt memory receipt) {
                    // @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.
                    uint256 messageValue = _payNative(_fee.nativeFee);
                    if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);
            
                    return
                        // solhint-disable-next-line check-send-result
                        endpoint.send{ value: messageValue }(
                            MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),
                            _refundAddress
                        );
                }
            
                /**
                 * @dev Internal function to pay the native fee associated with the message.
                 * @param _nativeFee The native fee to be paid.
                 * @return nativeFee The amount of native currency paid.
                 *
                 * @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,
                 * this will need to be overridden because msg.value would contain multiple lzFees.
                 * @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.
                 * @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.
                 * @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.
                 */
                function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {
                    if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);
                    return _nativeFee;
                }
            
                /**
                 * @dev Internal function to pay the LZ token fee associated with the message.
                 * @param _lzTokenFee The LZ token fee to be paid.
                 *
                 * @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.
                 * @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().
                 */
                function _payLzToken(uint256 _lzTokenFee) internal virtual {
                    // @dev Cannot cache the token because it is not immutable in the endpoint.
                    address lzToken = endpoint.lzToken();
                    if (lzToken == address(0)) revert LzTokenUnavailable();
            
                    // Pay LZ token fee by sending tokens to the endpoint.
                    IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            // @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers
            // solhint-disable-next-line no-unused-import
            
            // @dev Import the 'Origin' so it's exposed to OApp implementers
            // solhint-disable-next-line no-unused-import
            
            
            /**
             * @title OApp
             * @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.
             */
            abstract contract OApp is OAppSender, OAppReceiver {
                /**
                 * @dev Constructor to initialize the OApp with the provided endpoint and owner.
                 * @param _endpoint The address of the LOCAL LayerZero endpoint.
                 * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
                 */
                constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}
            
                /**
                 * @notice Retrieves the OApp version information.
                 * @return senderVersion The version of the OAppSender.sol implementation.
                 * @return receiverVersion The version of the OAppReceiver.sol implementation.
                 */
                function oAppVersion()
                    public
                    pure
                    virtual
                    override(OAppSender, OAppReceiver)
                    returns (uint64 senderVersion, uint64 receiverVersion)
                {
                    return (SENDER_VERSION, RECEIVER_VERSION);
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/precrime/libs/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            
            /**
             * @title InboundPacket
             * @dev Structure representing an inbound packet received by the contract.
             */
            struct InboundPacket {
                Origin origin; // Origin information of the packet.
                uint32 dstEid; // Destination endpointId of the packet.
                address receiver; // Receiver address for the packet.
                bytes32 guid; // Unique identifier of the packet.
                uint256 value; // msg.value of the packet.
                address executor; // Executor address for the packet.
                bytes message; // Message payload of the packet.
                bytes extraData; // Additional arbitrary data for the packet.
            }
            
            /**
             * @title PacketDecoder
             * @dev Library for decoding LayerZero packets.
             */
            library PacketDecoder {
                using PacketV1Codec for bytes;
            
                /**
                 * @dev Decode an inbound packet from the given packet data.
                 * @param _packet The packet data to decode.
                 * @return packet An InboundPacket struct representing the decoded packet.
                 */
                function decode(bytes calldata _packet) internal pure returns (InboundPacket memory packet) {
                    packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce());
                    packet.dstEid = _packet.dstEid();
                    packet.receiver = _packet.receiverB20();
                    packet.guid = _packet.guid();
                    packet.message = _packet.message();
                }
            
                /**
                 * @dev Decode multiple inbound packets from the given packet data and associated message values.
                 * @param _packets An array of packet data to decode.
                 * @param _packetMsgValues An array of associated message values for each packet.
                 * @return packets An array of InboundPacket structs representing the decoded packets.
                 */
                function decode(
                    bytes[] calldata _packets,
                    uint256[] memory _packetMsgValues
                ) internal pure returns (InboundPacket[] memory packets) {
                    packets = new InboundPacket[](_packets.length);
                    for (uint256 i = 0; i < _packets.length; i++) {
                        bytes calldata packet = _packets[i];
                        packets[i] = PacketDecoder.decode(packet);
                        // @dev Allows the verifier to specify the msg.value that gets passed in lzReceive.
                        packets[i].value = _packetMsgValues[i];
                    }
                }
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/precrime/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            // @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers.
            // solhint-disable-next-line no-unused-import
            
            /**
             * @title IOAppPreCrimeSimulator Interface
             * @dev Interface for the preCrime simulation functionality in an OApp.
             */
            interface IOAppPreCrimeSimulator {
                // @dev simulation result used in PreCrime implementation
                error SimulationResult(bytes result);
                error OnlySelf();
            
                /**
                 * @dev Emitted when the preCrime contract address is set.
                 * @param preCrimeAddress The address of the preCrime contract.
                 */
                event PreCrimeSet(address preCrimeAddress);
            
                /**
                 * @dev Retrieves the address of the preCrime contract implementation.
                 * @return The address of the preCrime contract.
                 */
                function preCrime() external view returns (address);
            
                /**
                 * @dev Retrieves the address of the OApp contract.
                 * @return The address of the OApp contract.
                 */
                function oApp() external view returns (address);
            
                /**
                 * @dev Sets the preCrime contract address.
                 * @param _preCrime The address of the preCrime contract.
                 */
                function setPreCrime(address _preCrime) external;
            
                /**
                 * @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result.
                 * @param _packets An array of LayerZero InboundPacket objects representing received packets.
                 */
                function lzReceiveAndRevert(InboundPacket[] calldata _packets) external payable;
            
                /**
                 * @dev checks if the specified peer is considered 'trusted' by the OApp.
                 * @param _eid The endpoint Id to check.
                 * @param _peer The peer to check.
                 * @return Whether the peer passed is considered 'trusted' by the OApp.
                 */
                function isPeer(uint32 _eid, bytes32 _peer) external view returns (bool);
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/precrime/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            struct PreCrimePeer {
                uint32 eid;
                bytes32 preCrime;
                bytes32 oApp;
            }
            
            // TODO not done yet
            interface IPreCrime {
                error OnlyOffChain();
            
                // for simulate()
                error PacketOversize(uint256 max, uint256 actual);
                error PacketUnsorted();
                error SimulationFailed(bytes reason);
            
                // for preCrime()
                error SimulationResultNotFound(uint32 eid);
                error InvalidSimulationResult(uint32 eid, bytes reason);
                error CrimeFound(bytes crime);
            
                function getConfig(bytes[] calldata _packets, uint256[] calldata _packetMsgValues) external returns (bytes memory);
            
                function simulate(
                    bytes[] calldata _packets,
                    uint256[] calldata _packetMsgValues
                ) external payable returns (bytes memory);
            
                function buildSimulationResult() external view returns (bytes memory);
            
                function preCrime(
                    bytes[] calldata _packets,
                    uint256[] calldata _packetMsgValues,
                    bytes[] calldata _simulations
                ) external;
            
                function version() external view returns (uint64 major, uint8 minor);
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/precrime/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            
            
            /**
             * @title OAppPreCrimeSimulator
             * @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.
             */
            abstract contract OAppPreCrimeSimulator is IOAppPreCrimeSimulator, Ownable {
                // The address of the preCrime implementation.
                address public preCrime;
            
                /**
                 * @dev Retrieves the address of the OApp contract.
                 * @return The address of the OApp contract.
                 *
                 * @dev The simulator contract is the base contract for the OApp by default.
                 * @dev If the simulator is a separate contract, override this function.
                 */
                function oApp() external view virtual returns (address) {
                    return address(this);
                }
            
                /**
                 * @dev Sets the preCrime contract address.
                 * @param _preCrime The address of the preCrime contract.
                 */
                function setPreCrime(address _preCrime) public virtual onlyOwner {
                    preCrime = _preCrime;
                    emit PreCrimeSet(_preCrime);
                }
            
                /**
                 * @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results.
                 * @param _packets An array of InboundPacket objects representing received packets to be delivered.
                 *
                 * @dev WARNING: MUST revert at the end with the simulation results.
                 * @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function,
                 * WITHOUT actually executing them.
                 */
                function lzReceiveAndRevert(InboundPacket[] calldata _packets) public payable virtual {
                    for (uint256 i = 0; i < _packets.length; i++) {
                        InboundPacket calldata packet = _packets[i];
            
                        // Ignore packets that are not from trusted peers.
                        if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue;
            
                        // @dev Because a verifier is calling this function, it doesnt have access to executor params:
                        //  - address _executor
                        //  - bytes calldata _extraData
                        // preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive().
                        // They are instead stubbed to default values, address(0) and bytes("")
                        // @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit,
                        // which would cause the revert to be ignored.
                        this.lzReceiveSimulate{ value: packet.value }(
                            packet.origin,
                            packet.guid,
                            packet.message,
                            packet.executor,
                            packet.extraData
                        );
                    }
            
                    // @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult().
                    revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult());
                }
            
                /**
                 * @dev Is effectively an internal function because msg.sender must be address(this).
                 * Allows resetting the call stack for 'internal' calls.
                 * @param _origin The origin information containing the source endpoint and sender address.
                 *  - srcEid: The source chain endpoint ID.
                 *  - sender: The sender address on the src chain.
                 *  - nonce: The nonce of the message.
                 * @param _guid The unique identifier of the packet.
                 * @param _message The message payload of the packet.
                 * @param _executor The executor address for the packet.
                 * @param _extraData Additional data for the packet.
                 */
                function lzReceiveSimulate(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) external payable virtual {
                    // @dev Ensure ONLY can be called 'internally'.
                    if (msg.sender != address(this)) revert OnlySelf();
                    _lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData);
                }
            
                /**
                 * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
                 * @param _origin The origin information.
                 *  - srcEid: The source chain endpoint ID.
                 *  - sender: The sender address from the src chain.
                 *  - nonce: The nonce of the LayerZero message.
                 * @param _guid The GUID of the LayerZero message.
                 * @param _message The LayerZero message.
                 * @param _executor The address of the off-chain executor.
                 * @param _extraData Arbitrary data passed by the msg executor.
                 *
                 * @dev Enables the preCrime simulator to mock sending lzReceive() messages,
                 * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
                 */
                function _lzReceiveSimulate(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) internal virtual;
            
                /**
                 * @dev checks if the specified peer is considered 'trusted' by the OApp.
                 * @param _eid The endpoint Id to check.
                 * @param _peer The peer to check.
                 * @return Whether the peer passed is considered 'trusted' by the OApp.
                 */
                function isPeer(uint32 _eid, bytes32 _peer) public view virtual returns (bool);
            }
            
            
            // File @layerzerolabs/onft-evm/contracts/onft721/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.22;
            
            /**
             * @dev Struct representing token parameters for the ONFT send() operation.
             */
            struct SendParam {
                uint32 dstEid; // Destination LayerZero EndpointV2 ID.
                bytes32 to; // Recipient address.
                uint256 tokenId;
                bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
                bytes composeMsg; // The composed message for the send() operation.
                bytes onftCmd; // The ONFT command to be executed, unused in default ONFT implementations.
            }
            
            /**
             * @title IONFT
             * @dev Interface for the ONFT721 token.
             * @dev Does not inherit ERC721 to accommodate usage by OFT721Adapter.
             */
            interface IONFT721 {
                // Custom error messages
                error InvalidReceiver();
                error OnlyNFTOwner(address caller, address owner);
            
                // Events
                event ONFTSent(
                    bytes32 indexed guid, // GUID of the ONFT message.
                    uint32 dstEid, // Destination Endpoint ID.
                    address indexed fromAddress, // Address of the sender on the src chain.
                    uint256 tokenId // ONFT ID sent.
                );
            
                event ONFTReceived(
                    bytes32 indexed guid, // GUID of the ONFT message.
                    uint32 srcEid, // Source Endpoint ID.
                    address indexed toAddress, // Address of the recipient on the dst chain.
                    uint256 tokenId // ONFT ID received.
                );
            
                /**
                 * @notice Retrieves interfaceID and the version of the ONFT.
                 * @return interfaceId The interface ID.
                 * @return version The version.
                 * @dev interfaceId: This specific interface ID is '0x94642228'.
                 * @dev version: Indicates a cross-chain compatible msg encoding with other ONFTs.
                 * @dev If a new feature is added to the ONFT cross-chain msg encoding, the version will be incremented.
                 * ie. localONFT version(x,1) CAN send messages to remoteONFT version(x,1)
                 */
                function onftVersion() external view returns (bytes4 interfaceId, uint64 version);
            
                /**
                 * @notice Retrieves the address of the token associated with the ONFT.
                 * @return token The address of the ERC721 token implementation.
                 */
                function token() external view returns (address);
            
                /**
                 * @notice Indicates whether the ONFT contract requires approval of the 'token()' to send.
                 * @return requiresApproval Needs approval of the underlying token implementation.
                 * @dev Allows things like wallet implementers to determine integration requirements,
                 * without understanding the underlying token implementation.
                 */
                function approvalRequired() external view returns (bool);
            
                /**
                 * @notice Provides a quote for the send() operation.
                 * @param _sendParam The parameters for the send() operation.
                 * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
                 * @return fee The calculated LayerZero messaging fee from the send() operation.
                 * @dev MessagingFee: LayerZero msg fee
                 *  - nativeFee: The native fee.
                 *  - lzTokenFee: The lzToken fee.
                 */
                function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);
            
                /**
                 * @notice Executes the send() operation.
                 * @param _sendParam The parameters for the send operation.
                 * @param _fee The fee information supplied by the caller.
                 *      - nativeFee: The native fee.
                 *      - lzTokenFee: The lzToken fee.
                 * @param _refundAddress The address to receive any excess funds from fees etc. on the src.
                 * @return receipt The LayerZero messaging receipt from the send() operation.
                 * @dev MessagingReceipt: LayerZero msg receipt
                 *  - guid: The unique identifier for the sent message.
                 *  - nonce: The nonce of the sent message.
                 *  - fee: The LayerZero fee incurred for the message.
                 */
                function send(
                    SendParam calldata _sendParam,
                    MessagingFee calldata _fee,
                    address _refundAddress
                ) external payable returns (MessagingReceipt memory);
            }
            
            
            // File @layerzerolabs/oapp-evm/contracts/oapp/interfaces/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.20;
            
            /**
             * @title IOAppMsgInspector
             * @dev Interface for the OApp Message Inspector, allowing examination of message and options contents.
             */
            interface IOAppMsgInspector {
                // Custom error message for inspection failure
                error InspectionFailed(bytes message, bytes options);
            
                /**
                 * @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid.
                 * @param _message The message payload to be inspected.
                 * @param _options Additional options or parameters for inspection.
                 * @return valid A boolean indicating whether the inspection passed (true) or failed (false).
                 *
                 * @dev Optionally done as a revert, OR use the boolean provided to handle the failure.
                 */
                function inspect(bytes calldata _message, bytes calldata _options) external view returns (bool valid);
            }
            
            
            // File @layerzerolabs/onft-evm/contracts/libs/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.22;
            
            /**
             * @title ONFT Composed Message Codec
             * @notice Library for encoding and decoding ONFT composed messages.
             */
            library ONFTComposeMsgCodec {
                // Offset constants for decoding composed messages
                uint8 private constant NONCE_OFFSET = 8;
                uint8 private constant SRC_EID_OFFSET = 12;
                uint8 private constant COMPOSE_FROM_OFFSET = 44;
            
                /**
                 * @dev Encodes a ONFT721 composed message.
                 * @param _nonce The nonce value.
                 * @param _srcEid The source LayerZero endpoint ID.
                 * @param _composeMsg The composed message.
                 * @return The encoded payload, including the composed message.
                 */
                function encode(
                    uint64 _nonce,
                    uint32 _srcEid,
                    bytes memory _composeMsg // 0x[composeFrom][composeMsg]
                ) internal pure returns (bytes memory) {
                    return abi.encodePacked(_nonce, _srcEid, _composeMsg);
                }
            
                /**
                 * @dev Retrieves the nonce for the composed message.
                 * @param _msg The message.
                 * @return The nonce value.
                 */
                function nonce(bytes calldata _msg) internal pure returns (uint64) {
                    return uint64(bytes8(_msg[:NONCE_OFFSET]));
                }
            
                /**
                 * @dev Retrieves the source LayerZero endpoint ID for the composed message.
                 * @param _msg The message.
                 * @return The source LayerZero endpoint ID.
                 */
                function srcEid(bytes calldata _msg) internal pure returns (uint32) {
                    return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));
                }
            
                /**
                 * @dev Retrieves the composeFrom value from the composed message.
                 * @param _msg The message.
                 * @return The composeFrom value as bytes32.
                 */
                function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {
                    return bytes32(_msg[SRC_EID_OFFSET:COMPOSE_FROM_OFFSET]);
                }
            
                /**
                 * @dev Retrieves the composed message.
                 * @param _msg The message.
                 * @return The composed message.
                 */
                function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
                    return _msg[COMPOSE_FROM_OFFSET:];
                }
            
                /**
                 * @dev Converts an address to bytes32.
                 * @param _addr The address to convert.
                 * @return The bytes32 representation of the address.
                 */
                function addressToBytes32(address _addr) internal pure returns (bytes32) {
                    return bytes32(uint256(uint160(_addr)));
                }
            
                /**
                 * @dev Converts bytes32 to an address.
                 * @param _b The bytes32 value to convert.
                 * @return The address representation of bytes32.
                 */
                function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
                    return address(uint160(uint256(_b)));
                }
            }
            
            
            // File @layerzerolabs/onft-evm/contracts/onft721/libs/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.22;
            
            /**
             * @title ONFT721MsgCodec
             * @notice Library for encoding and decoding ONFT721 LayerZero messages.
             */
            library ONFT721MsgCodec {
                uint8 private constant SEND_TO_OFFSET = 32;
                uint8 private constant TOKEN_ID_OFFSET = 64;
            
                /**
                 * @dev Encodes an ONFT721 LayerZero message payload.
                 * @param _sendTo The recipient address.
                 * @param _tokenId The ID of the token to transfer.
                 * @param _composeMsg The composed payload.
                 * @return payload The encoded message payload.
                 * @return hasCompose A boolean indicating whether the message payload contains a composed payload.
                 */
                function encode(
                    bytes32 _sendTo,
                    uint256 _tokenId,
                    bytes memory _composeMsg
                ) internal view returns (bytes memory payload, bool hasCompose) {
                    hasCompose = _composeMsg.length > 0;
                    payload = hasCompose
                        ? abi.encodePacked(_sendTo, _tokenId, addressToBytes32(msg.sender), _composeMsg)
                        : abi.encodePacked(_sendTo, _tokenId);
                }
            
                /**
                 * @dev Decodes sendTo from the ONFT LayerZero message.
                 * @param _msg The message.
                 * @return The recipient address in bytes32 format.
                 */
                function sendTo(bytes calldata _msg) internal pure returns (bytes32) {
                    return bytes32(_msg[:SEND_TO_OFFSET]);
                }
            
                /**
                 * @dev Decodes tokenId from the ONFT LayerZero message.
                 * @param _msg The message.
                 * @return The ID of the tokens to transfer.
                 */
                function tokenId(bytes calldata _msg) internal pure returns (uint256) {
                    return uint256(bytes32(_msg[SEND_TO_OFFSET:TOKEN_ID_OFFSET]));
                }
            
                /**
                 * @dev Decodes whether there is a composed payload.
                 * @param _msg The message.
                 * @return A boolean indicating whether the message has a composed payload.
                 */
                function isComposed(bytes calldata _msg) internal pure returns (bool) {
                    return _msg.length > TOKEN_ID_OFFSET;
                }
            
                /**
                 * @dev Decodes the composed message.
                 * @param _msg The message.
                 * @return The composed message.
                 */
                function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
                    return _msg[TOKEN_ID_OFFSET:];
                }
            
                /**
                 * @dev Converts an address to bytes32.
                 * @param _addr The address to convert.
                 * @return The bytes32 representation of the address.
                 */
                function addressToBytes32(address _addr) internal pure returns (bytes32) {
                    return bytes32(uint256(uint160(_addr)));
                }
            
                /**
                 * @dev Converts bytes32 to an address.
                 * @param _b The bytes32 value to convert.
                 * @return The address representation of bytes32.
                 */
                function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
                    return address(uint160(uint256(_b)));
                }
            }
            
            
            // File @layerzerolabs/onft-evm/contracts/onft721/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.22;
            
            
            
            
            
            
            /**
             * @title ONFT721Core
             * @dev Abstract contract for an ONFT721 token.
             */
            abstract contract ONFT721Core is IONFT721, OApp, OAppPreCrimeSimulator, OAppOptionsType3 {
                using ONFT721MsgCodec for bytes;
                using ONFT721MsgCodec for bytes32;
            
                // @notice Msg types that are used to identify the various OFT operations.
                // @dev This can be extended in child contracts for non-default oft operations
                // @dev These values are used in things like combineOptions() in OAppOptionsType3.sol.
                uint16 public constant SEND = 1;
                uint16 public constant SEND_AND_COMPOSE = 2;
            
                // Address of an optional contract to inspect both 'message' and 'options'
                address public msgInspector;
            
                event MsgInspectorSet(address inspector);
            
                /**
                 * @dev Constructor.
                 * @param _lzEndpoint The address of the LayerZero endpoint.
                 * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
                 */
                constructor(address _lzEndpoint, address _delegate) Ownable(_delegate) OApp(_lzEndpoint, _delegate) {}
            
                /**
                 * @notice Retrieves interfaceID and the version of the ONFT.
                 * @return interfaceId The interface ID (0x23e18da6).
                 * @return version The version.
                 * @dev version: Indicates a cross-chain compatible msg encoding with other ONFTs.
                 * @dev If a new feature is added to the ONFT cross-chain msg encoding, the version will be incremented.
                 * @dev ie. localONFT version(x,1) CAN send messages to remoteONFT version(x,1)
                 */
                function onftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) {
                    return (type(IONFT721).interfaceId, 1);
                }
            
                /**
                 * @notice Sets the message inspector address for the OFT.
                 * @param _msgInspector The address of the message inspector.
                 * @dev This is an optional contract that can be used to inspect both 'message' and 'options'.
                 * @dev Set it to address(0) to disable it, or set it to a contract address to enable it.
                 */
                function setMsgInspector(address _msgInspector) public virtual onlyOwner {
                    msgInspector = _msgInspector;
                    emit MsgInspectorSet(_msgInspector);
                }
            
                function quoteSend(
                    SendParam calldata _sendParam,
                    bool _payInLzToken
                ) external view virtual returns (MessagingFee memory msgFee) {
                    (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam);
                    return _quote(_sendParam.dstEid, message, options, _payInLzToken);
                }
            
                function send(
                    SendParam calldata _sendParam,
                    MessagingFee calldata _fee,
                    address _refundAddress
                ) external payable virtual returns (MessagingReceipt memory msgReceipt) {
                    _debit(msg.sender, _sendParam.tokenId, _sendParam.dstEid);
            
                    (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam);
            
                    // @dev Sends the message to the LayerZero Endpoint, returning the MessagingReceipt.
                    msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress);
                    emit ONFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, _sendParam.tokenId);
                }
            
                /**
                 * @dev Internal function to build the message and options.
                 * @param _sendParam The parameters for the send() operation.
                 * @return message The encoded message.
                 * @return options The encoded options.
                 */
                function _buildMsgAndOptions(
                    SendParam calldata _sendParam
                ) internal view virtual returns (bytes memory message, bytes memory options) {
                    if (_sendParam.to == bytes32(0)) revert InvalidReceiver();
                    bool hasCompose;
                    (message, hasCompose) = ONFT721MsgCodec.encode(_sendParam.to, _sendParam.tokenId, _sendParam.composeMsg);
                    uint16 msgType = hasCompose ? SEND_AND_COMPOSE : SEND;
            
                    options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions);
            
                    // @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector.
                    // @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean
                    address inspector = msgInspector; // caches the msgInspector to avoid potential double storage read
                    if (inspector != address(0)) IOAppMsgInspector(inspector).inspect(message, options);
                }
            
                /**
                 * @dev Internal function to handle the receive on the LayerZero endpoint.
                 * @param _origin The origin information.
                 *  - srcEid: The source chain endpoint ID.
                 *  - sender: The sender address from the src chain.
                 *  - nonce: The nonce of the LayerZero message.
                 * @param _guid The unique identifier for the received LayerZero message.
                 * @param _message The encoded message.
                 * @dev _executor The address of the executor.
                 * @dev _extraData Additional data.
                 */
                function _lzReceive(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address /*_executor*/, // @dev unused in the default implementation.
                    bytes calldata /*_extraData*/ // @dev unused in the default implementation.
                ) internal virtual override {
                    address toAddress = _message.sendTo().bytes32ToAddress();
                    uint256 tokenId = _message.tokenId();
            
                    _credit(toAddress, tokenId, _origin.srcEid);
            
                    if (_message.isComposed()) {
                        bytes memory composeMsg = ONFTComposeMsgCodec.encode(_origin.nonce, _origin.srcEid, _message.composeMsg());
                        // @dev As batching is not implemented, the compose index is always 0.
                        // @dev If batching is added, the index will need to be tracked.
                        endpoint.sendCompose(toAddress, _guid, 0 /* the index of composed message*/, composeMsg);
                    }
            
                    emit ONFTReceived(_guid, _origin.srcEid, toAddress, tokenId);
                }
            
                /*
                 * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
                 * @param _origin The origin information.
                 *  - srcEid: The source chain endpoint ID.
                 *  - sender: The sender address from the src chain.
                 *  - nonce: The nonce of the LayerZero message.
                 * @param _guid The unique identifier for the received LayerZero message.
                 * @param _message The LayerZero message.
                 * @param _executor The address of the off-chain executor.
                 * @param _extraData Arbitrary data passed by the msg executor.
                 * @dev Enables the preCrime simulator to mock sending lzReceive() messages,
                 * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
                 */
                function _lzReceiveSimulate(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) internal virtual override {
                    _lzReceive(_origin, _guid, _message, _executor, _extraData);
                }
            
                /**
                 * @dev Check if the peer is considered 'trusted' by the OApp.
                 * @param _eid The endpoint ID to check.
                 * @param _peer The peer to check.
                 * @return Whether the peer passed is considered 'trusted' by the OApp.
                 * @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source.
                 */
                function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) {
                    return peers[_eid] == _peer;
                }
            
                function _debit(address /*_from*/, uint256 /*_tokenId*/, uint32 /*_dstEid*/) internal virtual;
            
                function _credit(address /*_to*/, uint256 /*_tokenId*/, uint32 /*_srcEid*/) internal virtual;
            }
            
            
            // File @openzeppelin/contracts/token/ERC721/[email protected]
            
            // Original license: SPDX_License_Identifier: MIT
            // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)
            
            pragma solidity ^0.8.20;
            
            /**
             * @dev Required interface of an ERC-721 compliant contract.
             */
            interface IERC721 is IERC165 {
                /**
                 * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
                 */
                event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
            
                /**
                 * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
                 */
                event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
            
                /**
                 * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
                 */
                event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
            
                /**
                 * @dev Returns the number of tokens in ``owner``'s account.
                 */
                function balanceOf(address owner) external view returns (uint256 balance);
            
                /**
                 * @dev Returns the owner of the `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function ownerOf(uint256 tokenId) external view returns (address owner);
            
                /**
                 * @dev Safely transfers `tokenId` token from `from` to `to`.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must exist and be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
                 * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
                 *   a safe transfer.
                 *
                 * Emits a {Transfer} event.
                 */
                function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
            
                /**
                 * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
                 * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must exist and be owned by `from`.
                 * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
                 *   {setApprovalForAll}.
                 * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
                 *   a safe transfer.
                 *
                 * Emits a {Transfer} event.
                 */
                function safeTransferFrom(address from, address to, uint256 tokenId) external;
            
                /**
                 * @dev Transfers `tokenId` token from `from` to `to`.
                 *
                 * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
                 * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
                 * understand this adds an external call which potentially creates a reentrancy vulnerability.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(address from, address to, uint256 tokenId) external;
            
                /**
                 * @dev Gives permission to `to` to transfer `tokenId` token to another account.
                 * The approval is cleared when the token is transferred.
                 *
                 * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
                 *
                 * Requirements:
                 *
                 * - The caller must own the token or be an approved operator.
                 * - `tokenId` must exist.
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address to, uint256 tokenId) external;
            
                /**
                 * @dev Approve or remove `operator` as an operator for the caller.
                 * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
                 *
                 * Requirements:
                 *
                 * - The `operator` cannot be the address zero.
                 *
                 * Emits an {ApprovalForAll} event.
                 */
                function setApprovalForAll(address operator, bool approved) external;
            
                /**
                 * @dev Returns the account approved for `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function getApproved(uint256 tokenId) external view returns (address operator);
            
                /**
                 * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
                 *
                 * See {setApprovalForAll}
                 */
                function isApprovedForAll(address owner, address operator) external view returns (bool);
            }
            
            
            // File @pythnetwork/pyth-sdk-solidity/[email protected]
            
            // Original license: SPDX_License_Identifier: Apache-2.0
            pragma solidity ^0.8.0;
            
            /// @title IPythEvents contains the events that Pyth contract emits.
            /// @dev This interface can be used for listening to the updates for off-chain and testing purposes.
            interface IPythEvents {
                /// @dev Emitted when the price feed with `id` has received a fresh update.
                /// @param id The Pyth Price Feed ID.
                /// @param publishTime Publish time of the given price update.
                /// @param price Price of the given price update.
                /// @param conf Confidence interval of the given price update.
                event PriceFeedUpdate(
                    bytes32 indexed id,
                    uint64 publishTime,
                    int64 price,
                    uint64 conf
                );
            }
            
            
            // File @pythnetwork/pyth-sdk-solidity/[email protected]
            
            // Original license: SPDX_License_Identifier: Apache-2.0
            pragma solidity ^0.8.0;
            
            contract PythStructs {
                // A price with a degree of uncertainty, represented as a price +- a confidence interval.
                //
                // The confidence interval roughly corresponds to the standard error of a normal distribution.
                // Both the price and confidence are stored in a fixed-point numeric representation,
                // `x * (10^expo)`, where `expo` is the exponent.
                //
                // Please refer to the documentation at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how
                // to how this price safely.
                struct Price {
                    // Price
                    int64 price;
                    // Confidence interval around the price
                    uint64 conf;
                    // Price exponent
                    int32 expo;
                    // Unix timestamp describing when the price was published
                    uint publishTime;
                }
            
                // PriceFeed represents a current aggregate price from pyth publisher feeds.
                struct PriceFeed {
                    // The price ID.
                    bytes32 id;
                    // Latest available price
                    Price price;
                    // Latest available exponentially-weighted moving average price
                    Price emaPrice;
                }
            }
            
            
            // File @pythnetwork/pyth-sdk-solidity/[email protected]
            
            // Original license: SPDX_License_Identifier: Apache-2.0
            pragma solidity ^0.8.0;
            
            
            /// @title Consume prices from the Pyth Network (https://pyth.network/).
            /// @dev Please refer to the guidance at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how to consume prices safely.
            /// @author Pyth Data Association
            interface IPyth is IPythEvents {
                /// @notice Returns the price of a price feed without any sanity checks.
                /// @dev This function returns the most recent price update in this contract without any recency checks.
                /// This function is unsafe as the returned price update may be arbitrarily far in the past.
                ///
                /// Users of this function should check the `publishTime` in the price to ensure that the returned price is
                /// sufficiently recent for their application. If you are considering using this function, it may be
                /// safer / easier to use `getPriceNoOlderThan`.
                /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
                function getPriceUnsafe(
                    bytes32 id
                ) external view returns (PythStructs.Price memory price);
            
                /// @notice Returns the price that is no older than `age` seconds of the current time.
                /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in
                /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
                /// recently.
                /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
                function getPriceNoOlderThan(
                    bytes32 id,
                    uint age
                ) external view returns (PythStructs.Price memory price);
            
                /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.
                /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.
                /// However, if the price is not recent this function returns the latest available price.
                ///
                /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that
                /// the returned price is recent or useful for any particular application.
                ///
                /// Users of this function should check the `publishTime` in the price to ensure that the returned price is
                /// sufficiently recent for their application. If you are considering using this function, it may be
                /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.
                /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
                function getEmaPriceUnsafe(
                    bytes32 id
                ) external view returns (PythStructs.Price memory price);
            
                /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds
                /// of the current time.
                /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in
                /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
                /// recently.
                /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
                function getEmaPriceNoOlderThan(
                    bytes32 id,
                    uint age
                ) external view returns (PythStructs.Price memory price);
            
                /// @notice Update price feeds with given update messages.
                /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
                /// `getUpdateFee` with the length of the `updateData` array.
                /// Prices will be updated if they are more recent than the current stored prices.
                /// The call will succeed even if the update is not the most recent.
                /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.
                /// @param updateData Array of price update data.
                function updatePriceFeeds(bytes[] calldata updateData) external payable;
            
                /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is
                /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the
                /// given `publishTimes` for the price feeds and does not read the actual price update publish time within `updateData`.
                ///
                /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
                /// `getUpdateFee` with the length of the `updateData` array.
                ///
                /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime
                /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have
                /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.
                /// Otherwise, it calls updatePriceFeeds method to update the prices.
                ///
                /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.
                /// @param updateData Array of price update data.
                /// @param priceIds Array of price ids.
                /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`
                function updatePriceFeedsIfNecessary(
                    bytes[] calldata updateData,
                    bytes32[] calldata priceIds,
                    uint64[] calldata publishTimes
                ) external payable;
            
                /// @notice Returns the required fee to update an array of price updates.
                /// @param updateData Array of price update data.
                /// @return feeAmount The required fee in Wei.
                function getUpdateFee(
                    bytes[] calldata updateData
                ) external view returns (uint feeAmount);
            
                /// @notice Parse `updateData` and return price feeds of the given `priceIds` if they are all published
                /// within `minPublishTime` and `maxPublishTime`.
                ///
                /// You can use this method if you want to use a Pyth price at a fixed time and not the most recent price;
                /// otherwise, please consider using `updatePriceFeeds`. This method may store the price updates on-chain, if they
                /// are more recent than the current stored prices.
                ///
                /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
                /// `getUpdateFee` with the length of the `updateData` array.
                ///
                ///
                /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is
                /// no update for any of the given `priceIds` within the given time range.
                /// @param updateData Array of price update data.
                /// @param priceIds Array of price ids.
                /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`.
                /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`.
                /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order).
                function parsePriceFeedUpdates(
                    bytes[] calldata updateData,
                    bytes32[] calldata priceIds,
                    uint64 minPublishTime,
                    uint64 maxPublishTime
                ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds);
            
                /// @notice Similar to `parsePriceFeedUpdates` but ensures the updates returned are
                /// the first updates published in minPublishTime. That is, if there are multiple updates for a given timestamp,
                /// this method will return the first update. This method may store the price updates on-chain, if they
                /// are more recent than the current stored prices.
                ///
                ///
                /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is
                /// no update for any of the given `priceIds` within the given time range and uniqueness condition.
                /// @param updateData Array of price update data.
                /// @param priceIds Array of price ids.
                /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`.
                /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`.
                /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order).
                function parsePriceFeedUpdatesUnique(
                    bytes[] calldata updateData,
                    bytes32[] calldata priceIds,
                    uint64 minPublishTime,
                    uint64 maxPublishTime
                ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds);
            }
            
            
            // File contracts/main-contracts/KingdomlyFeeContract.sol
            
            // Original license: SPDX_License_Identifier: UNLICENSED
            pragma solidity ^0.8.24;
            
            
            error InsufficientUpdateFee(uint256 requiredFee);
            error ContractNotVerified(address contractAddress);
            
            contract KingdomlyFeeContract is Ownable {
                uint256 private cachedOneDollarInWei;
                uint256 private maxPriceAgeInSeconds;
            
                IPyth pyth;
                bytes32 ethUsdPriceId;
            
                constructor(address _pyth, bytes32 _ethUsdPriceId) Ownable(msg.sender) {
                    pyth = IPyth(_pyth);
                    ethUsdPriceId = _ethUsdPriceId;
                    maxPriceAgeInSeconds = 60 * 60 * 24;
                }
            
                function getOneDollarInWei() public view returns (uint256) {
                    try pyth.getPriceNoOlderThan(ethUsdPriceId, maxPriceAgeInSeconds) returns (PythStructs.Price memory price) {
                        uint256 ethPrice18Decimals =
                            (uint256(uint64(price.price)) * (10 ** 18)) / (10 ** uint8(uint32(-1 * price.expo)));
                        uint256 oneDollarInWei = ((10 ** 18) * (10 ** 18)) / ethPrice18Decimals;
            
                        return oneDollarInWei;
                    } catch {
                        return cachedOneDollarInWei;
                    }
                }
            
                function updateOracleAndGetOneDollarInWei(bytes[] calldata pythPriceUpdate) public payable returns (uint256) {
                    uint256 updateFee = pyth.getUpdateFee(pythPriceUpdate);
            
                    if (msg.value != updateFee) {
                        revert InsufficientUpdateFee(updateFee);
                    }
            
                    pyth.updatePriceFeeds{value: msg.value}(pythPriceUpdate);
            
                    cachedOneDollarInWei = getOneDollarInWei();
            
                    return cachedOneDollarInWei;
                }
            
                function updateMaxPriceAgeInSeconds(uint256 _maxPriceAgeInSeconds) public onlyOwner {
                    maxPriceAgeInSeconds = _maxPriceAgeInSeconds;
                }
            }
            
            
            // File contracts/utils/ONFT721Adapter.sol
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.22;
            
            /**
             * @title ONFT721Adapter Contract
             * @dev ONFT721Adapter is a wrapper used to enable cross-chain transferring of an existing ERC721 token.
             * @dev ERC721 NFTs from extensions which revert certain transactions, such as ones from blocked wallets or soulbound
             * @dev tokens, may still be bridgeable.
             */
            abstract contract ONFT721Adapter is ONFT721Core {
                IERC721 internal immutable innerToken;
            
                /**
                 * @dev Constructor for the ONFT721 contract.
                 * @param _token The underlying ERC721 token address this adapts
                 * @param _lzEndpoint The LayerZero endpoint address.
                 * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
                 */
                constructor(address _token, address _lzEndpoint, address _delegate) ONFT721Core(_lzEndpoint, _delegate) {
                    innerToken = IERC721(_token);
                }
            
                /**
                 * @notice Retrieves the address of the underlying ERC721 implementation (ie. external contract).
                 */
                function token() external view returns (address) {
                    return address(innerToken);
                }
            
                /**
                 * @notice Indicates whether the ONFT721 contract requires approval of the 'token()' to send.
                 * @dev In the case of ONFT where the contract IS the token, approval is NOT required.
                 * @return requiresApproval Needs approval of the underlying token implementation.
                 */
                function approvalRequired() external pure virtual returns (bool) {
                    return true;
                }
            
                function _debit(address _from, uint256 _tokenId, uint32 /*_dstEid*/ ) internal virtual override {
                    // @dev Dont need to check onERC721Received() when moving into this contract, ie. no 'safeTransferFrom' required
                    innerToken.transferFrom(_from, address(this), _tokenId);
                }
            
                function _credit(address _toAddress, uint256 _tokenId, uint32 /*_srcEid*/ ) internal virtual override {
                    // @dev Do not need to check onERC721Received() when moving out of this contract, ie. no 'safeTransferFrom'
                    // required
                    // @dev The default implementation does not implement IERC721Receiver as 'safeTransferFrom' is not used.
                    // @dev If IERC721Receiver is required, ensure proper re-entrancy protection is implemented.
                    innerToken.transferFrom(address(this), _toAddress, _tokenId);
                }
            }
            
            
            // File contracts/main-contracts/Sproto_Gremlins_Proxy.sol
            
            // Original license: SPDX_License_Identifier: MIT
            
            pragma solidity ^0.8.22;
            
            
            
            
            
            contract Sproto_Gremlins_Proxy is ONFT721Adapter {
                // ########## EVENTS ##########
                event KingdomlyFeeContractChanged(address feeContractAddress);
            
                // ########## ERRORS ##########
            
                error UnauthorizedAccess();
                error MaxBatchSendSizeExceeded(uint256 maxBatchSendSize);
                error InvalidBatchSendSize(uint256 batchSendSize);
                error InsufficientBatchSendFee();
                error InvalidKingdomlyFeeContract();
            
                //Bridge variables
                KingdomlyFeeContract public kingdomlyFeeContract;
                address public kingdomlyAdmin;
                address public feeCollectionAddress;
            
                uint256 public immutable bridgeFeeInCents;
            
                /**
                 * @dev Constructor for the ONFT721 contract.
                 * @param _token The underlying ERC721 token address this adapts
                 * @param _lzEndpoint The LayerZero endpoint address.
                 * @param _kingdomlyAdmin The admin address for Kingdomly.
                 * @param _feeCollectionAddress The address for the fee collection.
                 * @param _kingdomlyFeeContract The Contract for Kingdomly Fees.
                 */
                constructor(
                    address _token,
                    address _lzEndpoint,
                    address _kingdomlyAdmin,
                    address _feeCollectionAddress,
                    KingdomlyFeeContract _kingdomlyFeeContract
                ) ONFT721Adapter(_token, _lzEndpoint, msg.sender) {
                    //Bridge variables
                    kingdomlyAdmin = _kingdomlyAdmin;
                    kingdomlyFeeContract = _kingdomlyFeeContract;
                    feeCollectionAddress = _feeCollectionAddress;
            
                    bridgeFeeInCents = 200; // $2 * 100 = 200
                }
            
                // ###################### Modifiers ######################
            
                /**
                 * @dev Ensures the caller is the Kingdomly Admin.
                 */
                modifier isKingdomlyAdmin() {
                    if (msg.sender != kingdomlyAdmin) {
                        revert UnauthorizedAccess();
                    }
            
                    _;
                }
            
                //===================================START Bridge Functions===================================//
            
                function quoteSend(SendParam calldata _sendParam, bool _payInLzToken)
                    public
                    view
                    override
                    returns (MessagingFee memory msgFee)
                {
                    (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam);
            
                    MessagingFee memory _lzFee = _quote(_sendParam.dstEid, message, options, _payInLzToken);
            
                    uint256 bridgeNativeFee = getBridgeNativeFee();
            
                    return MessagingFee({nativeFee: _lzFee.nativeFee + bridgeNativeFee, lzTokenFee: _lzFee.lzTokenFee});
                }
            
                function send(SendParam calldata _sendParam, MessagingFee calldata _fee, address _refundAddress)
                    external
                    payable
                    override
                    returns (MessagingReceipt memory msgReceipt)
                {
                    _debit(msg.sender, _sendParam.tokenId, _sendParam.dstEid);
            
                    (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam);
            
                    // @dev Sends the message to the LayerZero Endpoint, returning the MessagingReceipt.
                    msgReceipt = _lzSend(
                        _sendParam.dstEid,
                        message,
                        options,
                        _fee,
                        feeCollectionAddress // feeCollectionAddress becomes the refund Address
                    );
                    emit ONFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, _sendParam.tokenId);
                }
            
                function _lzSendBatch(
                    uint32 _dstEid,
                    bytes memory _message,
                    bytes memory _options,
                    MessagingFee memory _fee,
                    address _refundAddress
                ) internal virtual returns (MessagingReceipt memory receipt) {
                    // @dev We remove the _payNative check because the main check is already done in the batchSend function.
                    uint256 messageValue = _fee.nativeFee;
                    if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);
            
                    return endpoint.send{value: messageValue}(
                        // solhint-disable-next-line check-send-result
                        MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),
                        _refundAddress
                    );
                }
            
                function quoteBatchSend(SendParam[] calldata _sendParams, bool _payInLzToken)
                    public
                    view
                    returns (MessagingFee memory totalBatchMsgFee, MessagingFee[] memory msgFees)
                {
                    if (_sendParams.length > 300) revert MaxBatchSendSizeExceeded(300);
                    if (_sendParams.length == 0) revert InvalidBatchSendSize(0);
            
                    uint256 totalNativeFee = 0;
                    uint256 totalLzTokenFee = 0;
            
                    MessagingFee[] memory _msgFees = new MessagingFee[](_sendParams.length);
            
                    for (uint256 i = 0; i < _sendParams.length;) {
                        MessagingFee memory fees = quoteSend(_sendParams[i], _payInLzToken);
                        totalNativeFee += fees.nativeFee;
                        totalLzTokenFee += fees.lzTokenFee;
                        _msgFees[i] = fees;
                        unchecked {
                            i++;
                        }
                    }
                    return (MessagingFee({nativeFee: totalNativeFee, lzTokenFee: totalLzTokenFee}), _msgFees);
                }
            
                function batchSend(
                    SendParam[] calldata _sendParams,
                    MessagingFee calldata _fee,
                    address _refundAddress,
                    bool _payInLzToken
                ) external payable {
                    uint256 sendParamsLength = _sendParams.length;
            
                    if (sendParamsLength > 100) revert MaxBatchSendSizeExceeded(100);
                    if (sendParamsLength == 0) revert InvalidBatchSendSize(0);
            
                    (MessagingFee memory totalBatchMsgFee, MessagingFee[] memory msgFees) =
                        quoteBatchSend(_sendParams, _payInLzToken);
            
                    if (_fee.nativeFee != totalBatchMsgFee.nativeFee || _fee.lzTokenFee != totalBatchMsgFee.lzTokenFee) {
                        revert InsufficientBatchSendFee();
                    }
            
                    if (msg.value != totalBatchMsgFee.nativeFee) {
                        revert InsufficientBatchSendFee();
                    }
            
                    for (uint256 i = 0; i < sendParamsLength; i++) {
                        _debit(msg.sender, _sendParams[i].tokenId, _sendParams[i].dstEid);
            
                        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParams[i]);
            
                        // @dev Sends the message to the LayerZero Endpoint, returning the MessagingReceipt.
                        MessagingReceipt memory msgReceipt = _lzSendBatch(
                            _sendParams[i].dstEid,
                            message,
                            options,
                            msgFees[i],
                            feeCollectionAddress // feeCollectionAddress becomes the refund Address
                        );
            
                        emit ONFTSent(msgReceipt.guid, _sendParams[i].dstEid, msg.sender, _sendParams[i].tokenId);
                    }
                }
            
                function hasPeer(uint32 _eid) public view returns (bool) {
                    bytes32 peer = peers[_eid];
                    if (peer == bytes32(0)) return false;
            
                    return true;
                }
            
                //===================================END Bridge Functions===================================//
            
                // ###################### Kingdomly Admin Functions ######################
            
                function setNewKingdomlyFeeContract(KingdomlyFeeContract _kingdomlyFeeContract) external isKingdomlyAdmin {
                    if (address(_kingdomlyFeeContract) == address(0)) {
                        revert InvalidKingdomlyFeeContract();
                    }
            
                    kingdomlyFeeContract = _kingdomlyFeeContract;
            
                    emit KingdomlyFeeContractChanged(address(_kingdomlyFeeContract));
                }
            
                function getKingdomlyFeeContract() external view returns (KingdomlyFeeContract) {
                    return kingdomlyFeeContract;
                }
            
                // ###################### Fee Functions ######################
            
                function getOneDollarInWei() internal view returns (uint256) {
                    return kingdomlyFeeContract.getOneDollarInWei();
                }
            
                function getBridgeNativeFee() public view returns (uint256) {
                    return (getOneDollarInWei() * bridgeFeeInCents) / 100;
                }
            }

            File 4 of 5: EndpointV2
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
            pragma solidity ^0.8.0;
            import "../utils/Context.sol";
            /**
             * @dev Contract module which provides a basic access control mechanism, where
             * there is an account (an owner) that can be granted exclusive access to
             * specific functions.
             *
             * By default, the owner account will be the one that deploys the contract. This
             * can later be changed with {transferOwnership}.
             *
             * This module is used through inheritance. It will make available the modifier
             * `onlyOwner`, which can be applied to your functions to restrict their use to
             * the owner.
             */
            abstract contract Ownable is Context {
                address private _owner;
                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                /**
                 * @dev Initializes the contract setting the deployer as the initial owner.
                 */
                constructor() {
                    _transferOwnership(_msgSender());
                }
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                    _checkOwner();
                    _;
                }
                /**
                 * @dev Returns the address of the current owner.
                 */
                function owner() public view virtual returns (address) {
                    return _owner;
                }
                /**
                 * @dev Throws if the sender is not the owner.
                 */
                function _checkOwner() internal view virtual {
                    require(owner() == _msgSender(), "Ownable: caller is not the owner");
                }
                /**
                 * @dev Leaves the contract without owner. It will not be possible to call
                 * `onlyOwner` functions. Can only be called by the current owner.
                 *
                 * NOTE: Renouncing ownership will leave the contract without an owner,
                 * thereby disabling any functionality that is only available to the owner.
                 */
                function renounceOwnership() public virtual onlyOwner {
                    _transferOwnership(address(0));
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Can only be called by the current owner.
                 */
                function transferOwnership(address newOwner) public virtual onlyOwner {
                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                    _transferOwnership(newOwner);
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Internal function without access restriction.
                 */
                function _transferOwnership(address newOwner) internal virtual {
                    address oldOwner = _owner;
                    _owner = newOwner;
                    emit OwnershipTransferred(oldOwner, newOwner);
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            interface IERC20 {
                /**
                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                 * another (`to`).
                 *
                 * Note that `value` may be zero.
                 */
                event Transfer(address indexed from, address indexed to, uint256 value);
                /**
                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                 * a call to {approve}. `value` is the new allowance.
                 */
                event Approval(address indexed owner, address indexed spender, uint256 value);
                /**
                 * @dev Returns the amount of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
                /**
                 * @dev Returns the amount of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
                /**
                 * @dev Moves `amount` tokens from the caller's account to `to`.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transfer(address to, uint256 amount) external returns (bool);
                /**
                 * @dev Returns the remaining number of tokens that `spender` will be
                 * allowed to spend on behalf of `owner` through {transferFrom}. This is
                 * zero by default.
                 *
                 * This value changes when {approve} or {transferFrom} are called.
                 */
                function allowance(address owner, address spender) external view returns (uint256);
                /**
                 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * IMPORTANT: Beware that changing an allowance with this method brings the risk
                 * that someone may use both the old and the new allowance by unfortunate
                 * transaction ordering. One possible solution to mitigate this race
                 * condition is to first reduce the spender's allowance to 0 and set the
                 * desired value afterwards:
                 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address spender, uint256 amount) external returns (bool);
                /**
                 * @dev Moves `amount` tokens from `from` to `to` using the
                 * allowance mechanism. `amount` is then deducted from the caller's
                 * allowance.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(address from, address to, uint256 amount) external returns (bool);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
             * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
             *
             * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
             * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
             * need to send a transaction, and thus is not required to hold Ether at all.
             *
             * ==== Security Considerations
             *
             * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
             * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
             * considered as an intention to spend the allowance in any specific way. The second is that because permits have
             * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
             * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
             * generally recommended is:
             *
             * ```solidity
             * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
             *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
             *     doThing(..., value);
             * }
             *
             * function doThing(..., uint256 value) public {
             *     token.safeTransferFrom(msg.sender, address(this), value);
             *     ...
             * }
             * ```
             *
             * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
             * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
             * {SafeERC20-safeTransferFrom}).
             *
             * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
             * contracts should have entry points that don't rely on permit.
             */
            interface IERC20Permit {
                /**
                 * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                 * given ``owner``'s signed approval.
                 *
                 * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                 * ordering also apply here.
                 *
                 * Emits an {Approval} event.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 * - `deadline` must be a timestamp in the future.
                 * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                 * over the EIP712-formatted function arguments.
                 * - the signature must use ``owner``'s current nonce (see {nonces}).
                 *
                 * For more information on the signature format, see the
                 * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                 * section].
                 *
                 * CAUTION: See Security Considerations above.
                 */
                function permit(
                    address owner,
                    address spender,
                    uint256 value,
                    uint256 deadline,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) external;
                /**
                 * @dev Returns the current nonce for `owner`. This value must be
                 * included whenever a signature is generated for {permit}.
                 *
                 * Every successful call to {permit} increases ``owner``'s nonce by one. This
                 * prevents a signature from being used multiple times.
                 */
                function nonces(address owner) external view returns (uint256);
                /**
                 * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                 */
                // solhint-disable-next-line func-name-mixedcase
                function DOMAIN_SEPARATOR() external view returns (bytes32);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
            pragma solidity ^0.8.0;
            import "../IERC20.sol";
            import "../extensions/IERC20Permit.sol";
            import "../../../utils/Address.sol";
            /**
             * @title SafeERC20
             * @dev Wrappers around ERC20 operations that throw on failure (when the token
             * contract returns false). Tokens that return no value (and instead revert or
             * throw on failure) are also supported, non-reverting calls are assumed to be
             * successful.
             * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
             * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
             */
            library SafeERC20 {
                using Address for address;
                /**
                 * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
                 * non-reverting calls are assumed to be successful.
                 */
                function safeTransfer(IERC20 token, address to, uint256 value) internal {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                }
                /**
                 * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
                 * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
                 */
                function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                }
                /**
                 * @dev Deprecated. This function has issues similar to the ones found in
                 * {IERC20-approve}, and its usage is discouraged.
                 *
                 * Whenever possible, use {safeIncreaseAllowance} and
                 * {safeDecreaseAllowance} instead.
                 */
                function safeApprove(IERC20 token, address spender, uint256 value) internal {
                    // safeApprove should only be called when setting an initial allowance,
                    // or when resetting it to zero. To increase and decrease it, use
                    // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                    require(
                        (value == 0) || (token.allowance(address(this), spender) == 0),
                        "SafeERC20: approve from non-zero to non-zero allowance"
                    );
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                }
                /**
                 * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                 * non-reverting calls are assumed to be successful.
                 */
                function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                    uint256 oldAllowance = token.allowance(address(this), spender);
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
                }
                /**
                 * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                 * non-reverting calls are assumed to be successful.
                 */
                function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                    unchecked {
                        uint256 oldAllowance = token.allowance(address(this), spender);
                        require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                    }
                }
                /**
                 * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
                 * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
                 * to be set to zero before setting it to a non-zero value, such as USDT.
                 */
                function forceApprove(IERC20 token, address spender, uint256 value) internal {
                    bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                    if (!_callOptionalReturnBool(token, approvalCall)) {
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                        _callOptionalReturn(token, approvalCall);
                    }
                }
                /**
                 * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
                 * Revert on invalid signature.
                 */
                function safePermit(
                    IERC20Permit token,
                    address owner,
                    address spender,
                    uint256 value,
                    uint256 deadline,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) internal {
                    uint256 nonceBefore = token.nonces(owner);
                    token.permit(owner, spender, value, deadline, v, r, s);
                    uint256 nonceAfter = token.nonces(owner);
                    require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                }
                /**
                 * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                 * on the return value: the return value is optional (but if data is returned, it must not be false).
                 * @param token The token targeted by the call.
                 * @param data The call data (encoded using abi.encode or one of its variants).
                 */
                function _callOptionalReturn(IERC20 token, bytes memory data) private {
                    // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                    // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                    // the target address contains contract code and also asserts for success in the low-level call.
                    bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                    require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                }
                /**
                 * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                 * on the return value: the return value is optional (but if data is returned, it must not be false).
                 * @param token The token targeted by the call.
                 * @param data The call data (encoded using abi.encode or one of its variants).
                 *
                 * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
                 */
                function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                    // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                    // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                    // and not revert is the subcall reverts.
                    (bool success, bytes memory returndata) = address(token).call(data);
                    return
                        success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
            pragma solidity ^0.8.1;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 *
                 * Furthermore, `isContract` will also return true if the target contract within
                 * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
                 * which only has an effect at the end of a transaction.
                 * ====
                 *
                 * [IMPORTANT]
                 * ====
                 * You shouldn't rely on `isContract` to protect against flash loan attacks!
                 *
                 * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                 * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                 * constructor.
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize/address.code.length, which returns 0
                    // for contracts in construction, since the code is only stored at the end
                    // of the constructor execution.
                    return account.code.length > 0;
                }
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    (bool success, ) = recipient.call{value: amount}("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
                /**
                 * @dev Performs a Solidity function call using a low level `call`. A
                 * plain `call` is an unsafe replacement for a function call: use this
                 * function instead.
                 *
                 * If `target` reverts with a revert reason, it is bubbled up by this
                 * function (like regular Solidity function calls).
                 *
                 * Returns the raw returned data. To convert to the expected return value,
                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                 *
                 * Requirements:
                 *
                 * - `target` must be a contract.
                 * - calling `target` with `data` must not revert.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                 * `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but also transferring `value` wei to `target`.
                 *
                 * Requirements:
                 *
                 * - the calling contract must have an ETH balance of at least `value`.
                 * - the called Solidity function must be `payable`.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(address(this).balance >= value, "Address: insufficient balance for call");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    return functionStaticCall(target, data, "Address: low-level static call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                 * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                 *
                 * _Available since v4.8._
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    if (success) {
                        if (returndata.length == 0) {
                            // only check isContract if the call was successful and the return data is empty
                            // otherwise we already know that it was a contract
                            require(isContract(target), "Address: call to non-contract");
                        }
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason or using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                function _revert(bytes memory returndata, string memory errorMessage) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Provides information about the current execution context, including the
             * sender of the transaction and its data. While these are generally available
             * via msg.sender and msg.data, they should not be accessed in such a direct
             * manner, since when dealing with meta-transactions the account sending and
             * paying for execution may not be the actual sender (as far as an application
             * is concerned).
             *
             * This contract is only required for intermediate, library-like contracts.
             */
            abstract contract Context {
                function _msgSender() internal view virtual returns (address) {
                    return msg.sender;
                }
                function _msgData() internal view virtual returns (bytes calldata) {
                    return msg.data;
                }
                function _contextSuffixLength() internal view virtual returns (uint256) {
                    return 0;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
            pragma solidity ^0.8.0;
            import "./IERC165.sol";
            /**
             * @dev Implementation of the {IERC165} interface.
             *
             * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
             * for the additional interface id that will be supported. For example:
             *
             * ```solidity
             * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
             *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
             * }
             * ```
             *
             * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
             */
            abstract contract ERC165 is IERC165 {
                /**
                 * @dev See {IERC165-supportsInterface}.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                    return interfaceId == type(IERC165).interfaceId;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC165 standard, as defined in the
             * https://eips.ethereum.org/EIPS/eip-165[EIP].
             *
             * Implementers can declare support of contract interfaces, which can then be
             * queried by others ({ERC165Checker}).
             *
             * For an implementation, see {ERC165}.
             */
            interface IERC165 {
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30 000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) external view returns (bool);
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import { MessagingFee, MessagingParams, MessagingReceipt, Origin, ILayerZeroEndpointV2 } from "./interfaces/ILayerZeroEndpointV2.sol";
            import { ISendLib, Packet } from "./interfaces/ISendLib.sol";
            import { ILayerZeroReceiver } from "./interfaces/ILayerZeroReceiver.sol";
            import { Errors } from "./libs/Errors.sol";
            import { GUID } from "./libs/GUID.sol";
            import { Transfer } from "./libs/Transfer.sol";
            import { MessagingChannel } from "./MessagingChannel.sol";
            import { MessagingComposer } from "./MessagingComposer.sol";
            import { MessageLibManager } from "./MessageLibManager.sol";
            import { MessagingContext } from "./MessagingContext.sol";
            // LayerZero EndpointV2 is fully backward compatible with LayerZero Endpoint(V1), but it also supports additional
            // features that Endpoint(V1) does not support now and may not in the future. We have also changed some terminology
            // to clarify pre-existing language that might have been confusing.
            //
            // The following is a list of terminology changes:
            //     -chainId -> eid
            //          - Rationale: chainId was a term we initially used to describe an endpoint on a specific chain. Since
            //          LayerZero supports non-EVMs we could not map the classic EVM chainIds to the LayerZero chainIds, making it
            //          confusing for developers. With the addition of EndpointV2 and its backward compatible nature, we would have
            //          two chainIds per chain that has Endpoint(V1), further confusing developers. We have decided to change the
            //          name to Endpoint Id, or eid, for simplicity and clarity.
            //     -adapterParams -> options
            //     -userApplication -> oapp. Omnichain Application
            //     -srcAddress -> sender
            //     -dstAddress -> receiver
            //          - Rationale: The sender/receiver on EVM is the address. However, on non-EVM chains, the sender/receiver could
            //          represented as a public key, or some other identifier. The term sender/receiver is more generic
            //     -payload -> message.
            //          - Rationale: The term payload is used in the context of a packet, which is a combination of the message and GUID
            contract EndpointV2 is ILayerZeroEndpointV2, MessagingChannel, MessageLibManager, MessagingComposer, MessagingContext {
                address public lzToken;
                mapping(address oapp => address delegate) public delegates;
                /// @param _eid the unique Endpoint Id for this deploy that all other Endpoints can use to send to it
                constructor(uint32 _eid, address _owner) MessagingChannel(_eid) {
                    _transferOwnership(_owner);
                }
                /// @dev MESSAGING STEP 0
                /// @notice This view function gives the application built on top of LayerZero the ability to requests a quote
                /// with the same parameters as they would to send their message. Since the quotes are given on chain there is a
                /// race condition in which the prices could change between the time the user gets their quote and the time they
                /// submit their message. If the price moves up and the user doesn't send enough funds the transaction will revert,
                /// if the price goes down the _refundAddress provided by the app will be refunded the difference.
                /// @param _params the messaging parameters
                /// @param _sender the sender of the message
                function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory) {
                    // lzToken must be set to support payInLzToken
                    if (_params.payInLzToken && lzToken == address(0x0)) revert Errors.LZ_LzTokenUnavailable();
                    // get the correct outbound nonce
                    uint64 nonce = outboundNonce[_sender][_params.dstEid][_params.receiver] + 1;
                    // construct the packet with a GUID
                    Packet memory packet = Packet({
                        nonce: nonce,
                        srcEid: eid,
                        sender: _sender,
                        dstEid: _params.dstEid,
                        receiver: _params.receiver,
                        guid: GUID.generate(nonce, eid, _sender, _params.dstEid, _params.receiver),
                        message: _params.message
                    });
                    // get the send library by sender and dst eid
                    // use _ to avoid variable shadowing
                    address _sendLibrary = getSendLibrary(_sender, _params.dstEid);
                    return ISendLib(_sendLibrary).quote(packet, _params.options, _params.payInLzToken);
                }
                /// @dev MESSAGING STEP 1 - OApp need to transfer the fees to the endpoint before sending the message
                /// @param _params the messaging parameters
                /// @param _refundAddress the address to refund both the native and lzToken
                function send(
                    MessagingParams calldata _params,
                    address _refundAddress
                ) external payable sendContext(_params.dstEid, msg.sender) returns (MessagingReceipt memory) {
                    if (_params.payInLzToken && lzToken == address(0x0)) revert Errors.LZ_LzTokenUnavailable();
                    // send message
                    (MessagingReceipt memory receipt, address _sendLibrary) = _send(msg.sender, _params);
                    // OApp can simulate with 0 native value it will fail with error including the required fee, which can be provided in the actual call
                    // this trick can be used to avoid the need to write the quote() function
                    // however, without the quote view function it will be hard to compose an oapp on chain
                    uint256 suppliedNative = _suppliedNative();
                    uint256 suppliedLzToken = _suppliedLzToken(_params.payInLzToken);
                    _assertMessagingFee(receipt.fee, suppliedNative, suppliedLzToken);
                    // handle lz token fees
                    _payToken(lzToken, receipt.fee.lzTokenFee, suppliedLzToken, _sendLibrary, _refundAddress);
                    // handle native fees
                    _payNative(receipt.fee.nativeFee, suppliedNative, _sendLibrary, _refundAddress);
                    return receipt;
                }
                /// @dev internal function for sending the messages used by all external send methods
                /// @param _sender the address of the application sending the message to the destination chain
                /// @param _params the messaging parameters
                function _send(
                    address _sender,
                    MessagingParams calldata _params
                ) internal returns (MessagingReceipt memory, address) {
                    // get the correct outbound nonce
                    uint64 latestNonce = _outbound(_sender, _params.dstEid, _params.receiver);
                    // construct the packet with a GUID
                    Packet memory packet = Packet({
                        nonce: latestNonce,
                        srcEid: eid,
                        sender: _sender,
                        dstEid: _params.dstEid,
                        receiver: _params.receiver,
                        guid: GUID.generate(latestNonce, eid, _sender, _params.dstEid, _params.receiver),
                        message: _params.message
                    });
                    // get the send library by sender and dst eid
                    address _sendLibrary = getSendLibrary(_sender, _params.dstEid);
                    // messageLib always returns encodedPacket with guid
                    (MessagingFee memory fee, bytes memory encodedPacket) = ISendLib(_sendLibrary).send(
                        packet,
                        _params.options,
                        _params.payInLzToken
                    );
                    // Emit packet information for DVNs, Executors, and any other offchain infrastructure to only listen
                    // for this one event to perform their actions.
                    emit PacketSent(encodedPacket, _params.options, _sendLibrary);
                    return (MessagingReceipt(packet.guid, latestNonce, fee), _sendLibrary);
                }
                /// @dev MESSAGING STEP 2 - on the destination chain
                /// @dev configured receive library verifies a message
                /// @param _origin a struct holding the srcEid, nonce, and sender of the message
                /// @param _receiver the receiver of the message
                /// @param _payloadHash the payload hash of the message
                function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external {
                    if (!isValidReceiveLibrary(_receiver, _origin.srcEid, msg.sender)) revert Errors.LZ_InvalidReceiveLibrary();
                    uint64 lazyNonce = lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender];
                    if (!_initializable(_origin, _receiver, lazyNonce)) revert Errors.LZ_PathNotInitializable();
                    if (!_verifiable(_origin, _receiver, lazyNonce)) revert Errors.LZ_PathNotVerifiable();
                    // insert the message into the message channel
                    _inbound(_receiver, _origin.srcEid, _origin.sender, _origin.nonce, _payloadHash);
                    emit PacketVerified(_origin, _receiver, _payloadHash);
                }
                /// @dev MESSAGING STEP 3 - the last step
                /// @dev execute a verified message to the designated receiver
                /// @dev the execution provides the execution context (caller, extraData) to the receiver. the receiver can optionally assert the caller and validate the untrusted extraData
                /// @dev cant reentrant because the payload is cleared before execution
                /// @param _origin the origin of the message
                /// @param _receiver the receiver of the message
                /// @param _guid the guid of the message
                /// @param _message the message
                /// @param _extraData the extra data provided by the executor. this data is untrusted and should be validated.
                function lzReceive(
                    Origin calldata _origin,
                    address _receiver,
                    bytes32 _guid,
                    bytes calldata _message,
                    bytes calldata _extraData
                ) external payable {
                    // clear the payload first to prevent reentrancy, and then execute the message
                    _clearPayload(_receiver, _origin.srcEid, _origin.sender, _origin.nonce, abi.encodePacked(_guid, _message));
                    ILayerZeroReceiver(_receiver).lzReceive{ value: msg.value }(_origin, _guid, _message, msg.sender, _extraData);
                    emit PacketDelivered(_origin, _receiver);
                }
                /// @param _origin the origin of the message
                /// @param _receiver the receiver of the message
                /// @param _guid the guid of the message
                /// @param _message the message
                /// @param _extraData the extra data provided by the executor.
                /// @param _reason the reason for failure
                function lzReceiveAlert(
                    Origin calldata _origin,
                    address _receiver,
                    bytes32 _guid,
                    uint256 _gas,
                    uint256 _value,
                    bytes calldata _message,
                    bytes calldata _extraData,
                    bytes calldata _reason
                ) external {
                    emit LzReceiveAlert(_receiver, msg.sender, _origin, _guid, _gas, _value, _message, _extraData, _reason);
                }
                /// @dev Oapp uses this interface to clear a message.
                /// @dev this is a PULL mode versus the PUSH mode of lzReceive
                /// @dev the cleared message can be ignored by the app (effectively burnt)
                /// @dev authenticated by oapp
                /// @param _origin the origin of the message
                /// @param _guid the guid of the message
                /// @param _message the message
                function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external {
                    _assertAuthorized(_oapp);
                    bytes memory payload = abi.encodePacked(_guid, _message);
                    _clearPayload(_oapp, _origin.srcEid, _origin.sender, _origin.nonce, payload);
                    emit PacketDelivered(_origin, _oapp);
                }
                /// @dev allows reconfiguration to recover from wrong configurations
                /// @dev users should never approve the EndpointV2 contract to spend their non-layerzero tokens
                /// @dev override this function if the endpoint is charging ERC20 tokens as native
                /// @dev only owner
                /// @param _lzToken the new layer zero token address
                function setLzToken(address _lzToken) public virtual onlyOwner {
                    lzToken = _lzToken;
                    emit LzTokenSet(_lzToken);
                }
                /// @dev recover the token sent to this contract by mistake
                /// @dev only owner
                /// @param _token the token to recover. if 0x0 then it is native token
                /// @param _to the address to send the token to
                /// @param _amount the amount to send
                function recoverToken(address _token, address _to, uint256 _amount) external onlyOwner {
                    Transfer.nativeOrToken(_token, _to, _amount);
                }
                /// @dev handling token payments on endpoint. the sender must approve the endpoint to spend the token
                /// @dev internal function
                /// @param _token the token to pay
                /// @param _required the amount required
                /// @param _supplied the amount supplied
                /// @param _receiver the receiver of the token
                function _payToken(
                    address _token,
                    uint256 _required,
                    uint256 _supplied,
                    address _receiver,
                    address _refundAddress
                ) internal {
                    if (_required > 0) {
                        Transfer.token(_token, _receiver, _required);
                    }
                    if (_required < _supplied) {
                        unchecked {
                            // refund the excess
                            Transfer.token(_token, _refundAddress, _supplied - _required);
                        }
                    }
                }
                /// @dev handling native token payments on endpoint
                /// @dev override this if the endpoint is charging ERC20 tokens as native
                /// @dev internal function
                /// @param _required the amount required
                /// @param _supplied the amount supplied
                /// @param _receiver the receiver of the native token
                /// @param _refundAddress the address to refund the excess to
                function _payNative(
                    uint256 _required,
                    uint256 _supplied,
                    address _receiver,
                    address _refundAddress
                ) internal virtual {
                    if (_required > 0) {
                        Transfer.native(_receiver, _required);
                    }
                    if (_required < _supplied) {
                        unchecked {
                            // refund the excess
                            Transfer.native(_refundAddress, _supplied - _required);
                        }
                    }
                }
                /// @dev get the balance of the lzToken as the supplied lzToken fee if payInLzToken is true
                function _suppliedLzToken(bool _payInLzToken) internal view returns (uint256 supplied) {
                    if (_payInLzToken) {
                        supplied = IERC20(lzToken).balanceOf(address(this));
                        // if payInLzToken is true, the supplied fee must be greater than 0 to prevent a race condition
                        // in which an oapp sending a message with lz token and the lz token is set to a new token between the tx
                        // being sent and the tx being mined. if the required lz token fee is 0 and the old lz token would be
                        // locked in the contract instead of being refunded
                        if (supplied == 0) revert Errors.LZ_ZeroLzTokenFee();
                    }
                }
                /// @dev override this if the endpoint is charging ERC20 tokens as native
                function _suppliedNative() internal view virtual returns (uint256) {
                    return msg.value;
                }
                /// @dev Assert the required fees and the supplied fees are enough
                function _assertMessagingFee(
                    MessagingFee memory _required,
                    uint256 _suppliedNativeFee,
                    uint256 _suppliedLzTokenFee
                ) internal pure {
                    if (_required.nativeFee > _suppliedNativeFee || _required.lzTokenFee > _suppliedLzTokenFee) {
                        revert Errors.LZ_InsufficientFee(
                            _required.nativeFee,
                            _suppliedNativeFee,
                            _required.lzTokenFee,
                            _suppliedLzTokenFee
                        );
                    }
                }
                /// @dev override this if the endpoint is charging ERC20 tokens as native
                /// @return 0x0 if using native. otherwise the address of the native ERC20 token
                function nativeToken() external view virtual returns (address) {
                    return address(0x0);
                }
                /// @notice delegate is authorized by the oapp to configure anything in layerzero
                function setDelegate(address _delegate) external {
                    delegates[msg.sender] = _delegate;
                    emit DelegateSet(msg.sender, _delegate);
                }
                // ========================= Internal =========================
                function _initializable(
                    Origin calldata _origin,
                    address _receiver,
                    uint64 _lazyInboundNonce
                ) internal view returns (bool) {
                    return
                        _lazyInboundNonce > 0 || // allowInitializePath already checked
                        ILayerZeroReceiver(_receiver).allowInitializePath(_origin);
                }
                /// @dev bytes(0) payloadHash can never be submitted
                function _verifiable(
                    Origin calldata _origin,
                    address _receiver,
                    uint64 _lazyInboundNonce
                ) internal view returns (bool) {
                    return
                        _origin.nonce > _lazyInboundNonce || // either initializing an empty slot or reverifying
                        inboundPayloadHash[_receiver][_origin.srcEid][_origin.sender][_origin.nonce] != EMPTY_PAYLOAD_HASH; // only allow reverifying if it hasn't been executed
                }
                /// @dev assert the caller to either be the oapp or the delegate
                function _assertAuthorized(address _oapp) internal view override(MessagingChannel, MessageLibManager) {
                    if (msg.sender != _oapp && msg.sender != delegates[_oapp]) revert Errors.LZ_Unauthorized();
                }
                // ========================= VIEW FUNCTIONS FOR OFFCHAIN ONLY =========================
                // Not involved in any state transition function.
                // ====================================================================================
                function initializable(Origin calldata _origin, address _receiver) external view returns (bool) {
                    return _initializable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
                }
                function verifiable(Origin calldata _origin, address _receiver) external view returns (bool) {
                    return _verifiable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]);
                }
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
            import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
            import { IMessageLib, MessageLibType } from "./interfaces/IMessageLib.sol";
            import { IMessageLibManager, SetConfigParam } from "./interfaces/IMessageLibManager.sol";
            import { Errors } from "./libs/Errors.sol";
            import { BlockedMessageLib } from "./messagelib/BlockedMessageLib.sol";
            abstract contract MessageLibManager is Ownable, IMessageLibManager {
                address private constant DEFAULT_LIB = address(0);
                // the library that reverts both on send and quote
                // must be configured on construction and be immutable
                address public immutable blockedLibrary;
                // only registered libraries all valid libraries
                // the blockedLibrary will be registered on construction
                address[] internal registeredLibraries;
                mapping(address lib => bool) public isRegisteredLibrary;
                // both sendLibrary and receiveLibrary config can be lazily resolved
                mapping(address sender => mapping(uint32 dstEid => address lib)) internal sendLibrary;
                mapping(address receiver => mapping(uint32 srcEid => address lib)) internal receiveLibrary;
                mapping(address receiver => mapping(uint32 srcEid => Timeout)) public receiveLibraryTimeout;
                mapping(uint32 dstEid => address lib) public defaultSendLibrary;
                mapping(uint32 srcEid => address lib) public defaultReceiveLibrary;
                mapping(uint32 srcEid => Timeout) public defaultReceiveLibraryTimeout;
                constructor() {
                    blockedLibrary = address(new BlockedMessageLib());
                    registerLibrary(blockedLibrary);
                }
                modifier onlyRegistered(address _lib) {
                    if (!isRegisteredLibrary[_lib]) revert Errors.LZ_OnlyRegisteredLib();
                    _;
                }
                modifier isSendLib(address _lib) {
                    if (_lib != DEFAULT_LIB) {
                        if (IMessageLib(_lib).messageLibType() == MessageLibType.Receive) revert Errors.LZ_OnlySendLib();
                    }
                    _;
                }
                modifier isReceiveLib(address _lib) {
                    if (_lib != DEFAULT_LIB) {
                        if (IMessageLib(_lib).messageLibType() == MessageLibType.Send) revert Errors.LZ_OnlyReceiveLib();
                    }
                    _;
                }
                modifier onlyRegisteredOrDefault(address _lib) {
                    if (!isRegisteredLibrary[_lib] && _lib != DEFAULT_LIB) revert Errors.LZ_OnlyRegisteredOrDefaultLib();
                    _;
                }
                /// @dev check if the library supported the eid.
                modifier onlySupportedEid(address _lib, uint32 _eid) {
                    /// @dev doesnt need to check for default lib, because when they are initially added they get passed through this modifier
                    if (_lib != DEFAULT_LIB) {
                        if (!IMessageLib(_lib).isSupportedEid(_eid)) revert Errors.LZ_UnsupportedEid();
                    }
                    _;
                }
                function getRegisteredLibraries() external view returns (address[] memory) {
                    return registeredLibraries;
                }
                /// @notice The Send Library is the Oapp specified library that will be used to send the message to the destination
                /// endpoint. If the Oapp does not specify a Send Library, the default Send Library will be used.
                /// @dev If the Oapp does not have a selected Send Library, this function will resolve to the default library
                /// configured by LayerZero
                /// @return lib address of the Send Library
                /// @param _sender The address of the Oapp that is sending the message
                /// @param _dstEid The destination endpoint id
                function getSendLibrary(address _sender, uint32 _dstEid) public view returns (address lib) {
                    lib = sendLibrary[_sender][_dstEid];
                    if (lib == DEFAULT_LIB) {
                        lib = defaultSendLibrary[_dstEid];
                        if (lib == address(0x0)) revert Errors.LZ_DefaultSendLibUnavailable();
                    }
                }
                function isDefaultSendLibrary(address _sender, uint32 _dstEid) public view returns (bool) {
                    return sendLibrary[_sender][_dstEid] == DEFAULT_LIB;
                }
                /// @dev the receiveLibrary can be lazily resolved that if not set it will point to the default configured by LayerZero
                function getReceiveLibrary(address _receiver, uint32 _srcEid) public view returns (address lib, bool isDefault) {
                    lib = receiveLibrary[_receiver][_srcEid];
                    if (lib == DEFAULT_LIB) {
                        lib = defaultReceiveLibrary[_srcEid];
                        if (lib == address(0x0)) revert Errors.LZ_DefaultReceiveLibUnavailable();
                        isDefault = true;
                    }
                }
                /// @dev called when the endpoint checks if the msgLib attempting to verify the msg is the configured msgLib of the Oapp
                /// @dev this check provides the ability for Oapp to lock in a trusted msgLib
                /// @dev it will fist check if the msgLib is the currently configured one. then check if the msgLib is the one in grace period of msgLib versioning upgrade
                function isValidReceiveLibrary(
                    address _receiver,
                    uint32 _srcEid,
                    address _actualReceiveLib
                ) public view returns (bool) {
                    // early return true if the _actualReceiveLib is the currently configured one
                    (address expectedReceiveLib, bool isDefault) = getReceiveLibrary(_receiver, _srcEid);
                    if (_actualReceiveLib == expectedReceiveLib) {
                        return true;
                    }
                    // check the timeout condition otherwise
                    // if the Oapp is using defaultReceiveLibrary, use the default Timeout config
                    // otherwise, use the Timeout configured by the Oapp
                    Timeout memory timeout = isDefault
                        ? defaultReceiveLibraryTimeout[_srcEid]
                        : receiveLibraryTimeout[_receiver][_srcEid];
                    // requires the _actualReceiveLib to be the same as the one in grace period and the grace period has not expired
                    // block.number is uint256 so timeout.expiry must > 0, which implies a non-ZERO value
                    if (timeout.lib == _actualReceiveLib && timeout.expiry > block.number) {
                        // timeout lib set and has not expired
                        return true;
                    }
                    // returns false by default
                    return false;
                }
                //------- Owner interfaces
                /// @dev all libraries have to implement the erc165 interface to prevent wrong configurations
                /// @dev only owner
                function registerLibrary(address _lib) public onlyOwner {
                    // must have the right interface
                    if (!IERC165(_lib).supportsInterface(type(IMessageLib).interfaceId)) revert Errors.LZ_UnsupportedInterface();
                    // must have not been registered
                    if (isRegisteredLibrary[_lib]) revert Errors.LZ_AlreadyRegistered();
                    // insert into both the map and the list
                    isRegisteredLibrary[_lib] = true;
                    registeredLibraries.push(_lib);
                    emit LibraryRegistered(_lib);
                }
                /// @dev owner setting the defaultSendLibrary
                /// @dev can set to the blockedLibrary, which is a registered library
                /// @dev the msgLib must enable the support before they can be registered to the endpoint as the default
                /// @dev only owner
                function setDefaultSendLibrary(
                    uint32 _eid,
                    address _newLib
                ) external onlyOwner onlyRegistered(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
                    // must provide a different value
                    if (defaultSendLibrary[_eid] == _newLib) revert Errors.LZ_SameValue();
                    defaultSendLibrary[_eid] = _newLib;
                    emit DefaultSendLibrarySet(_eid, _newLib);
                }
                /// @dev owner setting the defaultSendLibrary
                /// @dev must be a registered library (including blockLibrary) with the eid support enabled
                /// @dev in version migration, it can add a grace period to the old library. if the grace period is 0, it will delete the timeout configuration.
                /// @dev only owner
                function setDefaultReceiveLibrary(
                    uint32 _eid,
                    address _newLib,
                    uint256 _gracePeriod
                ) external onlyOwner onlyRegistered(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
                    address oldLib = defaultReceiveLibrary[_eid];
                    // must provide a different value
                    if (oldLib == _newLib) revert Errors.LZ_SameValue();
                    defaultReceiveLibrary[_eid] = _newLib;
                    emit DefaultReceiveLibrarySet(_eid, _newLib);
                    if (_gracePeriod > 0) {
                        // override the current default timeout to the [old_lib + new expiry]
                        Timeout storage timeout = defaultReceiveLibraryTimeout[_eid];
                        timeout.lib = oldLib;
                        timeout.expiry = block.number + _gracePeriod;
                        emit DefaultReceiveLibraryTimeoutSet(_eid, oldLib, timeout.expiry);
                    } else {
                        // otherwise, remove the old configuration.
                        delete defaultReceiveLibraryTimeout[_eid];
                        emit DefaultReceiveLibraryTimeoutSet(_eid, oldLib, 0);
                    }
                }
                /// @dev owner setting the defaultSendLibrary
                /// @dev must be a registered library (including blockLibrary) with the eid support enabled
                /// @dev can used to (1) extend the current configuration (2) force remove the current configuration (3) change to a new configuration
                /// @param _expiry the block number when lib expires
                function setDefaultReceiveLibraryTimeout(
                    uint32 _eid,
                    address _lib,
                    uint256 _expiry
                ) external onlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) onlyOwner {
                    if (_expiry == 0) {
                        // force remove the current configuration
                        delete defaultReceiveLibraryTimeout[_eid];
                    } else {
                        // override it with new configuration
                        if (_expiry <= block.number) revert Errors.LZ_InvalidExpiry();
                        Timeout storage timeout = defaultReceiveLibraryTimeout[_eid];
                        timeout.lib = _lib;
                        timeout.expiry = _expiry;
                    }
                    emit DefaultReceiveLibraryTimeoutSet(_eid, _lib, _expiry);
                }
                /// @dev returns true only if both the default send/receive libraries are set
                function isSupportedEid(uint32 _eid) external view returns (bool) {
                    return defaultSendLibrary[_eid] != address(0) && defaultReceiveLibrary[_eid] != address(0);
                }
                //------- OApp interfaces
                /// @dev Oapp setting the sendLibrary
                /// @dev must be a registered library (including blockLibrary) with the eid support enabled
                /// @dev authenticated by the Oapp
                function setSendLibrary(
                    address _oapp,
                    uint32 _eid,
                    address _newLib
                ) external onlyRegisteredOrDefault(_newLib) isSendLib(_newLib) onlySupportedEid(_newLib, _eid) {
                    _assertAuthorized(_oapp);
                    // must provide a different value
                    if (sendLibrary[_oapp][_eid] == _newLib) revert Errors.LZ_SameValue();
                    sendLibrary[_oapp][_eid] = _newLib;
                    emit SendLibrarySet(_oapp, _eid, _newLib);
                }
                /// @dev Oapp setting the receiveLibrary
                /// @dev must be a registered library (including blockLibrary) with the eid support enabled
                /// @dev in version migration, it can add a grace period to the old library. if the grace period is 0, it will delete the timeout configuration.
                /// @dev authenticated by the Oapp
                /// @param _gracePeriod the number of blocks from now until oldLib expires
                function setReceiveLibrary(
                    address _oapp,
                    uint32 _eid,
                    address _newLib,
                    uint256 _gracePeriod
                ) external onlyRegisteredOrDefault(_newLib) isReceiveLib(_newLib) onlySupportedEid(_newLib, _eid) {
                    _assertAuthorized(_oapp);
                    address oldLib = receiveLibrary[_oapp][_eid];
                    // must provide new values
                    if (oldLib == _newLib) revert Errors.LZ_SameValue();
                    receiveLibrary[_oapp][_eid] = _newLib;
                    emit ReceiveLibrarySet(_oapp, _eid, _newLib);
                    if (_gracePeriod > 0) {
                        // to simplify the logic, we only allow to set timeout if neither the new lib nor old lib is DEFAULT_LIB, which would should read the default timeout configurations
                        // (1) if the Oapp wants to fall back to the DEFAULT, then set the newLib to DEFAULT with grace period == 0
                        // (2) if the Oapp wants to change to a non DEFAULT from DEFAULT, then set the newLib to 'non-default' with _gracePeriod == 0, then use setReceiveLibraryTimeout() interface
                        if (oldLib == DEFAULT_LIB || _newLib == DEFAULT_LIB) revert Errors.LZ_OnlyNonDefaultLib();
                        // write to storage
                        Timeout memory timeout = Timeout({ lib: oldLib, expiry: block.number + _gracePeriod });
                        receiveLibraryTimeout[_oapp][_eid] = timeout;
                        emit ReceiveLibraryTimeoutSet(_oapp, _eid, oldLib, timeout.expiry);
                    } else {
                        delete receiveLibraryTimeout[_oapp][_eid];
                        emit ReceiveLibraryTimeoutSet(_oapp, _eid, oldLib, 0);
                    }
                }
                /// @dev Oapp setting the defaultSendLibrary
                /// @dev must be a registered library (including blockLibrary) with the eid support enabled
                /// @dev can used to (1) extend the current configuration (2)  force remove the current configuration (3) change to a new configuration
                /// @param _expiry the block number when lib expires
                function setReceiveLibraryTimeout(
                    address _oapp,
                    uint32 _eid,
                    address _lib,
                    uint256 _expiry
                ) external onlyRegistered(_lib) isReceiveLib(_lib) onlySupportedEid(_lib, _eid) {
                    _assertAuthorized(_oapp);
                    (, bool isDefault) = getReceiveLibrary(_oapp, _eid);
                    // if current library is DEFAULT, Oapp cant set the timeout
                    if (isDefault) revert Errors.LZ_OnlyNonDefaultLib();
                    if (_expiry == 0) {
                        // force remove the current configuration
                        delete receiveLibraryTimeout[_oapp][_eid];
                    } else {
                        // override it with new configuration
                        if (_expiry <= block.number) revert Errors.LZ_InvalidExpiry();
                        Timeout storage timeout = receiveLibraryTimeout[_oapp][_eid];
                        timeout.lib = _lib;
                        timeout.expiry = _expiry;
                    }
                    emit ReceiveLibraryTimeoutSet(_oapp, _eid, _lib, _expiry);
                }
                //------- library config setter/getter. all pass-through functions to the msgLib
                /// @dev authenticated by the _oapp
                function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external onlyRegistered(_lib) {
                    _assertAuthorized(_oapp);
                    IMessageLib(_lib).setConfig(_oapp, _params);
                }
                /// @dev a view function to query the current configuration of the OApp
                function getConfig(
                    address _oapp,
                    address _lib,
                    uint32 _eid,
                    uint32 _configType
                ) external view onlyRegistered(_lib) returns (bytes memory config) {
                    return IMessageLib(_lib).getConfig(_eid, _oapp, _configType);
                }
                function _assertAuthorized(address _oapp) internal virtual;
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { IMessagingChannel } from "./interfaces/IMessagingChannel.sol";
            import { Errors } from "./libs/Errors.sol";
            import { GUID } from "./libs/GUID.sol";
            abstract contract MessagingChannel is IMessagingChannel {
                bytes32 public constant EMPTY_PAYLOAD_HASH = bytes32(0);
                bytes32 public constant NIL_PAYLOAD_HASH = bytes32(type(uint256).max);
                // The universally unique id (UUID) of this deployed Endpoint
                uint32 public immutable eid;
                mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => uint64 nonce)))
                    public lazyInboundNonce;
                mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => mapping(uint64 inboundNonce => bytes32 payloadHash))))
                    public inboundPayloadHash;
                mapping(address sender => mapping(uint32 dstEid => mapping(bytes32 receiver => uint64 nonce))) public outboundNonce;
                /// @param _eid is the universally unique id (UUID) of this deployed Endpoint
                constructor(uint32 _eid) {
                    eid = _eid;
                }
                /// @dev increase and return the next outbound nonce
                function _outbound(address _sender, uint32 _dstEid, bytes32 _receiver) internal returns (uint64 nonce) {
                    unchecked {
                        nonce = ++outboundNonce[_sender][_dstEid][_receiver];
                    }
                }
                /// @dev inbound won't update the nonce eagerly to allow unordered verification
                /// @dev instead, it will update the nonce lazily when the message is received
                /// @dev messages can only be cleared in order to preserve censorship-resistance
                function _inbound(
                    address _receiver,
                    uint32 _srcEid,
                    bytes32 _sender,
                    uint64 _nonce,
                    bytes32 _payloadHash
                ) internal {
                    if (_payloadHash == EMPTY_PAYLOAD_HASH) revert Errors.LZ_InvalidPayloadHash();
                    inboundPayloadHash[_receiver][_srcEid][_sender][_nonce] = _payloadHash;
                }
                /// @dev returns the max index of the longest gapless sequence of verified msg nonces.
                /// @dev the uninitialized value is 0. the first nonce is always 1
                /// @dev it starts from the lazyInboundNonce (last checkpoint) and iteratively check if the next nonce has been verified
                /// @dev this function can OOG if too many backlogs, but it can be trivially fixed by just clearing some prior messages
                /// @dev NOTE: Oapp explicitly skipped nonces count as "verified" for these purposes
                /// @dev eg. [1,2,3,4,6,7] => 4, [1,2,6,8,10] => 2, [1,3,4,5,6] => 1
                function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) public view returns (uint64) {
                    uint64 nonceCursor = lazyInboundNonce[_receiver][_srcEid][_sender];
                    // find the effective inbound currentNonce
                    unchecked {
                        while (_hasPayloadHash(_receiver, _srcEid, _sender, nonceCursor + 1)) {
                            ++nonceCursor;
                        }
                    }
                    return nonceCursor;
                }
                /// @dev checks if the storage slot is not initialized. Assumes computationally infeasible that payload can hash to 0
                function _hasPayloadHash(
                    address _receiver,
                    uint32 _srcEid,
                    bytes32 _sender,
                    uint64 _nonce
                ) internal view returns (bool) {
                    return inboundPayloadHash[_receiver][_srcEid][_sender][_nonce] != EMPTY_PAYLOAD_HASH;
                }
                /// @dev the caller must provide _nonce to prevent skipping the unintended nonce
                /// @dev it could happen in some race conditions, e.g. to skip nonce 3, but nonce 3 was consumed first
                /// @dev usage: skipping the next nonce to prevent message verification, e.g. skip a message when Precrime throws alerts
                /// @dev if the Oapp wants to skip a verified message, it should call the clear() function instead
                /// @dev after skipping, the lazyInboundNonce is set to the provided nonce, which makes the inboundNonce also the provided nonce
                /// @dev ie. allows the Oapp to increment the lazyInboundNonce without having had that corresponding msg be verified
                function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external {
                    _assertAuthorized(_oapp);
                    if (_nonce != inboundNonce(_oapp, _srcEid, _sender) + 1) revert Errors.LZ_InvalidNonce(_nonce);
                    lazyInboundNonce[_oapp][_srcEid][_sender] = _nonce;
                    emit InboundNonceSkipped(_srcEid, _sender, _oapp, _nonce);
                }
                /// @dev Marks a packet as verified, but disallows execution until it is re-verified.
                /// @dev Reverts if the provided _payloadHash does not match the currently verified payload hash.
                /// @dev A non-verified nonce can be nilified by passing EMPTY_PAYLOAD_HASH for _payloadHash.
                /// @dev Assumes the computational intractability of finding a payload that hashes to bytes32.max.
                /// @dev Authenticated by the caller
                function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external {
                    _assertAuthorized(_oapp);
                    bytes32 curPayloadHash = inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
                    if (curPayloadHash != _payloadHash) revert Errors.LZ_PayloadHashNotFound(curPayloadHash, _payloadHash);
                    if (_nonce <= lazyInboundNonce[_oapp][_srcEid][_sender] && curPayloadHash == EMPTY_PAYLOAD_HASH)
                        revert Errors.LZ_InvalidNonce(_nonce);
                    // set it to nil
                    inboundPayloadHash[_oapp][_srcEid][_sender][_nonce] = NIL_PAYLOAD_HASH;
                    emit PacketNilified(_srcEid, _sender, _oapp, _nonce, _payloadHash);
                }
                /// @dev Marks a nonce as unexecutable and un-verifiable. The nonce can never be re-verified or executed.
                /// @dev Reverts if the provided _payloadHash does not match the currently verified payload hash.
                /// @dev Only packets with nonces less than or equal to the lazy inbound nonce can be burned.
                /// @dev Reverts if the nonce has already been executed.
                /// @dev Authenticated by the caller
                function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external {
                    _assertAuthorized(_oapp);
                    bytes32 curPayloadHash = inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
                    if (curPayloadHash != _payloadHash) revert Errors.LZ_PayloadHashNotFound(curPayloadHash, _payloadHash);
                    if (curPayloadHash == EMPTY_PAYLOAD_HASH || _nonce > lazyInboundNonce[_oapp][_srcEid][_sender])
                        revert Errors.LZ_InvalidNonce(_nonce);
                    delete inboundPayloadHash[_oapp][_srcEid][_sender][_nonce];
                    emit PacketBurnt(_srcEid, _sender, _oapp, _nonce, _payloadHash);
                }
                /// @dev calling this function will clear the stored message and increment the lazyInboundNonce to the provided nonce
                /// @dev if a lot of messages are queued, the messages can be cleared with a smaller step size to prevent OOG
                /// @dev NOTE: this function does not change inboundNonce, it only changes the lazyInboundNonce up to the provided nonce
                function _clearPayload(
                    address _receiver,
                    uint32 _srcEid,
                    bytes32 _sender,
                    uint64 _nonce,
                    bytes memory _payload
                ) internal returns (bytes32 actualHash) {
                    uint64 currentNonce = lazyInboundNonce[_receiver][_srcEid][_sender];
                    if (_nonce > currentNonce) {
                        unchecked {
                            // try to lazily update the inboundNonce till the _nonce
                            for (uint64 i = currentNonce + 1; i <= _nonce; ++i) {
                                if (!_hasPayloadHash(_receiver, _srcEid, _sender, i)) revert Errors.LZ_InvalidNonce(i);
                            }
                            lazyInboundNonce[_receiver][_srcEid][_sender] = _nonce;
                        }
                    }
                    // check the hash of the payload to verify the executor has given the proper payload that has been verified
                    actualHash = keccak256(_payload);
                    bytes32 expectedHash = inboundPayloadHash[_receiver][_srcEid][_sender][_nonce];
                    if (expectedHash != actualHash) revert Errors.LZ_PayloadHashNotFound(expectedHash, actualHash);
                    // remove it from the storage
                    delete inboundPayloadHash[_receiver][_srcEid][_sender][_nonce];
                }
                /// @dev returns the GUID for the next message given the path
                /// @dev the Oapp might want to include the GUID into the message in some cases
                function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32) {
                    uint64 nextNonce = outboundNonce[_sender][_dstEid][_receiver] + 1;
                    return GUID.generate(nextNonce, eid, _sender, _dstEid, _receiver);
                }
                function _assertAuthorized(address _oapp) internal virtual;
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { IMessagingComposer } from "./interfaces/IMessagingComposer.sol";
            import { ILayerZeroComposer } from "./interfaces/ILayerZeroComposer.sol";
            import { Errors } from "./libs/Errors.sol";
            abstract contract MessagingComposer is IMessagingComposer {
                bytes32 private constant NO_MESSAGE_HASH = bytes32(0);
                bytes32 private constant RECEIVED_MESSAGE_HASH = bytes32(uint256(1));
                mapping(address from => mapping(address to => mapping(bytes32 guid => mapping(uint16 index => bytes32 messageHash))))
                    public composeQueue;
                /// @dev the Oapp sends the lzCompose message to the endpoint
                /// @dev the composer MUST assert the sender because anyone can send compose msg with this function
                /// @dev with the same GUID, the Oapp can send compose to multiple _composer at the same time
                /// @dev authenticated by the msg.sender
                /// @param _to the address which will receive the composed message
                /// @param _guid the message guid
                /// @param _message the message
                function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external {
                    // must have not been sent before
                    if (composeQueue[msg.sender][_to][_guid][_index] != NO_MESSAGE_HASH) revert Errors.LZ_ComposeExists();
                    composeQueue[msg.sender][_to][_guid][_index] = keccak256(_message);
                    emit ComposeSent(msg.sender, _to, _guid, _index, _message);
                }
                /// @dev execute a composed messages from the sender to the composer (receiver)
                /// @dev the execution provides the execution context (caller, extraData) to the receiver.
                ///      the receiver can optionally assert the caller and validate the untrusted extraData
                /// @dev can not re-entrant
                /// @param _from the address which sends the composed message. in most cases, it is the Oapp's address.
                /// @param _to the address which receives the composed message
                /// @param _guid the message guid
                /// @param _message the message
                /// @param _extraData the extra data provided by the executor. this data is untrusted and should be validated.
                function lzCompose(
                    address _from,
                    address _to,
                    bytes32 _guid,
                    uint16 _index,
                    bytes calldata _message,
                    bytes calldata _extraData
                ) external payable {
                    // assert the validity
                    bytes32 expectedHash = composeQueue[_from][_to][_guid][_index];
                    bytes32 actualHash = keccak256(_message);
                    if (expectedHash != actualHash) revert Errors.LZ_ComposeNotFound(expectedHash, actualHash);
                    // marks the message as received to prevent reentrancy
                    // cannot just delete the value, otherwise the message can be sent again and could result in some undefined behaviour
                    // even though the sender(composing Oapp) is implicitly fully trusted by the composer.
                    // eg. sender may not even realize it has such a bug
                    composeQueue[_from][_to][_guid][_index] = RECEIVED_MESSAGE_HASH;
                    ILayerZeroComposer(_to).lzCompose{ value: msg.value }(_from, _guid, _message, msg.sender, _extraData);
                    emit ComposeDelivered(_from, _to, _guid, _index);
                }
                /// @param _from the address which sends the composed message
                /// @param _to the address which receives the composed message
                /// @param _guid the message guid
                /// @param _message the message
                /// @param _extraData the extra data provided by the executor
                /// @param _reason the reason why the message is not received
                function lzComposeAlert(
                    address _from,
                    address _to,
                    bytes32 _guid,
                    uint16 _index,
                    uint256 _gas,
                    uint256 _value,
                    bytes calldata _message,
                    bytes calldata _extraData,
                    bytes calldata _reason
                ) external {
                    emit LzComposeAlert(_from, _to, msg.sender, _guid, _index, _gas, _value, _message, _extraData, _reason);
                }
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { IMessagingContext } from "./interfaces/IMessagingContext.sol";
            import { Errors } from "./libs/Errors.sol";
            /// this contract acts as a non-reentrancy guard and a source of messaging context
            /// the context includes the remote eid and the sender address
            /// it separates the send and receive context to allow messaging receipts (send back on receive())
            abstract contract MessagingContext is IMessagingContext {
                uint256 private constant NOT_ENTERED = 1;
                uint256 private _sendContext = NOT_ENTERED;
                /// @dev the sendContext is set to 8 bytes 0s + 4 bytes eid + 20 bytes sender
                modifier sendContext(uint32 _dstEid, address _sender) {
                    if (_sendContext != NOT_ENTERED) revert Errors.LZ_SendReentrancy();
                    _sendContext = (uint256(_dstEid) << 160) | uint160(_sender);
                    _;
                    _sendContext = NOT_ENTERED;
                }
                /// @dev returns true if sending message
                function isSendingMessage() public view returns (bool) {
                    return _sendContext != NOT_ENTERED;
                }
                /// @dev returns (eid, sender) if sending message, (0, 0) otherwise
                function getSendContext() external view returns (uint32, address) {
                    return isSendingMessage() ? _getSendContext(_sendContext) : (0, address(0));
                }
                function _getSendContext(uint256 _context) internal pure returns (uint32, address) {
                    return (uint32(_context >> 160), address(uint160(_context)));
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            /**
             * @title ILayerZeroComposer
             */
            interface ILayerZeroComposer {
                /**
                 * @notice Composes a LayerZero message from an OApp.
                 * @param _from The address initiating the composition, typically the OApp where the lzReceive was called.
                 * @param _guid The unique identifier for the corresponding LayerZero src/dst tx.
                 * @param _message The composed message payload in bytes. NOT necessarily the same payload passed via lzReceive.
                 * @param _executor The address of the executor for the composed message.
                 * @param _extraData Additional arbitrary data in bytes passed by the entity who executes the lzCompose.
                 */
                function lzCompose(
                    address _from,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) external payable;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            import { IMessageLibManager } from "./IMessageLibManager.sol";
            import { IMessagingComposer } from "./IMessagingComposer.sol";
            import { IMessagingChannel } from "./IMessagingChannel.sol";
            import { IMessagingContext } from "./IMessagingContext.sol";
            struct MessagingParams {
                uint32 dstEid;
                bytes32 receiver;
                bytes message;
                bytes options;
                bool payInLzToken;
            }
            struct MessagingReceipt {
                bytes32 guid;
                uint64 nonce;
                MessagingFee fee;
            }
            struct MessagingFee {
                uint256 nativeFee;
                uint256 lzTokenFee;
            }
            struct Origin {
                uint32 srcEid;
                bytes32 sender;
                uint64 nonce;
            }
            interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
                event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
                event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
                event PacketDelivered(Origin origin, address receiver);
                event LzReceiveAlert(
                    address indexed receiver,
                    address indexed executor,
                    Origin origin,
                    bytes32 guid,
                    uint256 gas,
                    uint256 value,
                    bytes message,
                    bytes extraData,
                    bytes reason
                );
                event LzTokenSet(address token);
                event DelegateSet(address sender, address delegate);
                function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
                function send(
                    MessagingParams calldata _params,
                    address _refundAddress
                ) external payable returns (MessagingReceipt memory);
                function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
                function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
                function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
                function lzReceive(
                    Origin calldata _origin,
                    address _receiver,
                    bytes32 _guid,
                    bytes calldata _message,
                    bytes calldata _extraData
                ) external payable;
                // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
                function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
                function setLzToken(address _lzToken) external;
                function lzToken() external view returns (address);
                function nativeToken() external view returns (address);
                function setDelegate(address _delegate) external;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            import { Origin } from "./ILayerZeroEndpointV2.sol";
            interface ILayerZeroReceiver {
                function allowInitializePath(Origin calldata _origin) external view returns (bool);
                function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);
                function lzReceive(
                    Origin calldata _origin,
                    bytes32 _guid,
                    bytes calldata _message,
                    address _executor,
                    bytes calldata _extraData
                ) external payable;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
            import { SetConfigParam } from "./IMessageLibManager.sol";
            enum MessageLibType {
                Send,
                Receive,
                SendAndReceive
            }
            interface IMessageLib is IERC165 {
                function setConfig(address _oapp, SetConfigParam[] calldata _config) external;
                function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);
                function isSupportedEid(uint32 _eid) external view returns (bool);
                // message libs of same major version are compatible
                function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
                function messageLibType() external view returns (MessageLibType);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            struct SetConfigParam {
                uint32 eid;
                uint32 configType;
                bytes config;
            }
            interface IMessageLibManager {
                struct Timeout {
                    address lib;
                    uint256 expiry;
                }
                event LibraryRegistered(address newLib);
                event DefaultSendLibrarySet(uint32 eid, address newLib);
                event DefaultReceiveLibrarySet(uint32 eid, address newLib);
                event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
                event SendLibrarySet(address sender, uint32 eid, address newLib);
                event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
                event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
                function registerLibrary(address _lib) external;
                function isRegisteredLibrary(address _lib) external view returns (bool);
                function getRegisteredLibraries() external view returns (address[] memory);
                function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
                function defaultSendLibrary(uint32 _eid) external view returns (address);
                function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _timeout) external;
                function defaultReceiveLibrary(uint32 _eid) external view returns (address);
                function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
                function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
                function isSupportedEid(uint32 _eid) external view returns (bool);
                function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
                /// ------------------- OApp interfaces -------------------
                function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
                function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
                function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
                function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
                function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
                function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _gracePeriod) external;
                function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
                function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
                function getConfig(
                    address _oapp,
                    address _lib,
                    uint32 _eid,
                    uint32 _configType
                ) external view returns (bytes memory config);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            interface IMessagingChannel {
                event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
                event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
                event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
                function eid() external view returns (uint32);
                // this is an emergency function if a message cannot be verified for some reasons
                // required to provide _nextNonce to avoid race condition
                function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
                function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
                function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
                function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
                function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
                function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
                function inboundPayloadHash(
                    address _receiver,
                    uint32 _srcEid,
                    bytes32 _sender,
                    uint64 _nonce
                ) external view returns (bytes32);
                function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            interface IMessagingComposer {
                event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
                event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
                event LzComposeAlert(
                    address indexed from,
                    address indexed to,
                    address indexed executor,
                    bytes32 guid,
                    uint16 index,
                    uint256 gas,
                    uint256 value,
                    bytes message,
                    bytes extraData,
                    bytes reason
                );
                function composeQueue(
                    address _from,
                    address _to,
                    bytes32 _guid,
                    uint16 _index
                ) external view returns (bytes32 messageHash);
                function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
                function lzCompose(
                    address _from,
                    address _to,
                    bytes32 _guid,
                    uint16 _index,
                    bytes calldata _message,
                    bytes calldata _extraData
                ) external payable;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            interface IMessagingContext {
                function isSendingMessage() external view returns (bool);
                function getSendContext() external view returns (uint32 dstEid, address sender);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.0;
            import { MessagingFee } from "./ILayerZeroEndpointV2.sol";
            import { IMessageLib } from "./IMessageLib.sol";
            struct Packet {
                uint64 nonce;
                uint32 srcEid;
                address sender;
                uint32 dstEid;
                bytes32 receiver;
                bytes32 guid;
                bytes message;
            }
            interface ISendLib is IMessageLib {
                function send(
                    Packet calldata _packet,
                    bytes calldata _options,
                    bool _payInLzToken
                ) external returns (MessagingFee memory, bytes memory encodedPacket);
                function quote(
                    Packet calldata _packet,
                    bytes calldata _options,
                    bool _payInLzToken
                ) external view returns (MessagingFee memory);
                function setTreasury(address _treasury) external;
                function withdrawFee(address _to, uint256 _amount) external;
                function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            library AddressCast {
                error AddressCast_InvalidSizeForAddress();
                error AddressCast_InvalidAddress();
                function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
                    if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
                    result = bytes32(_addressBytes);
                    unchecked {
                        uint256 offset = 32 - _addressBytes.length;
                        result = result >> (offset * 8);
                    }
                }
                function toBytes32(address _address) internal pure returns (bytes32 result) {
                    result = bytes32(uint256(uint160(_address)));
                }
                function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
                    if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
                    result = new bytes(_size);
                    unchecked {
                        uint256 offset = 256 - _size * 8;
                        assembly {
                            mstore(add(result, 32), shl(offset, _addressBytes32))
                        }
                    }
                }
                function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
                    result = address(uint160(uint256(_addressBytes32)));
                }
                function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
                    if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
                    result = address(bytes20(_addressBytes));
                }
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            library Errors {
                error LZ_LzTokenUnavailable();
                error LZ_InvalidReceiveLibrary();
                error LZ_InvalidNonce(uint64 nonce);
                error LZ_InvalidArgument();
                error LZ_InvalidExpiry();
                error LZ_InvalidAmount(uint256 required, uint256 supplied);
                error LZ_OnlyRegisteredOrDefaultLib();
                error LZ_OnlyRegisteredLib();
                error LZ_OnlyNonDefaultLib();
                error LZ_Unauthorized();
                error LZ_DefaultSendLibUnavailable();
                error LZ_DefaultReceiveLibUnavailable();
                error LZ_PathNotInitializable();
                error LZ_PathNotVerifiable();
                error LZ_OnlySendLib();
                error LZ_OnlyReceiveLib();
                error LZ_UnsupportedEid();
                error LZ_UnsupportedInterface();
                error LZ_AlreadyRegistered();
                error LZ_SameValue();
                error LZ_InvalidPayloadHash();
                error LZ_PayloadHashNotFound(bytes32 expected, bytes32 actual);
                error LZ_ComposeNotFound(bytes32 expected, bytes32 actual);
                error LZ_ComposeExists();
                error LZ_SendReentrancy();
                error LZ_NotImplemented();
                error LZ_InsufficientFee(
                    uint256 requiredNative,
                    uint256 suppliedNative,
                    uint256 requiredLzToken,
                    uint256 suppliedLzToken
                );
                error LZ_ZeroLzTokenFee();
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { AddressCast } from "./AddressCast.sol";
            library GUID {
                using AddressCast for address;
                function generate(
                    uint64 _nonce,
                    uint32 _srcEid,
                    address _sender,
                    uint32 _dstEid,
                    bytes32 _receiver
                ) internal pure returns (bytes32) {
                    return keccak256(abi.encodePacked(_nonce, _srcEid, _sender.toBytes32(), _dstEid, _receiver));
                }
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
            import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            library Transfer {
                using SafeERC20 for IERC20;
                address internal constant ADDRESS_ZERO = address(0);
                error Transfer_NativeFailed(address _to, uint256 _value);
                error Transfer_ToAddressIsZero();
                function native(address _to, uint256 _value) internal {
                    if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
                    (bool success, ) = _to.call{ value: _value }("");
                    if (!success) revert Transfer_NativeFailed(_to, _value);
                }
                function token(address _token, address _to, uint256 _value) internal {
                    if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero();
                    IERC20(_token).safeTransfer(_to, _value);
                }
                function nativeOrToken(address _token, address _to, uint256 _value) internal {
                    if (_token == ADDRESS_ZERO) {
                        native(_to, _value);
                    } else {
                        token(_token, _to, _value);
                    }
                }
            }
            // SPDX-License-Identifier: LZBL-1.2
            pragma solidity ^0.8.20;
            import { ERC165 } from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
            import { IMessageLib, MessageLibType } from "../interfaces/IMessageLib.sol";
            import { Errors } from "../libs/Errors.sol";
            contract BlockedMessageLib is ERC165 {
                function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
                    return interfaceId == type(IMessageLib).interfaceId || super.supportsInterface(interfaceId);
                }
                function version() external pure returns (uint64 major, uint8 minor, uint8 endpointVersion) {
                    return (type(uint64).max, type(uint8).max, 2);
                }
                function messageLibType() external pure returns (MessageLibType) {
                    return MessageLibType.SendAndReceive;
                }
                function isSupportedEid(uint32) external pure returns (bool) {
                    return true;
                }
                fallback() external {
                    revert Errors.LZ_NotImplemented();
                }
            }
            

            File 5 of 5: Archetype
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
            pragma solidity ^0.8.0;
            import "../utils/introspection/IERC165Upgradeable.sol";
            /**
             * @dev Interface for the NFT Royalty Standard.
             *
             * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
             * support for royalty payments across all NFT marketplaces and ecosystem participants.
             *
             * _Available since v4.5._
             */
            interface IERC2981Upgradeable is IERC165Upgradeable {
                /**
                 * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
                 * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
                 */
                function royaltyInfo(uint256 tokenId, uint256 salePrice)
                    external
                    view
                    returns (address receiver, uint256 royaltyAmount);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
            pragma solidity ^0.8.2;
            import "../../utils/AddressUpgradeable.sol";
            /**
             * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
             * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
             * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
             * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
             *
             * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
             * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
             * case an upgrade adds a module that needs to be initialized.
             *
             * For example:
             *
             * [.hljs-theme-light.nopadding]
             * ```
             * contract MyToken is ERC20Upgradeable {
             *     function initialize() initializer public {
             *         __ERC20_init("MyToken", "MTK");
             *     }
             * }
             * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
             *     function initializeV2() reinitializer(2) public {
             *         __ERC20Permit_init("MyToken");
             *     }
             * }
             * ```
             *
             * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
             * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
             *
             * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
             * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
             *
             * [CAUTION]
             * ====
             * Avoid leaving a contract uninitialized.
             *
             * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
             * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
             * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
             *
             * [.hljs-theme-light.nopadding]
             * ```
             * /// @custom:oz-upgrades-unsafe-allow constructor
             * constructor() {
             *     _disableInitializers();
             * }
             * ```
             * ====
             */
            abstract contract Initializable {
                /**
                 * @dev Indicates that the contract has been initialized.
                 * @custom:oz-retyped-from bool
                 */
                uint8 private _initialized;
                /**
                 * @dev Indicates that the contract is in the process of being initialized.
                 */
                bool private _initializing;
                /**
                 * @dev Triggered when the contract has been initialized or reinitialized.
                 */
                event Initialized(uint8 version);
                /**
                 * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
                 * `onlyInitializing` functions can be used to initialize parent contracts.
                 *
                 * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
                 * constructor.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier initializer() {
                    bool isTopLevelCall = !_initializing;
                    require(
                        (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                        "Initializable: contract is already initialized"
                    );
                    _initialized = 1;
                    if (isTopLevelCall) {
                        _initializing = true;
                    }
                    _;
                    if (isTopLevelCall) {
                        _initializing = false;
                        emit Initialized(1);
                    }
                }
                /**
                 * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
                 * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
                 * used to initialize parent contracts.
                 *
                 * A reinitializer may be used after the original initialization step. This is essential to configure modules that
                 * are added through upgrades and that require initialization.
                 *
                 * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
                 * cannot be nested. If one is invoked in the context of another, execution will revert.
                 *
                 * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
                 * a contract, executing them in the right order is up to the developer or operator.
                 *
                 * WARNING: setting the version to 255 will prevent any future reinitialization.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier reinitializer(uint8 version) {
                    require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                    _initialized = version;
                    _initializing = true;
                    _;
                    _initializing = false;
                    emit Initialized(version);
                }
                /**
                 * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                 * {initializer} and {reinitializer} modifiers, directly or indirectly.
                 */
                modifier onlyInitializing() {
                    require(_initializing, "Initializable: contract is not initializing");
                    _;
                }
                /**
                 * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
                 * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
                 * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
                 * through proxies.
                 *
                 * Emits an {Initialized} event the first time it is successfully executed.
                 */
                function _disableInitializers() internal virtual {
                    require(!_initializing, "Initializable: contract is initializing");
                    if (_initialized < type(uint8).max) {
                        _initialized = type(uint8).max;
                        emit Initialized(type(uint8).max);
                    }
                }
                /**
                 * @dev Internal function that returns the initialized version. Returns `_initialized`
                 */
                function _getInitializedVersion() internal view returns (uint8) {
                    return _initialized;
                }
                /**
                 * @dev Internal function that returns the initialized version. Returns `_initializing`
                 */
                function _isInitializing() internal view returns (bool) {
                    return _initializing;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
            pragma solidity ^0.8.0;
            import "../../interfaces/IERC2981Upgradeable.sol";
            import "../../utils/introspection/ERC165Upgradeable.sol";
            import "../../proxy/utils/Initializable.sol";
            /**
             * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
             *
             * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
             * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
             *
             * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
             * fee is specified in basis points by default.
             *
             * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
             * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
             * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
             *
             * _Available since v4.5._
             */
            abstract contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {
                function __ERC2981_init() internal onlyInitializing {
                }
                function __ERC2981_init_unchained() internal onlyInitializing {
                }
                struct RoyaltyInfo {
                    address receiver;
                    uint96 royaltyFraction;
                }
                RoyaltyInfo private _defaultRoyaltyInfo;
                mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
                /**
                 * @dev See {IERC165-supportsInterface}.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) {
                    return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId);
                }
                /**
                 * @inheritdoc IERC2981Upgradeable
                 */
                function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
                    RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
                    if (royalty.receiver == address(0)) {
                        royalty = _defaultRoyaltyInfo;
                    }
                    uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
                    return (royalty.receiver, royaltyAmount);
                }
                /**
                 * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
                 * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
                 * override.
                 */
                function _feeDenominator() internal pure virtual returns (uint96) {
                    return 10000;
                }
                /**
                 * @dev Sets the royalty information that all ids in this contract will default to.
                 *
                 * Requirements:
                 *
                 * - `receiver` cannot be the zero address.
                 * - `feeNumerator` cannot be greater than the fee denominator.
                 */
                function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
                    require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                    require(receiver != address(0), "ERC2981: invalid receiver");
                    _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
                }
                /**
                 * @dev Removes default royalty information.
                 */
                function _deleteDefaultRoyalty() internal virtual {
                    delete _defaultRoyaltyInfo;
                }
                /**
                 * @dev Sets the royalty information for a specific token id, overriding the global default.
                 *
                 * Requirements:
                 *
                 * - `receiver` cannot be the zero address.
                 * - `feeNumerator` cannot be greater than the fee denominator.
                 */
                function _setTokenRoyalty(
                    uint256 tokenId,
                    address receiver,
                    uint96 feeNumerator
                ) internal virtual {
                    require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
                    require(receiver != address(0), "ERC2981: Invalid parameters");
                    _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
                }
                /**
                 * @dev Resets royalty information for the token id back to the global default.
                 */
                function _resetTokenRoyalty(uint256 tokenId) internal virtual {
                    delete _tokenRoyaltyInfo[tokenId];
                }
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[48] private __gap;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            interface IERC20Upgradeable {
                /**
                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                 * another (`to`).
                 *
                 * Note that `value` may be zero.
                 */
                event Transfer(address indexed from, address indexed to, uint256 value);
                /**
                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                 * a call to {approve}. `value` is the new allowance.
                 */
                event Approval(address indexed owner, address indexed spender, uint256 value);
                /**
                 * @dev Returns the amount of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
                /**
                 * @dev Returns the amount of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
                /**
                 * @dev Moves `amount` tokens from the caller's account to `to`.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transfer(address to, uint256 amount) external returns (bool);
                /**
                 * @dev Returns the remaining number of tokens that `spender` will be
                 * allowed to spend on behalf of `owner` through {transferFrom}. This is
                 * zero by default.
                 *
                 * This value changes when {approve} or {transferFrom} are called.
                 */
                function allowance(address owner, address spender) external view returns (uint256);
                /**
                 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * IMPORTANT: Beware that changing an allowance with this method brings the risk
                 * that someone may use both the old and the new allowance by unfortunate
                 * transaction ordering. One possible solution to mitigate this race
                 * condition is to first reduce the spender's allowance to 0 and set the
                 * desired value afterwards:
                 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address spender, uint256 amount) external returns (bool);
                /**
                 * @dev Moves `amount` tokens from `from` to `to` using the
                 * allowance mechanism. `amount` is then deducted from the caller's
                 * allowance.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 amount
                ) external returns (bool);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
            pragma solidity ^0.8.1;
            /**
             * @dev Collection of functions related to the address type
             */
            library AddressUpgradeable {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 * ====
                 *
                 * [IMPORTANT]
                 * ====
                 * You shouldn't rely on `isContract` to protect against flash loan attacks!
                 *
                 * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                 * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                 * constructor.
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize/address.code.length, which returns 0
                    // for contracts in construction, since the code is only stored at the end
                    // of the constructor execution.
                    return account.code.length > 0;
                }
                /**
                 * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                 * `recipient`, forwarding all available gas and reverting on errors.
                 *
                 * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                 * of certain opcodes, possibly making contracts go over the 2300 gas limit
                 * imposed by `transfer`, making them unable to receive funds via
                 * `transfer`. {sendValue} removes this limitation.
                 *
                 * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                 *
                 * IMPORTANT: because control is transferred to `recipient`, care must be
                 * taken to not create reentrancy vulnerabilities. Consider using
                 * {ReentrancyGuard} or the
                 * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    (bool success, ) = recipient.call{value: amount}("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
                /**
                 * @dev Performs a Solidity function call using a low level `call`. A
                 * plain `call` is an unsafe replacement for a function call: use this
                 * function instead.
                 *
                 * If `target` reverts with a revert reason, it is bubbled up by this
                 * function (like regular Solidity function calls).
                 *
                 * Returns the raw returned data. To convert to the expected return value,
                 * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                 *
                 * Requirements:
                 *
                 * - `target` must be a contract.
                 * - calling `target` with `data` must not revert.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                 * `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but also transferring `value` wei to `target`.
                 *
                 * Requirements:
                 *
                 * - the calling contract must have an ETH balance of at least `value`.
                 * - the called Solidity function must be `payable`.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(address(this).balance >= value, "Address: insufficient balance for call");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    return functionStaticCall(target, data, "Address: low-level static call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                 * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                 *
                 * _Available since v4.8._
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    if (success) {
                        if (returndata.length == 0) {
                            // only check isContract if the call was successful and the return data is empty
                            // otherwise we already know that it was a contract
                            require(isContract(target), "Address: call to non-contract");
                        }
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason or using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                function _revert(bytes memory returndata, string memory errorMessage) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
            pragma solidity ^0.8.0;
            import "./IERC165Upgradeable.sol";
            import "../../proxy/utils/Initializable.sol";
            /**
             * @dev Implementation of the {IERC165} interface.
             *
             * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
             * for the additional interface id that will be supported. For example:
             *
             * ```solidity
             * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
             *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
             * }
             * ```
             *
             * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
             */
            abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
                function __ERC165_init() internal onlyInitializing {
                }
                function __ERC165_init_unchained() internal onlyInitializing {
                }
                /**
                 * @dev See {IERC165-supportsInterface}.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                    return interfaceId == type(IERC165Upgradeable).interfaceId;
                }
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[50] private __gap;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC165 standard, as defined in the
             * https://eips.ethereum.org/EIPS/eip-165[EIP].
             *
             * Implementers can declare support of contract interfaces, which can then be
             * queried by others ({ERC165Checker}).
             *
             * For an implementation, see {ERC165}.
             */
            interface IERC165Upgradeable {
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30 000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) external view returns (bool);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Optimized and flexible operator filterer to abide to OpenSea's
            /// mandatory on-chain royalty enforcement in order for new collections to
            /// receive royalties.
            /// For more information, see:
            /// See: https://github.com/ProjectOpenSea/operator-filter-registry
            abstract contract OperatorFilterer {
                /// @dev The default OpenSea operator blocklist subscription.
                address internal constant _DEFAULT_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6;
                /// @dev The OpenSea operator filter registry.
                address internal constant _OPERATOR_FILTER_REGISTRY = 0x000000000000AAeB6D7670E522A718067333cd4E;
                /// @dev Registers the current contract to OpenSea's operator filter,
                /// and subscribe to the default OpenSea operator blocklist.
                /// Note: Will not revert nor update existing settings for repeated registration.
                function _registerForOperatorFiltering() internal virtual {
                    _registerForOperatorFiltering(_DEFAULT_SUBSCRIPTION, true);
                }
                /// @dev Registers the current contract to OpenSea's operator filter.
                /// Note: Will not revert nor update existing settings for repeated registration.
                function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe)
                    internal
                    virtual
                {
                    /// @solidity memory-safe-assembly
                    assembly {
                        let functionSelector := 0x7d3e3dbe // `registerAndSubscribe(address,address)`.
                        // Clean the upper 96 bits of `subscriptionOrRegistrantToCopy` in case they are dirty.
                        subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy))
                        for {} iszero(subscribe) {} {
                            if iszero(subscriptionOrRegistrantToCopy) {
                                functionSelector := 0x4420e486 // `register(address)`.
                                break
                            }
                            functionSelector := 0xa0af2903 // `registerAndCopyEntries(address,address)`.
                            break
                        }
                        // Store the function selector.
                        mstore(0x00, shl(224, functionSelector))
                        // Store the `address(this)`.
                        mstore(0x04, address())
                        // Store the `subscriptionOrRegistrantToCopy`.
                        mstore(0x24, subscriptionOrRegistrantToCopy)
                        // Register into the registry.
                        if iszero(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x04)) {
                            // If the function selector has not been overwritten,
                            // it is an out-of-gas error.
                            if eq(shr(224, mload(0x00)), functionSelector) {
                                // To prevent gas under-estimation.
                                revert(0, 0)
                            }
                        }
                        // Restore the part of the free memory pointer that was overwritten,
                        // which is guaranteed to be zero, because of Solidity's memory size limits.
                        mstore(0x24, 0)
                    }
                }
                /// @dev Modifier to guard a function and revert if the caller is a blocked operator.
                modifier onlyAllowedOperator(address from) virtual {
                    if (from != msg.sender) {
                        if (!_isPriorityOperator(msg.sender)) {
                            if (_operatorFilteringEnabled()) _revertIfBlocked(msg.sender);
                        }
                    }
                    _;
                }
                /// @dev Modifier to guard a function from approving a blocked operator..
                modifier onlyAllowedOperatorApproval(address operator) virtual {
                    if (!_isPriorityOperator(operator)) {
                        if (_operatorFilteringEnabled()) _revertIfBlocked(operator);
                    }
                    _;
                }
                /// @dev Helper function that reverts if the `operator` is blocked by the registry.
                function _revertIfBlocked(address operator) private view {
                    /// @solidity memory-safe-assembly
                    assembly {
                        // Store the function selector of `isOperatorAllowed(address,address)`,
                        // shifted left by 6 bytes, which is enough for 8tb of memory.
                        // We waste 6-3 = 3 bytes to save on 6 runtime gas (PUSH1 0x224 SHL).
                        mstore(0x00, 0xc6171134001122334455)
                        // Store the `address(this)`.
                        mstore(0x1a, address())
                        // Store the `operator`.
                        mstore(0x3a, operator)
                        // `isOperatorAllowed` always returns true if it does not revert.
                        if iszero(staticcall(gas(), _OPERATOR_FILTER_REGISTRY, 0x16, 0x44, 0x00, 0x00)) {
                            // Bubble up the revert if the staticcall reverts.
                            returndatacopy(0x00, 0x00, returndatasize())
                            revert(0x00, returndatasize())
                        }
                        // We'll skip checking if `from` is inside the blacklist.
                        // Even though that can block transferring out of wrapper contracts,
                        // we don't want tokens to be stuck.
                        // Restore the part of the free memory pointer that was overwritten,
                        // which is guaranteed to be zero, if less than 8tb of memory is used.
                        mstore(0x3a, 0)
                    }
                }
                /// @dev For deriving contracts to override, so that operator filtering
                /// can be turned on / off.
                /// Returns true by default.
                function _operatorFilteringEnabled() internal view virtual returns (bool) {
                    return true;
                }
                /// @dev For deriving contracts to override, so that preferred marketplaces can
                /// skip operator filtering, helping users save gas.
                /// Returns false for all inputs by default.
                function _isPriorityOperator(address) internal view virtual returns (bool) {
                    return false;
                }
            }
            // SPDX-License-Identifier: MIT
            // Archetype v0.5.1
            //
            //        d8888                 888               888
            //       d88888                 888               888
            //      d88P888                 888               888
            //     d88P 888 888d888 .d8888b 88888b.   .d88b.  888888 888  888 88888b.   .d88b.
            //    d88P  888 888P"  d88P"    888 "88b d8P  Y8b 888    888  888 888 "88b d8P  Y8b
            //   d88P   888 888    888      888  888 88888888 888    888  888 888  888 88888888
            //  d8888888888 888    Y88b.    888  888 Y8b.     Y88b.  Y88b 888 888 d88P Y8b.
            // d88P     888 888     "Y8888P 888  888  "Y8888   "Y888  "Y88888 88888P"   "Y8888
            //                                                            888 888
            //                                                       Y8b d88P 888
            //                                                        "Y88P"  888
            pragma solidity ^0.8.4;
            import "./ArchetypeLogic.sol";
            import "erc721a-upgradeable/contracts/ERC721AUpgradeable.sol";
            import "erc721a-upgradeable/contracts/ERC721A__Initializable.sol";
            import "./ERC721A__OwnableUpgradeable.sol";
            import "solady/src/utils/LibString.sol";
            import "closedsea/src/OperatorFilterer.sol";
            import "@openzeppelin/contracts-upgradeable/token/common/ERC2981Upgradeable.sol";
            contract Archetype is
              ERC721A__Initializable,
              ERC721AUpgradeable,
              OperatorFilterer,
              ERC721A__OwnableUpgradeable,
              ERC2981Upgradeable
            {
              //
              // EVENTS
              //
              event Invited(bytes32 indexed key, bytes32 indexed cid);
              event Referral(address indexed affiliate, address token, uint128 wad, uint256 numMints);
              event Withdrawal(address indexed src, address token, uint128 wad);
              //
              // VARIABLES
              //
              mapping(bytes32 => DutchInvite) public invites;
              mapping(address => mapping(bytes32 => uint256)) private _minted;
              mapping(bytes32 => uint256) private _listSupply;
              mapping(address => OwnerBalance) private _ownerBalance;
              mapping(address => mapping(address => uint128)) private _affiliateBalance;
              mapping(uint256 => bytes) private _tokenMsg;
              Config public config;
              BurnConfig public burnConfig;
              Options public options;
              string public provenance;
              //
              // METHODS
              //
              function initialize(
                string memory name,
                string memory symbol,
                Config calldata config_,
                address _receiver
              ) external initializerERC721A {
                __ERC721A_init(name, symbol);
                // check max bps not reached and min platform fee.
                if (
                  config_.affiliateFee > MAXBPS ||
                  config_.platformFee > MAXBPS ||
                  config_.platformFee < 500 ||
                  config_.discounts.affiliateDiscount > MAXBPS ||
                  config_.affiliateSigner == address(0) ||
                  config_.maxBatchSize == 0
                ) {
                  revert InvalidConfig();
                }
                // ensure mint tiers are correctly ordered from highest to lowest.
                for (uint256 i = 1; i < config_.discounts.mintTiers.length; i++) {
                  if (
                    config_.discounts.mintTiers[i].mintDiscount > MAXBPS ||
                    config_.discounts.mintTiers[i].numMints > config_.discounts.mintTiers[i - 1].numMints
                  ) {
                    revert InvalidConfig();
                  }
                }
                config = config_;
                __Ownable_init();
                if (config.ownerAltPayout != address(0)) {
                  setDefaultRoyalty(config.ownerAltPayout, config.defaultRoyalty);
                } else {
                  setDefaultRoyalty(_receiver, config.defaultRoyalty);
                }
              }
              //
              // PUBLIC
              //
              function mint(
                Auth calldata auth,
                uint256 quantity,
                address affiliate,
                bytes calldata signature
              ) external payable {
                mintTo(auth, quantity, msg.sender, affiliate, signature);
              }
              function batchMintTo(
                Auth calldata auth,
                address[] calldata toList,
                uint256[] calldata quantityList,
                address affiliate,
                bytes calldata signature
              ) external payable {
                if (quantityList.length != toList.length) {
                  revert InvalidConfig();
                }
                DutchInvite storage invite = invites[auth.key];
                uint256 quantity = 0;
                {
                  uint32 unitSize = invite.unitSize;
                  for (uint256 i = 0; i < quantityList.length; i++) {
                    if (unitSize > 1) {
                      quantity += quantityList[i] * unitSize;
                    } else {
                      quantity += quantityList[i];
                    }
                  }
                }
                uint256 curSupply = _totalMinted();
                ArchetypeLogic.validateMint(
                  invite,
                  config,
                  auth,
                  quantity,
                  owner(),
                  affiliate,
                  curSupply,
                  _minted,
                  _listSupply,
                  signature
                );
                {
                  uint32 unitSize = invite.unitSize;
                  for (uint256 i = 0; i < toList.length; i++) {
                    if (unitSize > 1) {
                      _mint(toList[i], quantityList[i] * unitSize);
                    } else {
                      _mint(toList[i], quantityList[i]);
                    }
                  }
                }
                if (invite.limit < invite.maxSupply) {
                  _minted[msg.sender][auth.key] += quantity;
                }
                if (invite.maxSupply < config.maxSupply) {
                  _listSupply[auth.key] += quantity;
                }
                ArchetypeLogic.updateBalances(
                  invite,
                  config,
                  _ownerBalance,
                  _affiliateBalance,
                  affiliate,
                  quantity
                );
              }
              function mintTo(
                Auth calldata auth,
                uint256 quantity,
                address to,
                address affiliate,
                bytes calldata signature
              ) public payable {
                DutchInvite storage i = invites[auth.key];
                if (i.unitSize > 1) {
                  quantity = quantity * i.unitSize;
                }
                uint256 curSupply = _totalMinted();
                ArchetypeLogic.validateMint(
                  i,
                  config,
                  auth,
                  quantity,
                  owner(),
                  affiliate,
                  curSupply,
                  _minted,
                  _listSupply,
                  signature
                );
                _mint(to, quantity);
                if (i.limit < i.maxSupply) {
                  _minted[msg.sender][auth.key] += quantity;
                }
                if (i.maxSupply < config.maxSupply) {
                  _listSupply[auth.key] += quantity;
                }
                ArchetypeLogic.updateBalances(i, config, _ownerBalance, _affiliateBalance, affiliate, quantity);
              }
              function burnToMint(uint256[] calldata tokenIds) external {
                uint256 curSupply = _totalMinted();
                ArchetypeLogic.validateBurnToMint(config, burnConfig, tokenIds, curSupply, _minted);
                for (uint256 i = 0; i < tokenIds.length; i++) {
                  burnConfig.archetype.transferFrom(
                    msg.sender,
                    address(0x000000000000000000000000000000000000dEaD),
                    tokenIds[i]
                  );
                }
                uint256 quantity = burnConfig.reversed
                  ? tokenIds.length * burnConfig.ratio
                  : tokenIds.length / burnConfig.ratio;
                _mint(msg.sender, quantity);
                if (burnConfig.limit < config.maxSupply) {
                  _minted[msg.sender][bytes32("burn")] += quantity;
                }
              }
              function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                return
                  bytes(config.baseUri).length != 0
                    ? string(abi.encodePacked(config.baseUri, LibString.toString(tokenId)))
                    : "";
              }
              function withdraw() external {
                address[] memory tokens = new address[](1);
                tokens[0] = address(0);
                withdrawTokens(tokens);
              }
              function withdrawTokens(address[] memory tokens) public {
                ArchetypeLogic.withdrawTokens(config, _ownerBalance, _affiliateBalance, owner(), tokens);
              }
              function setTokenMsg(uint256 tokenId, string calldata message) external {
                if (msg.sender != ownerOf(tokenId)) {
                  revert NotTokenOwner();
                }
                _tokenMsg[tokenId] = bytes(message);
              }
              function getTokenMsg(uint256 tokenId) external view returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                return string(_tokenMsg[tokenId]);
              }
              function ownerBalance() external view returns (OwnerBalance memory) {
                return _ownerBalance[address(0)];
              }
              function ownerBalanceToken(address token) external view returns (OwnerBalance memory) {
                return _ownerBalance[token];
              }
              function affiliateBalance(address affiliate) external view returns (uint128) {
                return _affiliateBalance[affiliate][address(0)];
              }
              function affiliateBalanceToken(address affiliate, address token) external view returns (uint128) {
                return _affiliateBalance[affiliate][token];
              }
              function minted(address minter, bytes32 key) external view returns (uint256) {
                return _minted[minter][key];
              }
              function listSupply(bytes32 key) external view returns (uint256) {
                return _listSupply[key];
              }
              function platform() external pure returns (address) {
                return PLATFORM;
              }
              //
              // OWNER ONLY
              //
              function setBaseURI(string memory baseUri) external onlyOwner {
                if (options.uriLocked) {
                  revert LockedForever();
                }
                config.baseUri = baseUri;
              }
              /// @notice the password is "forever"
              function lockURI(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.uriLocked = true;
              }
              /// @notice the password is "forever"
              // max supply cannot subceed total supply. Be careful changing.
              function setMaxSupply(uint32 maxSupply, string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                if (options.maxSupplyLocked) {
                  revert LockedForever();
                }
                if (maxSupply < _totalMinted()) {
                  revert MaxSupplyExceeded();
                }
                config.maxSupply = maxSupply;
              }
              /// @notice the password is "forever"
              function lockMaxSupply(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.maxSupplyLocked = true;
              }
              function setAffiliateFee(uint16 affiliateFee) external onlyOwner {
                if (options.affiliateFeeLocked) {
                  revert LockedForever();
                }
                if (affiliateFee > MAXBPS) {
                  revert InvalidConfig();
                }
                config.affiliateFee = affiliateFee;
              }
              /// @notice the password is "forever"
              function lockAffiliateFee(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.affiliateFeeLocked = true;
              }
              function setDiscounts(Discount calldata discounts) external onlyOwner {
                if (options.discountsLocked) {
                  revert LockedForever();
                }
                if (discounts.affiliateDiscount > MAXBPS) {
                  revert InvalidConfig();
                }
                // ensure mint tiers are correctly ordered from highest to lowest.
                for (uint256 i = 1; i < discounts.mintTiers.length; i++) {
                  if (
                    discounts.mintTiers[i].mintDiscount > MAXBPS ||
                    discounts.mintTiers[i].numMints > discounts.mintTiers[i - 1].numMints
                  ) {
                    revert InvalidConfig();
                  }
                }
                config.discounts = discounts;
              }
              /// @notice the password is "forever"
              function lockDiscounts(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.discountsLocked = true;
              }
              /// @notice Set BAYC-style provenance once it's calculated
              function setProvenanceHash(string memory provenanceHash) external onlyOwner {
                if (options.provenanceHashLocked) {
                  revert LockedForever();
                }
                provenance = provenanceHash;
              }
              /// @notice the password is "forever"
              function lockProvenanceHash(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.provenanceHashLocked = true;
              }
              function setOwnerAltPayout(address ownerAltPayout) external onlyOwner {
                if (options.ownerAltPayoutLocked) {
                  revert LockedForever();
                }
                config.ownerAltPayout = ownerAltPayout;
              }
              /// @notice the password is "forever"
              function lockOwnerAltPayout(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.ownerAltPayoutLocked = true;
              }
              function setMaxBatchSize(uint32 maxBatchSize) external onlyOwner {
                config.maxBatchSize = maxBatchSize;
              }
              function setInvite(
                bytes32 _key,
                bytes32 _cid,
                Invite calldata _invite
              ) external onlyOwner {
                invites[_key] = DutchInvite({
                  price: _invite.price,
                  reservePrice: _invite.price,
                  delta: 0,
                  start: _invite.start,
                  end: _invite.end,
                  limit: _invite.limit,
                  maxSupply: _invite.maxSupply,
                  interval: 0,
                  unitSize: _invite.unitSize,
                  tokenAddress: _invite.tokenAddress
                });
                emit Invited(_key, _cid);
              }
              function setDutchInvite(
                bytes32 _key,
                bytes32 _cid,
                DutchInvite memory _dutchInvite
              ) external onlyOwner {
                if (_dutchInvite.start < block.timestamp) {
                  _dutchInvite.start = uint32(block.timestamp);
                }
                invites[_key] = _dutchInvite;
                emit Invited(_key, _cid);
              }
              function enableBurnToMint(
                address archetype,
                bool reversed,
                uint16 ratio,
                uint64 start,
                uint64 limit
              ) external onlyOwner {
                burnConfig = BurnConfig({
                  archetype: IERC721AUpgradeable(archetype),
                  enabled: true,
                  reversed: reversed,
                  ratio: ratio,
                  start: start,
                  limit: limit
                });
              }
              function disableBurnToMint() external onlyOwner {
                burnConfig = BurnConfig({
                  enabled: false,
                  reversed: false,
                  ratio: 0,
                  archetype: IERC721AUpgradeable(address(0)),
                  start: 0,
                  limit: 0
                });
              }
              //
              // PLATFORM ONLY
              //
              function setSuperAffiliatePayout(address superAffiliatePayout) external onlyPlatform {
                config.superAffiliatePayout = superAffiliatePayout;
              }
              //
              // INTERNAL
              //
              function _startTokenId() internal view virtual override returns (uint256) {
                return 1;
              }
              modifier onlyPlatform() {
                if (msg.sender != PLATFORM) {
                  revert NotPlatform();
                }
                _;
              }
              // OPTIONAL ROYALTY ENFORCEMENT WITH OPENSEA
              function enableRoyaltyEnforcement() external onlyOwner {
                if (options.royaltyEnforcementLocked) {
                  revert LockedForever();
                }
                _registerForOperatorFiltering();
                options.royaltyEnforcementEnabled = true;
              }
              function disableRoyaltyEnforcement() external onlyOwner {
                if (options.royaltyEnforcementLocked) {
                  revert LockedForever();
                }
                options.royaltyEnforcementEnabled = false;
              }
              /// @notice the password is "forever"
              function lockRoyaltyEnforcement(string memory password) external onlyOwner {
                if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) {
                  revert WrongPassword();
                }
                options.royaltyEnforcementLocked = true;
              }
              function setApprovalForAll(address operator, bool approved)
                public
                override
                onlyAllowedOperatorApproval(operator)
              {
                super.setApprovalForAll(operator, approved);
              }
              function approve(address operator, uint256 tokenId)
                public
                payable
                override
                onlyAllowedOperatorApproval(operator)
              {
                super.approve(operator, tokenId);
              }
              function transferFrom(
                address from,
                address to,
                uint256 tokenId
              ) public payable override onlyAllowedOperator(from) {
                super.transferFrom(from, to, tokenId);
              }
              function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId
              ) public payable override onlyAllowedOperator(from) {
                super.safeTransferFrom(from, to, tokenId);
              }
              function safeTransferFrom(
                address from,
                address to,
                uint256 tokenId,
                bytes memory data
              ) public payable override onlyAllowedOperator(from) {
                super.safeTransferFrom(from, to, tokenId, data);
              }
              function _operatorFilteringEnabled() internal view override returns (bool) {
                return options.royaltyEnforcementEnabled;
              }
              //ERC2981 ROYALTY
              function supportsInterface(bytes4 interfaceId)
                public
                view
                virtual
                override(ERC721AUpgradeable, ERC2981Upgradeable)
                returns (bool)
              {
                // Supports the following `interfaceId`s:
                // - IERC165: 0x01ffc9a7
                // - IERC721: 0x80ac58cd
                // - IERC721Metadata: 0x5b5e139f
                // - IERC2981: 0x2a55205a
                return
                  ERC721AUpgradeable.supportsInterface(interfaceId) ||
                  ERC2981Upgradeable.supportsInterface(interfaceId);
              }
              function setDefaultRoyalty(address receiver, uint16 feeNumerator) public onlyOwner {
                config.defaultRoyalty = feeNumerator;
                _setDefaultRoyalty(receiver, feeNumerator);
              }
            }
            // SPDX-License-Identifier: MIT
            // ArchetypeLogic v0.5.1
            //
            //        d8888                 888               888
            //       d88888                 888               888
            //      d88P888                 888               888
            //     d88P 888 888d888 .d8888b 88888b.   .d88b.  888888 888  888 88888b.   .d88b.
            //    d88P  888 888P"  d88P"    888 "88b d8P  Y8b 888    888  888 888 "88b d8P  Y8b
            //   d88P   888 888    888      888  888 88888888 888    888  888 888  888 88888888
            //  d8888888888 888    Y88b.    888  888 Y8b.     Y88b.  Y88b 888 888 d88P Y8b.
            // d88P     888 888     "Y8888P 888  888  "Y8888   "Y888  "Y88888 88888P"   "Y8888
            //                                                            888 888
            //                                                       Y8b d88P 888
            //                                                        "Y88P"  888
            pragma solidity ^0.8.4;
            import "erc721a-upgradeable/contracts/ERC721AUpgradeable.sol";
            import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
            import "solady/src/utils/MerkleProofLib.sol";
            import "solady/src/utils/ECDSA.sol";
            error InvalidConfig();
            error MintNotYetStarted();
            error MintEnded();
            error WalletUnauthorizedToMint();
            error InsufficientEthSent();
            error ExcessiveEthSent();
            error Erc20BalanceTooLow();
            error MaxSupplyExceeded();
            error ListMaxSupplyExceeded();
            error NumberOfMintsExceeded();
            error MintingPaused();
            error InvalidReferral();
            error InvalidSignature();
            error BalanceEmpty();
            error TransferFailed();
            error MaxBatchSizeExceeded();
            error BurnToMintDisabled();
            error NotTokenOwner();
            error NotPlatform();
            error NotApprovedToTransfer();
            error InvalidAmountOfTokens();
            error WrongPassword();
            error LockedForever();
            //
            // STRUCTS
            //
            struct Auth {
              bytes32 key;
              bytes32[] proof;
            }
            struct MintTier {
              uint16 numMints;
              uint16 mintDiscount; //BPS
            }
            struct Discount {
              uint16 affiliateDiscount; //BPS
              MintTier[] mintTiers;
            }
            struct Config {
              string baseUri;
              address affiliateSigner;
              address ownerAltPayout; // optional alternative address for owner withdrawals.
              address superAffiliatePayout; // optional super affiliate address, will receive half of platform fee if set.
              uint32 maxSupply;
              uint32 maxBatchSize;
              uint16 affiliateFee; //BPS
              uint16 platformFee; //BPS
              uint16 defaultRoyalty; //BPS
              Discount discounts;
            }
            struct Options {
              bool uriLocked;
              bool maxSupplyLocked;
              bool affiliateFeeLocked;
              bool discountsLocked;
              bool ownerAltPayoutLocked;
              bool royaltyEnforcementEnabled;
              bool royaltyEnforcementLocked;
              bool provenanceHashLocked;
            }
            struct DutchInvite {
              uint128 price;
              uint128 reservePrice;
              uint128 delta;
              uint32 start;
              uint32 end;
              uint32 limit;
              uint32 maxSupply;
              uint32 interval;
              uint32 unitSize; // mint 1 get x
              address tokenAddress;
            }
            struct Invite {
              uint128 price;
              uint32 start;
              uint32 end;
              uint32 limit;
              uint32 maxSupply;
              uint32 unitSize; // mint 1 get x
              address tokenAddress;
            }
            struct OwnerBalance {
              uint128 owner;
              uint128 platform;
            }
            struct BurnConfig {
              IERC721AUpgradeable archetype;
              bool enabled;
              bool reversed; // side of the ratio (false=burn {ratio} get 1, true=burn 1 get {ratio})
              uint16 ratio;
              uint64 start;
              uint64 limit;
            }
            // address constant PLATFORM = 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC; // TEST (account[2])
            address constant PLATFORM = 0x86B82972282Dd22348374bC63fd21620F7ED847B;
            uint16 constant MAXBPS = 5000; // max fee or discount is 50%
            library ArchetypeLogic {
              //
              // EVENTS
              //
              event Invited(bytes32 indexed key, bytes32 indexed cid);
              event Referral(address indexed affiliate, address token, uint128 wad, uint256 numMints);
              event Withdrawal(address indexed src, address token, uint128 wad);
              // calculate price based on affiliate usage and mint discounts
              function computePrice(
                DutchInvite storage invite,
                Discount storage discounts,
                uint256 numTokens,
                bool affiliateUsed
              ) public view returns (uint256) {
                uint256 price = invite.price;
                if (invite.interval != 0) {
                  uint256 diff = (((block.timestamp - invite.start) / invite.interval) * invite.delta);
                  if (price > invite.reservePrice) {
                    if (diff > price - invite.reservePrice) {
                      price = invite.reservePrice;
                    } else {
                      price = price - diff;
                    }
                  } else if (price < invite.reservePrice) {
                    if (diff > invite.reservePrice - price) {
                      price = invite.reservePrice;
                    } else {
                      price = price + diff;
                    }
                  }
                }
                uint256 cost = price * numTokens;
                if (affiliateUsed) {
                  cost = cost - ((cost * discounts.affiliateDiscount) / 10000);
                }
                for (uint256 i = 0; i < discounts.mintTiers.length; i++) {
                  if (numTokens >= discounts.mintTiers[i].numMints) {
                    return cost = cost - ((cost * discounts.mintTiers[i].mintDiscount) / 10000);
                  }
                }
                return cost;
              }
              function validateMint(
                DutchInvite storage i,
                Config storage config,
                Auth calldata auth,
                uint256 quantity,
                address owner,
                address affiliate,
                uint256 curSupply,
                mapping(address => mapping(bytes32 => uint256)) storage minted,
                mapping(bytes32 => uint256) storage listSupply,
                bytes calldata signature
              ) public view {
                if (affiliate != address(0)) {
                  if (affiliate == PLATFORM || affiliate == owner || affiliate == msg.sender) {
                    revert InvalidReferral();
                  }
                  validateAffiliate(affiliate, signature, config.affiliateSigner);
                }
                if (i.limit == 0) {
                  revert MintingPaused();
                }
                if (!verify(auth, i.tokenAddress, msg.sender)) {
                  revert WalletUnauthorizedToMint();
                }
                if (block.timestamp < i.start) {
                  revert MintNotYetStarted();
                }
                if (i.end > i.start && block.timestamp > i.end) {
                  revert MintEnded();
                }
                if (i.limit < i.maxSupply) {
                  uint256 totalAfterMint = minted[msg.sender][auth.key] + quantity;
                  if (totalAfterMint > i.limit) {
                    revert NumberOfMintsExceeded();
                  }
                }
                if (i.maxSupply < config.maxSupply) {
                  uint256 totalAfterMint = listSupply[auth.key] + quantity;
                  if (totalAfterMint > i.maxSupply) {
                    revert ListMaxSupplyExceeded();
                  }
                }
                if (quantity > config.maxBatchSize) {
                  revert MaxBatchSizeExceeded();
                }
                if ((curSupply + quantity) > config.maxSupply) {
                  revert MaxSupplyExceeded();
                }
                uint256 cost = computePrice(i, config.discounts, quantity, affiliate != address(0));
                if (i.tokenAddress != address(0)) {
                  IERC20Upgradeable erc20Token = IERC20Upgradeable(i.tokenAddress);
                  if (erc20Token.allowance(msg.sender, address(this)) < cost) {
                    revert NotApprovedToTransfer();
                  }
                  if (erc20Token.balanceOf(msg.sender) < cost) {
                    revert Erc20BalanceTooLow();
                  }
                  if (msg.value != 0) {
                    revert ExcessiveEthSent();
                  }
                } else {
                  if (msg.value < cost) {
                    revert InsufficientEthSent();
                  }
                  if (msg.value > cost) {
                    revert ExcessiveEthSent();
                  }
                }
              }
              function validateBurnToMint(
                Config storage config,
                BurnConfig storage burnConfig,
                uint256[] calldata tokenIds,
                uint256 curSupply,
                mapping(address => mapping(bytes32 => uint256)) storage minted
              ) public view {
                if (!burnConfig.enabled) {
                  revert BurnToMintDisabled();
                }
                if (block.timestamp < burnConfig.start) {
                  revert MintNotYetStarted();
                }
                // check if msg.sender owns tokens and has correct approvals
                for (uint256 i = 0; i < tokenIds.length; i++) {
                  if (burnConfig.archetype.ownerOf(tokenIds[i]) != msg.sender) {
                    revert NotTokenOwner();
                  }
                }
                if (!burnConfig.archetype.isApprovedForAll(msg.sender, address(this))) {
                  revert NotApprovedToTransfer();
                }
                uint256 quantity;
                if (burnConfig.reversed) {
                  quantity = tokenIds.length * burnConfig.ratio;
                } else {
                  if (tokenIds.length % burnConfig.ratio != 0) {
                    revert InvalidAmountOfTokens();
                  }
                  quantity = tokenIds.length / burnConfig.ratio;
                }
                if (quantity > config.maxBatchSize) {
                  revert MaxBatchSizeExceeded();
                }
                if (burnConfig.limit < config.maxSupply) {
                  uint256 totalAfterMint = minted[msg.sender][bytes32("burn")] + quantity;
                  if (totalAfterMint > burnConfig.limit) {
                    revert NumberOfMintsExceeded();
                  }
                }
                if ((curSupply + quantity) > config.maxSupply) {
                  revert MaxSupplyExceeded();
                }
              }
              function updateBalances(
                DutchInvite storage i,
                Config storage config,
                mapping(address => OwnerBalance) storage _ownerBalance,
                mapping(address => mapping(address => uint128)) storage _affiliateBalance,
                address affiliate,
                uint256 quantity
              ) public {
                address tokenAddress = i.tokenAddress;
                uint128 value = uint128(msg.value);
                if (tokenAddress != address(0)) {
                  value = uint128(computePrice(i, config.discounts, quantity, affiliate != address(0)));
                }
                uint128 affiliateWad = 0;
                if (affiliate != address(0)) {
                  affiliateWad = (value * config.affiliateFee) / 10000;
                  _affiliateBalance[affiliate][tokenAddress] += affiliateWad;
                  emit Referral(affiliate, tokenAddress, affiliateWad, quantity);
                }
                uint128 superAffiliateWad = 0;
                if (config.superAffiliatePayout != address(0)) {
                  superAffiliateWad = ((value * config.platformFee) / 2) / 10000;
                  _affiliateBalance[config.superAffiliatePayout][tokenAddress] += superAffiliateWad;
                }
                OwnerBalance memory balance = _ownerBalance[tokenAddress];
                uint128 platformWad = ((value * config.platformFee) / 10000) - superAffiliateWad;
                uint128 ownerWad = value - affiliateWad - platformWad - superAffiliateWad;
                _ownerBalance[tokenAddress] = OwnerBalance({
                  owner: balance.owner + ownerWad,
                  platform: balance.platform + platformWad
                });
                if (tokenAddress != address(0)) {
                  IERC20Upgradeable erc20Token = IERC20Upgradeable(tokenAddress);
                  erc20Token.transferFrom(msg.sender, address(this), value);
                }
              }
              function withdrawTokens(
                Config storage config,
                mapping(address => OwnerBalance) storage _ownerBalance,
                mapping(address => mapping(address => uint128)) storage _affiliateBalance,
                address owner,
                address[] calldata tokens
              ) public {
                for (uint256 i = 0; i < tokens.length; i++) {
                  address tokenAddress = tokens[i];
                  uint128 wad = 0;
                  if (msg.sender == owner || msg.sender == config.ownerAltPayout || msg.sender == PLATFORM) {
                    OwnerBalance storage balance = _ownerBalance[tokenAddress];
                    if (msg.sender == owner || msg.sender == config.ownerAltPayout) {
                      wad = balance.owner;
                      balance.owner = 0;
                    } else {
                      wad = balance.platform;
                      balance.platform = 0;
                    }
                  } else {
                    wad = _affiliateBalance[msg.sender][tokenAddress];
                    _affiliateBalance[msg.sender][tokenAddress] = 0;
                  }
                  if (wad == 0) {
                    revert BalanceEmpty();
                  }
                  if (tokenAddress == address(0)) {
                    bool success = false;
                    // send to ownerAltPayout if set and owner is withdrawing
                    if (msg.sender == owner && config.ownerAltPayout != address(0)) {
                      (success, ) = payable(config.ownerAltPayout).call{ value: wad }("");
                    } else {
                      (success, ) = msg.sender.call{ value: wad }("");
                    }
                    if (!success) {
                      revert TransferFailed();
                    }
                  } else {
                    IERC20Upgradeable erc20Token = IERC20Upgradeable(tokenAddress);
                    if (msg.sender == owner && config.ownerAltPayout != address(0)) {
                      erc20Token.transfer(config.ownerAltPayout, wad);
                    } else {
                      erc20Token.transfer(msg.sender, wad);
                    }
                  }
                  emit Withdrawal(msg.sender, tokenAddress, wad);
                }
              }
              function validateAffiliate(
                address affiliate,
                bytes calldata signature,
                address affiliateSigner
              ) public view {
                bytes32 signedMessagehash = ECDSA.toEthSignedMessageHash(
                  keccak256(abi.encodePacked(affiliate))
                );
                address signer = ECDSA.recover(signedMessagehash, signature);
                if (signer != affiliateSigner) {
                  revert InvalidSignature();
                }
              }
              function verify(
                Auth calldata auth,
                address tokenAddress,
                address account
              ) public pure returns (bool) {
                // keys 0-255 and tokenAddress are public
                if (uint256(auth.key) <= 0xff || auth.key == keccak256(abi.encodePacked(tokenAddress))) {
                  return true;
                }
                return MerkleProofLib.verify(auth.proof, auth.key, keccak256(abi.encodePacked(account)));
              }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
            import 'erc721a-upgradeable/contracts/ERC721A__Initializable.sol';
            import 'erc721a-upgradeable/contracts/ERC721AUpgradeable.sol';
            pragma solidity ^0.8.4;
            /**
             * @dev Contract module which provides a basic access control mechanism, where
             * there is an account (an owner) that can be granted exclusive access to
             * specific functions.
             *
             * By default, the owner account will be the one that deploys the contract. This
             * can later be changed with {transferOwnership}.
             *
             * This module is used through inheritance. It will make available the modifier
             * `onlyOwner`, which can be applied to your functions to restrict their use to
             * the owner.
             */
            abstract contract ERC721A__OwnableUpgradeable is ERC721A__Initializable, ERC721AUpgradeable {
                address private _owner;
                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                /**
                 * @dev Initializes the contract setting the deployer as the initial owner.
                 */
                function __Ownable_init() internal onlyInitializingERC721A {
                    __Ownable_init_unchained();
                }
                function __Ownable_init_unchained() internal onlyInitializingERC721A {
                    _transferOwnership(_msgSenderERC721A());
                }
                /**
                 * @dev Returns the address of the current owner.
                 */
                function owner() public view virtual returns (address) {
                    return _owner;
                }
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                    _isOwner();
                    _;
                }
                function _isOwner() internal view {
                    require(owner() == _msgSenderERC721A(), "Ownable: caller is not the owner");
                }
                /**
                 * @dev Leaves the contract without owner. It will not be possible to call
                 * `onlyOwner` functions anymore. Can only be called by the current owner.
                 *
                 * NOTE: Renouncing ownership will leave the contract without an owner,
                 * thereby removing any functionality that is only available to the owner.
                 */
                function renounceOwnership() public virtual onlyOwner {
                    _transferOwnership(address(0));
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Can only be called by the current owner.
                 */
                function transferOwnership(address newOwner) public virtual onlyOwner {
                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                    _transferOwnership(newOwner);
                }
                /**
                 * @dev Transfers ownership of the contract to a new account (`newOwner`).
                 * Internal function without access restriction.
                 */
                function _transferOwnership(address newOwner) internal virtual {
                    address oldOwner = _owner;
                    _owner = newOwner;
                    emit OwnershipTransferred(oldOwner, newOwner);
                }
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[49] private __gap;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /**
             * @dev This is a base contract to aid in writing upgradeable diamond facet contracts, or any kind of contract that will be deployed
             * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
             * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
             * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
             *
             * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
             * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
             *
             * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
             * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
             */
            import {ERC721A__InitializableStorage} from './ERC721A__InitializableStorage.sol';
            abstract contract ERC721A__Initializable {
                using ERC721A__InitializableStorage for ERC721A__InitializableStorage.Layout;
                /**
                 * @dev Modifier to protect an initializer function from being invoked twice.
                 */
                modifier initializerERC721A() {
                    // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                    // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                    // contract may have been reentered.
                    require(
                        ERC721A__InitializableStorage.layout()._initializing
                            ? _isConstructor()
                            : !ERC721A__InitializableStorage.layout()._initialized,
                        'ERC721A__Initializable: contract is already initialized'
                    );
                    bool isTopLevelCall = !ERC721A__InitializableStorage.layout()._initializing;
                    if (isTopLevelCall) {
                        ERC721A__InitializableStorage.layout()._initializing = true;
                        ERC721A__InitializableStorage.layout()._initialized = true;
                    }
                    _;
                    if (isTopLevelCall) {
                        ERC721A__InitializableStorage.layout()._initializing = false;
                    }
                }
                /**
                 * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                 * {initializer} modifier, directly or indirectly.
                 */
                modifier onlyInitializingERC721A() {
                    require(
                        ERC721A__InitializableStorage.layout()._initializing,
                        'ERC721A__Initializable: contract is not initializing'
                    );
                    _;
                }
                /// @dev Returns true if and only if the function is running in the constructor
                function _isConstructor() private view returns (bool) {
                    // extcodesize checks the size of the code stored in an address, and
                    // address returns the current address. Since the code is still not
                    // deployed when running a constructor, any checks on its code size will
                    // yield zero, making it an effective way to detect if a contract is
                    // under construction or not.
                    address self = address(this);
                    uint256 cs;
                    assembly {
                        cs := extcodesize(self)
                    }
                    return cs == 0;
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            /**
             * @dev This is a base storage for the  initialization function for upgradeable diamond facet contracts
             **/
            library ERC721A__InitializableStorage {
                struct Layout {
                    /*
                     * Indicates that the contract has been initialized.
                     */
                    bool _initialized;
                    /*
                     * Indicates that the contract is in the process of being initialized.
                     */
                    bool _initializing;
                }
                bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.initializable.facet');
                function layout() internal pure returns (Layout storage l) {
                    bytes32 slot = STORAGE_SLOT;
                    assembly {
                        l.slot := slot
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            library ERC721AStorage {
                // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
                struct TokenApprovalRef {
                    address value;
                }
                struct Layout {
                    // =============================================================
                    //                            STORAGE
                    // =============================================================
                    // The next token ID to be minted.
                    uint256 _currentIndex;
                    // The number of tokens burned.
                    uint256 _burnCounter;
                    // Token name
                    string _name;
                    // Token symbol
                    string _symbol;
                    // Mapping from token ID to ownership details
                    // An empty struct value does not necessarily mean the token is unowned.
                    // See {_packedOwnershipOf} implementation for details.
                    //
                    // Bits Layout:
                    // - [0..159]   `addr`
                    // - [160..223] `startTimestamp`
                    // - [224]      `burned`
                    // - [225]      `nextInitialized`
                    // - [232..255] `extraData`
                    mapping(uint256 => uint256) _packedOwnerships;
                    // Mapping owner address to address data.
                    //
                    // Bits Layout:
                    // - [0..63]    `balance`
                    // - [64..127]  `numberMinted`
                    // - [128..191] `numberBurned`
                    // - [192..255] `aux`
                    mapping(address => uint256) _packedAddressData;
                    // Mapping from token ID to approved address.
                    mapping(uint256 => ERC721AStorage.TokenApprovalRef) _tokenApprovals;
                    // Mapping from owner to operator approvals
                    mapping(address => mapping(address => bool)) _operatorApprovals;
                }
                bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.ERC721A');
                function layout() internal pure returns (Layout storage l) {
                    bytes32 slot = STORAGE_SLOT;
                    assembly {
                        l.slot := slot
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // ERC721A Contracts v4.2.3
            // Creator: Chiru Labs
            pragma solidity ^0.8.4;
            import './IERC721AUpgradeable.sol';
            import {ERC721AStorage} from './ERC721AStorage.sol';
            import './ERC721A__Initializable.sol';
            /**
             * @dev Interface of ERC721 token receiver.
             */
            interface ERC721A__IERC721ReceiverUpgradeable {
                function onERC721Received(
                    address operator,
                    address from,
                    uint256 tokenId,
                    bytes calldata data
                ) external returns (bytes4);
            }
            /**
             * @title ERC721A
             *
             * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
             * Non-Fungible Token Standard, including the Metadata extension.
             * Optimized for lower gas during batch mints.
             *
             * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
             * starting from `_startTokenId()`.
             *
             * Assumptions:
             *
             * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
             * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
             */
            contract ERC721AUpgradeable is ERC721A__Initializable, IERC721AUpgradeable {
                using ERC721AStorage for ERC721AStorage.Layout;
                // =============================================================
                //                           CONSTANTS
                // =============================================================
                // Mask of an entry in packed address data.
                uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
                // The bit position of `numberMinted` in packed address data.
                uint256 private constant _BITPOS_NUMBER_MINTED = 64;
                // The bit position of `numberBurned` in packed address data.
                uint256 private constant _BITPOS_NUMBER_BURNED = 128;
                // The bit position of `aux` in packed address data.
                uint256 private constant _BITPOS_AUX = 192;
                // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
                uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
                // The bit position of `startTimestamp` in packed ownership.
                uint256 private constant _BITPOS_START_TIMESTAMP = 160;
                // The bit mask of the `burned` bit in packed ownership.
                uint256 private constant _BITMASK_BURNED = 1 << 224;
                // The bit position of the `nextInitialized` bit in packed ownership.
                uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
                // The bit mask of the `nextInitialized` bit in packed ownership.
                uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
                // The bit position of `extraData` in packed ownership.
                uint256 private constant _BITPOS_EXTRA_DATA = 232;
                // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
                uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
                // The mask of the lower 160 bits for addresses.
                uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
                // The maximum `quantity` that can be minted with {_mintERC2309}.
                // This limit is to prevent overflows on the address data entries.
                // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
                // is required to cause an overflow, which is unrealistic.
                uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
                // The `Transfer` event signature is given by:
                // `keccak256(bytes("Transfer(address,address,uint256)"))`.
                bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
                    0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
                // =============================================================
                //                          CONSTRUCTOR
                // =============================================================
                function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                    __ERC721A_init_unchained(name_, symbol_);
                }
                function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
                    ERC721AStorage.layout()._name = name_;
                    ERC721AStorage.layout()._symbol = symbol_;
                    ERC721AStorage.layout()._currentIndex = _startTokenId();
                }
                // =============================================================
                //                   TOKEN COUNTING OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the starting token ID.
                 * To change the starting token ID, please override this function.
                 */
                function _startTokenId() internal view virtual returns (uint256) {
                    return 0;
                }
                /**
                 * @dev Returns the next token ID to be minted.
                 */
                function _nextTokenId() internal view virtual returns (uint256) {
                    return ERC721AStorage.layout()._currentIndex;
                }
                /**
                 * @dev Returns the total number of tokens in existence.
                 * Burned tokens will reduce the count.
                 * To get the total number of tokens minted, please see {_totalMinted}.
                 */
                function totalSupply() public view virtual override returns (uint256) {
                    // Counter underflow is impossible as _burnCounter cannot be incremented
                    // more than `_currentIndex - _startTokenId()` times.
                    unchecked {
                        return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId();
                    }
                }
                /**
                 * @dev Returns the total amount of tokens minted in the contract.
                 */
                function _totalMinted() internal view virtual returns (uint256) {
                    // Counter underflow is impossible as `_currentIndex` does not decrement,
                    // and it is initialized to `_startTokenId()`.
                    unchecked {
                        return ERC721AStorage.layout()._currentIndex - _startTokenId();
                    }
                }
                /**
                 * @dev Returns the total number of tokens burned.
                 */
                function _totalBurned() internal view virtual returns (uint256) {
                    return ERC721AStorage.layout()._burnCounter;
                }
                // =============================================================
                //                    ADDRESS DATA OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the number of tokens in `owner`'s account.
                 */
                function balanceOf(address owner) public view virtual override returns (uint256) {
                    if (owner == address(0)) revert BalanceQueryForZeroAddress();
                    return ERC721AStorage.layout()._packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
                }
                /**
                 * Returns the number of tokens minted by `owner`.
                 */
                function _numberMinted(address owner) internal view returns (uint256) {
                    return
                        (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
                }
                /**
                 * Returns the number of tokens burned by or on behalf of `owner`.
                 */
                function _numberBurned(address owner) internal view returns (uint256) {
                    return
                        (ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
                }
                /**
                 * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
                 */
                function _getAux(address owner) internal view returns (uint64) {
                    return uint64(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_AUX);
                }
                /**
                 * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
                 * If there are multiple variables, please pack them into a uint64.
                 */
                function _setAux(address owner, uint64 aux) internal virtual {
                    uint256 packed = ERC721AStorage.layout()._packedAddressData[owner];
                    uint256 auxCasted;
                    // Cast `aux` with assembly to avoid redundant masking.
                    assembly {
                        auxCasted := aux
                    }
                    packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
                    ERC721AStorage.layout()._packedAddressData[owner] = packed;
                }
                // =============================================================
                //                            IERC165
                // =============================================================
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                    // The interface IDs are constants representing the first 4 bytes
                    // of the XOR of all function selectors in the interface.
                    // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
                    // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
                    return
                        interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
                        interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
                        interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
                }
                // =============================================================
                //                        IERC721Metadata
                // =============================================================
                /**
                 * @dev Returns the token collection name.
                 */
                function name() public view virtual override returns (string memory) {
                    return ERC721AStorage.layout()._name;
                }
                /**
                 * @dev Returns the token collection symbol.
                 */
                function symbol() public view virtual override returns (string memory) {
                    return ERC721AStorage.layout()._symbol;
                }
                /**
                 * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
                 */
                function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                    if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                    string memory baseURI = _baseURI();
                    return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
                }
                /**
                 * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
                 * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
                 * by default, it can be overridden in child contracts.
                 */
                function _baseURI() internal view virtual returns (string memory) {
                    return '';
                }
                // =============================================================
                //                     OWNERSHIPS OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the owner of the `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function ownerOf(uint256 tokenId) public view virtual override returns (address) {
                    return address(uint160(_packedOwnershipOf(tokenId)));
                }
                /**
                 * @dev Gas spent here starts off proportional to the maximum mint batch size.
                 * It gradually moves to O(1) as tokens get transferred around over time.
                 */
                function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
                    return _unpackedOwnership(_packedOwnershipOf(tokenId));
                }
                /**
                 * @dev Returns the unpacked `TokenOwnership` struct at `index`.
                 */
                function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
                    return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]);
                }
                /**
                 * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
                 */
                function _initializeOwnershipAt(uint256 index) internal virtual {
                    if (ERC721AStorage.layout()._packedOwnerships[index] == 0) {
                        ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(index);
                    }
                }
                /**
                 * Returns the packed ownership data of `tokenId`.
                 */
                function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
                    if (_startTokenId() <= tokenId) {
                        packed = ERC721AStorage.layout()._packedOwnerships[tokenId];
                        // If not burned.
                        if (packed & _BITMASK_BURNED == 0) {
                            // If the data at the starting slot does not exist, start the scan.
                            if (packed == 0) {
                                if (tokenId >= ERC721AStorage.layout()._currentIndex) revert OwnerQueryForNonexistentToken();
                                // Invariant:
                                // There will always be an initialized ownership slot
                                // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                                // before an unintialized ownership slot
                                // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                                // Hence, `tokenId` will not underflow.
                                //
                                // We can directly compare the packed value.
                                // If the address is zero, packed will be zero.
                                for (;;) {
                                    unchecked {
                                        packed = ERC721AStorage.layout()._packedOwnerships[--tokenId];
                                    }
                                    if (packed == 0) continue;
                                    return packed;
                                }
                            }
                            // Otherwise, the data exists and is not burned. We can skip the scan.
                            // This is possible because we have already achieved the target condition.
                            // This saves 2143 gas on transfers of initialized tokens.
                            return packed;
                        }
                    }
                    revert OwnerQueryForNonexistentToken();
                }
                /**
                 * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
                 */
                function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
                    ownership.addr = address(uint160(packed));
                    ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
                    ownership.burned = packed & _BITMASK_BURNED != 0;
                    ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
                }
                /**
                 * @dev Packs ownership data into a single uint256.
                 */
                function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
                    assembly {
                        // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        owner := and(owner, _BITMASK_ADDRESS)
                        // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
                        result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
                    }
                }
                /**
                 * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
                 */
                function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
                    // For branchless setting of the `nextInitialized` flag.
                    assembly {
                        // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
                        result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
                    }
                }
                // =============================================================
                //                      APPROVAL OPERATIONS
                // =============================================================
                /**
                 * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
                 *
                 * Requirements:
                 *
                 * - The caller must own the token or be an approved operator.
                 */
                function approve(address to, uint256 tokenId) public payable virtual override {
                    _approve(to, tokenId, true);
                }
                /**
                 * @dev Returns the account approved for `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function getApproved(uint256 tokenId) public view virtual override returns (address) {
                    if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
                    return ERC721AStorage.layout()._tokenApprovals[tokenId].value;
                }
                /**
                 * @dev Approve or remove `operator` as an operator for the caller.
                 * Operators can call {transferFrom} or {safeTransferFrom}
                 * for any token owned by the caller.
                 *
                 * Requirements:
                 *
                 * - The `operator` cannot be the caller.
                 *
                 * Emits an {ApprovalForAll} event.
                 */
                function setApprovalForAll(address operator, bool approved) public virtual override {
                    ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][operator] = approved;
                    emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
                }
                /**
                 * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
                 *
                 * See {setApprovalForAll}.
                 */
                function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
                    return ERC721AStorage.layout()._operatorApprovals[owner][operator];
                }
                /**
                 * @dev Returns whether `tokenId` exists.
                 *
                 * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
                 *
                 * Tokens start existing when they are minted. See {_mint}.
                 */
                function _exists(uint256 tokenId) internal view virtual returns (bool) {
                    return
                        _startTokenId() <= tokenId &&
                        tokenId < ERC721AStorage.layout()._currentIndex && // If within bounds,
                        ERC721AStorage.layout()._packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
                }
                /**
                 * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
                 */
                function _isSenderApprovedOrOwner(
                    address approvedAddress,
                    address owner,
                    address msgSender
                ) private pure returns (bool result) {
                    assembly {
                        // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        owner := and(owner, _BITMASK_ADDRESS)
                        // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
                        msgSender := and(msgSender, _BITMASK_ADDRESS)
                        // `msgSender == owner || msgSender == approvedAddress`.
                        result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
                    }
                }
                /**
                 * @dev Returns the storage slot and value for the approved address of `tokenId`.
                 */
                function _getApprovedSlotAndAddress(uint256 tokenId)
                    private
                    view
                    returns (uint256 approvedAddressSlot, address approvedAddress)
                {
                    ERC721AStorage.TokenApprovalRef storage tokenApproval = ERC721AStorage.layout()._tokenApprovals[tokenId];
                    // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
                    assembly {
                        approvedAddressSlot := tokenApproval.slot
                        approvedAddress := sload(approvedAddressSlot)
                    }
                }
                // =============================================================
                //                      TRANSFER OPERATIONS
                // =============================================================
                /**
                 * @dev Transfers `tokenId` from `from` to `to`.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token
                 * by either {approve} or {setApprovalForAll}.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) public payable virtual override {
                    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                    if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
                    (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                    // The nested ifs save around 20+ gas over a compound boolean condition.
                    if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                        if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                    if (to == address(0)) revert TransferToZeroAddress();
                    _beforeTokenTransfers(from, to, tokenId, 1);
                    // Clear approvals from the previous owner.
                    assembly {
                        if approvedAddress {
                            // This is equivalent to `delete _tokenApprovals[tokenId]`.
                            sstore(approvedAddressSlot, 0)
                        }
                    }
                    // Underflow of the sender's balance is impossible because we check for
                    // ownership above and the recipient's balance can't realistically overflow.
                    // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                    unchecked {
                        // We can directly increment and decrement the balances.
                        --ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`.
                        ++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`.
                        // Updates:
                        // - `address` to the next owner.
                        // - `startTimestamp` to the timestamp of transfering.
                        // - `burned` to `false`.
                        // - `nextInitialized` to `true`.
                        ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                            to,
                            _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
                        );
                        // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                        if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                            uint256 nextTokenId = tokenId + 1;
                            // If the next slot's address is zero and not burned (i.e. packed value is zero).
                            if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                                // If the next slot is within bounds.
                                if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                    // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                    ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                                }
                            }
                        }
                    }
                    emit Transfer(from, to, tokenId);
                    _afterTokenTransfers(from, to, tokenId, 1);
                }
                /**
                 * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) public payable virtual override {
                    safeTransferFrom(from, to, tokenId, '');
                }
                /**
                 * @dev Safely transfers `tokenId` token from `from` to `to`.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must exist and be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token
                 * by either {approve} or {setApprovalForAll}.
                 * - If `to` refers to a smart contract, it must implement
                 * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                 *
                 * Emits a {Transfer} event.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                ) public payable virtual override {
                    transferFrom(from, to, tokenId);
                    if (to.code.length != 0)
                        if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                            revert TransferToNonERC721ReceiverImplementer();
                        }
                }
                /**
                 * @dev Hook that is called before a set of serially-ordered token IDs
                 * are about to be transferred. This includes minting.
                 * And also called before burning one token.
                 *
                 * `startTokenId` - the first token ID to be transferred.
                 * `quantity` - the amount to be transferred.
                 *
                 * Calling conditions:
                 *
                 * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
                 * transferred to `to`.
                 * - When `from` is zero, `tokenId` will be minted for `to`.
                 * - When `to` is zero, `tokenId` will be burned by `from`.
                 * - `from` and `to` are never both zero.
                 */
                function _beforeTokenTransfers(
                    address from,
                    address to,
                    uint256 startTokenId,
                    uint256 quantity
                ) internal virtual {}
                /**
                 * @dev Hook that is called after a set of serially-ordered token IDs
                 * have been transferred. This includes minting.
                 * And also called after one token has been burned.
                 *
                 * `startTokenId` - the first token ID to be transferred.
                 * `quantity` - the amount to be transferred.
                 *
                 * Calling conditions:
                 *
                 * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
                 * transferred to `to`.
                 * - When `from` is zero, `tokenId` has been minted for `to`.
                 * - When `to` is zero, `tokenId` has been burned by `from`.
                 * - `from` and `to` are never both zero.
                 */
                function _afterTokenTransfers(
                    address from,
                    address to,
                    uint256 startTokenId,
                    uint256 quantity
                ) internal virtual {}
                /**
                 * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
                 *
                 * `from` - Previous owner of the given token ID.
                 * `to` - Target address that will receive the token.
                 * `tokenId` - Token ID to be transferred.
                 * `_data` - Optional data to send along with the call.
                 *
                 * Returns whether the call correctly returned the expected magic value.
                 */
                function _checkContractOnERC721Received(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                ) private returns (bool) {
                    try
                        ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data)
                    returns (bytes4 retval) {
                        return retval == ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received.selector;
                    } catch (bytes memory reason) {
                        if (reason.length == 0) {
                            revert TransferToNonERC721ReceiverImplementer();
                        } else {
                            assembly {
                                revert(add(32, reason), mload(reason))
                            }
                        }
                    }
                }
                // =============================================================
                //                        MINT OPERATIONS
                // =============================================================
                /**
                 * @dev Mints `quantity` tokens and transfers them to `to`.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - `quantity` must be greater than 0.
                 *
                 * Emits a {Transfer} event for each mint.
                 */
                function _mint(address to, uint256 quantity) internal virtual {
                    uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                    if (quantity == 0) revert MintZeroQuantity();
                    _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                    // Overflows are incredibly unrealistic.
                    // `balance` and `numberMinted` have a maximum limit of 2**64.
                    // `tokenId` has a maximum limit of 2**256.
                    unchecked {
                        // Updates:
                        // - `balance += quantity`.
                        // - `numberMinted += quantity`.
                        //
                        // We can directly add to the `balance` and `numberMinted`.
                        ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                        // Updates:
                        // - `address` to the owner.
                        // - `startTimestamp` to the timestamp of minting.
                        // - `burned` to `false`.
                        // - `nextInitialized` to `quantity == 1`.
                        ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                            to,
                            _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                        );
                        uint256 toMasked;
                        uint256 end = startTokenId + quantity;
                        // Use assembly to loop and emit the `Transfer` event for gas savings.
                        // The duplicated `log4` removes an extra check and reduces stack juggling.
                        // The assembly, together with the surrounding Solidity code, have been
                        // delicately arranged to nudge the compiler into producing optimized opcodes.
                        assembly {
                            // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                            toMasked := and(to, _BITMASK_ADDRESS)
                            // Emit the `Transfer` event.
                            log4(
                                0, // Start of data (0, since no data).
                                0, // End of data (0, since no data).
                                _TRANSFER_EVENT_SIGNATURE, // Signature.
                                0, // `address(0)`.
                                toMasked, // `to`.
                                startTokenId // `tokenId`.
                            )
                            // The `iszero(eq(,))` check ensures that large values of `quantity`
                            // that overflows uint256 will make the loop run out of gas.
                            // The compiler will optimize the `iszero` away for performance.
                            for {
                                let tokenId := add(startTokenId, 1)
                            } iszero(eq(tokenId, end)) {
                                tokenId := add(tokenId, 1)
                            } {
                                // Emit the `Transfer` event. Similar to above.
                                log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                            }
                        }
                        if (toMasked == 0) revert MintToZeroAddress();
                        ERC721AStorage.layout()._currentIndex = end;
                    }
                    _afterTokenTransfers(address(0), to, startTokenId, quantity);
                }
                /**
                 * @dev Mints `quantity` tokens and transfers them to `to`.
                 *
                 * This function is intended for efficient minting only during contract creation.
                 *
                 * It emits only one {ConsecutiveTransfer} as defined in
                 * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
                 * instead of a sequence of {Transfer} event(s).
                 *
                 * Calling this function outside of contract creation WILL make your contract
                 * non-compliant with the ERC721 standard.
                 * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
                 * {ConsecutiveTransfer} event is only permissible during contract creation.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - `quantity` must be greater than 0.
                 *
                 * Emits a {ConsecutiveTransfer} event.
                 */
                function _mintERC2309(address to, uint256 quantity) internal virtual {
                    uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
                    if (to == address(0)) revert MintToZeroAddress();
                    if (quantity == 0) revert MintZeroQuantity();
                    if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
                    _beforeTokenTransfers(address(0), to, startTokenId, quantity);
                    // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
                    unchecked {
                        // Updates:
                        // - `balance += quantity`.
                        // - `numberMinted += quantity`.
                        //
                        // We can directly add to the `balance` and `numberMinted`.
                        ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                        // Updates:
                        // - `address` to the owner.
                        // - `startTimestamp` to the timestamp of minting.
                        // - `burned` to `false`.
                        // - `nextInitialized` to `quantity == 1`.
                        ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
                            to,
                            _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                        );
                        emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
                        ERC721AStorage.layout()._currentIndex = startTokenId + quantity;
                    }
                    _afterTokenTransfers(address(0), to, startTokenId, quantity);
                }
                /**
                 * @dev Safely mints `quantity` tokens and transfers them to `to`.
                 *
                 * Requirements:
                 *
                 * - If `to` refers to a smart contract, it must implement
                 * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
                 * - `quantity` must be greater than 0.
                 *
                 * See {_mint}.
                 *
                 * Emits a {Transfer} event for each mint.
                 */
                function _safeMint(
                    address to,
                    uint256 quantity,
                    bytes memory _data
                ) internal virtual {
                    _mint(to, quantity);
                    unchecked {
                        if (to.code.length != 0) {
                            uint256 end = ERC721AStorage.layout()._currentIndex;
                            uint256 index = end - quantity;
                            do {
                                if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                                    revert TransferToNonERC721ReceiverImplementer();
                                }
                            } while (index < end);
                            // Reentrancy protection.
                            if (ERC721AStorage.layout()._currentIndex != end) revert();
                        }
                    }
                }
                /**
                 * @dev Equivalent to `_safeMint(to, quantity, '')`.
                 */
                function _safeMint(address to, uint256 quantity) internal virtual {
                    _safeMint(to, quantity, '');
                }
                // =============================================================
                //                       APPROVAL OPERATIONS
                // =============================================================
                /**
                 * @dev Equivalent to `_approve(to, tokenId, false)`.
                 */
                function _approve(address to, uint256 tokenId) internal virtual {
                    _approve(to, tokenId, false);
                }
                /**
                 * @dev Gives permission to `to` to transfer `tokenId` token to another account.
                 * The approval is cleared when the token is transferred.
                 *
                 * Only a single account can be approved at a time, so approving the
                 * zero address clears previous approvals.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 *
                 * Emits an {Approval} event.
                 */
                function _approve(
                    address to,
                    uint256 tokenId,
                    bool approvalCheck
                ) internal virtual {
                    address owner = ownerOf(tokenId);
                    if (approvalCheck)
                        if (_msgSenderERC721A() != owner)
                            if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                                revert ApprovalCallerNotOwnerNorApproved();
                            }
                    ERC721AStorage.layout()._tokenApprovals[tokenId].value = to;
                    emit Approval(owner, to, tokenId);
                }
                // =============================================================
                //                        BURN OPERATIONS
                // =============================================================
                /**
                 * @dev Equivalent to `_burn(tokenId, false)`.
                 */
                function _burn(uint256 tokenId) internal virtual {
                    _burn(tokenId, false);
                }
                /**
                 * @dev Destroys `tokenId`.
                 * The approval is cleared when the token is burned.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 *
                 * Emits a {Transfer} event.
                 */
                function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
                    uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
                    address from = address(uint160(prevOwnershipPacked));
                    (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
                    if (approvalCheck) {
                        // The nested ifs save around 20+ gas over a compound boolean condition.
                        if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                            if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
                    }
                    _beforeTokenTransfers(from, address(0), tokenId, 1);
                    // Clear approvals from the previous owner.
                    assembly {
                        if approvedAddress {
                            // This is equivalent to `delete _tokenApprovals[tokenId]`.
                            sstore(approvedAddressSlot, 0)
                        }
                    }
                    // Underflow of the sender's balance is impossible because we check for
                    // ownership above and the recipient's balance can't realistically overflow.
                    // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
                    unchecked {
                        // Updates:
                        // - `balance -= 1`.
                        // - `numberBurned += 1`.
                        //
                        // We can directly decrement the balance, and increment the number burned.
                        // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
                        ERC721AStorage.layout()._packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
                        // Updates:
                        // - `address` to the last owner.
                        // - `startTimestamp` to the timestamp of burning.
                        // - `burned` to `true`.
                        // - `nextInitialized` to `true`.
                        ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
                            from,
                            (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
                        );
                        // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                        if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                            uint256 nextTokenId = tokenId + 1;
                            // If the next slot's address is zero and not burned (i.e. packed value is zero).
                            if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
                                // If the next slot is within bounds.
                                if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
                                    // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                                    ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
                                }
                            }
                        }
                    }
                    emit Transfer(from, address(0), tokenId);
                    _afterTokenTransfers(from, address(0), tokenId, 1);
                    // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
                    unchecked {
                        ERC721AStorage.layout()._burnCounter++;
                    }
                }
                // =============================================================
                //                     EXTRA DATA OPERATIONS
                // =============================================================
                /**
                 * @dev Directly sets the extra data for the ownership data `index`.
                 */
                function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
                    uint256 packed = ERC721AStorage.layout()._packedOwnerships[index];
                    if (packed == 0) revert OwnershipNotInitializedForExtraData();
                    uint256 extraDataCasted;
                    // Cast `extraData` with assembly to avoid redundant masking.
                    assembly {
                        extraDataCasted := extraData
                    }
                    packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
                    ERC721AStorage.layout()._packedOwnerships[index] = packed;
                }
                /**
                 * @dev Called during each token transfer to set the 24bit `extraData` field.
                 * Intended to be overridden by the cosumer contract.
                 *
                 * `previousExtraData` - the value of `extraData` before transfer.
                 *
                 * Calling conditions:
                 *
                 * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
                 * transferred to `to`.
                 * - When `from` is zero, `tokenId` will be minted for `to`.
                 * - When `to` is zero, `tokenId` will be burned by `from`.
                 * - `from` and `to` are never both zero.
                 */
                function _extraData(
                    address from,
                    address to,
                    uint24 previousExtraData
                ) internal view virtual returns (uint24) {}
                /**
                 * @dev Returns the next extra data for the packed ownership data.
                 * The returned result is shifted into position.
                 */
                function _nextExtraData(
                    address from,
                    address to,
                    uint256 prevOwnershipPacked
                ) private view returns (uint256) {
                    uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
                    return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
                }
                // =============================================================
                //                       OTHER OPERATIONS
                // =============================================================
                /**
                 * @dev Returns the message sender (defaults to `msg.sender`).
                 *
                 * If you are writing GSN compatible contracts, you need to override this function.
                 */
                function _msgSenderERC721A() internal view virtual returns (address) {
                    return msg.sender;
                }
                /**
                 * @dev Converts a uint256 to its ASCII string decimal representation.
                 */
                function _toString(uint256 value) internal pure virtual returns (string memory str) {
                    assembly {
                        // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                        // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                        // We will need 1 word for the trailing zeros padding, 1 word for the length,
                        // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                        let m := add(mload(0x40), 0xa0)
                        // Update the free memory pointer to allocate.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end of the memory to calculate the length later.
                        let end := str
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 1)
                            // Write the character to the pointer.
                            // The ASCII index of the '0' character is 48.
                            mstore8(str, add(48, mod(temp, 10)))
                            // Keep dividing `temp` until zero.
                            temp := div(temp, 10)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        let length := sub(end, str)
                        // Move the pointer 32 bytes leftwards to make room for the length.
                        str := sub(str, 0x20)
                        // Store the length.
                        mstore(str, length)
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // ERC721A Contracts v4.2.3
            // Creator: Chiru Labs
            pragma solidity ^0.8.4;
            /**
             * @dev Interface of ERC721A.
             */
            interface IERC721AUpgradeable {
                /**
                 * The caller must own the token or be an approved operator.
                 */
                error ApprovalCallerNotOwnerNorApproved();
                /**
                 * The token does not exist.
                 */
                error ApprovalQueryForNonexistentToken();
                /**
                 * Cannot query the balance for the zero address.
                 */
                error BalanceQueryForZeroAddress();
                /**
                 * Cannot mint to the zero address.
                 */
                error MintToZeroAddress();
                /**
                 * The quantity of tokens minted must be more than zero.
                 */
                error MintZeroQuantity();
                /**
                 * The token does not exist.
                 */
                error OwnerQueryForNonexistentToken();
                /**
                 * The caller must own the token or be an approved operator.
                 */
                error TransferCallerNotOwnerNorApproved();
                /**
                 * The token must be owned by `from`.
                 */
                error TransferFromIncorrectOwner();
                /**
                 * Cannot safely transfer to a contract that does not implement the
                 * ERC721Receiver interface.
                 */
                error TransferToNonERC721ReceiverImplementer();
                /**
                 * Cannot transfer to the zero address.
                 */
                error TransferToZeroAddress();
                /**
                 * The token does not exist.
                 */
                error URIQueryForNonexistentToken();
                /**
                 * The `quantity` minted with ERC2309 exceeds the safety limit.
                 */
                error MintERC2309QuantityExceedsLimit();
                /**
                 * The `extraData` cannot be set on an unintialized ownership slot.
                 */
                error OwnershipNotInitializedForExtraData();
                // =============================================================
                //                            STRUCTS
                // =============================================================
                struct TokenOwnership {
                    // The address of the owner.
                    address addr;
                    // Stores the start time of ownership with minimal overhead for tokenomics.
                    uint64 startTimestamp;
                    // Whether the token has been burned.
                    bool burned;
                    // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
                    uint24 extraData;
                }
                // =============================================================
                //                         TOKEN COUNTERS
                // =============================================================
                /**
                 * @dev Returns the total number of tokens in existence.
                 * Burned tokens will reduce the count.
                 * To get the total number of tokens minted, please see {_totalMinted}.
                 */
                function totalSupply() external view returns (uint256);
                // =============================================================
                //                            IERC165
                // =============================================================
                /**
                 * @dev Returns true if this contract implements the interface defined by
                 * `interfaceId`. See the corresponding
                 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
                 * to learn more about how these ids are created.
                 *
                 * This function call must use less than 30000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) external view returns (bool);
                // =============================================================
                //                            IERC721
                // =============================================================
                /**
                 * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
                 */
                event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
                /**
                 * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
                 */
                event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
                /**
                 * @dev Emitted when `owner` enables or disables
                 * (`approved`) `operator` to manage all of its assets.
                 */
                event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
                /**
                 * @dev Returns the number of tokens in `owner`'s account.
                 */
                function balanceOf(address owner) external view returns (uint256 balance);
                /**
                 * @dev Returns the owner of the `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function ownerOf(uint256 tokenId) external view returns (address owner);
                /**
                 * @dev Safely transfers `tokenId` token from `from` to `to`,
                 * checking first that contract recipients are aware of the ERC721 protocol
                 * to prevent tokens from being forever locked.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must exist and be owned by `from`.
                 * - If the caller is not `from`, it must be have been allowed to move
                 * this token by either {approve} or {setApprovalForAll}.
                 * - If `to` refers to a smart contract, it must implement
                 * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                 *
                 * Emits a {Transfer} event.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes calldata data
                ) external payable;
                /**
                 * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) external payable;
                /**
                 * @dev Transfers `tokenId` from `from` to `to`.
                 *
                 * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
                 * whenever possible.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must be owned by `from`.
                 * - If the caller is not `from`, it must be approved to move this token
                 * by either {approve} or {setApprovalForAll}.
                 *
                 * Emits a {Transfer} event.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) external payable;
                /**
                 * @dev Gives permission to `to` to transfer `tokenId` token to another account.
                 * The approval is cleared when the token is transferred.
                 *
                 * Only a single account can be approved at a time, so approving the
                 * zero address clears previous approvals.
                 *
                 * Requirements:
                 *
                 * - The caller must own the token or be an approved operator.
                 * - `tokenId` must exist.
                 *
                 * Emits an {Approval} event.
                 */
                function approve(address to, uint256 tokenId) external payable;
                /**
                 * @dev Approve or remove `operator` as an operator for the caller.
                 * Operators can call {transferFrom} or {safeTransferFrom}
                 * for any token owned by the caller.
                 *
                 * Requirements:
                 *
                 * - The `operator` cannot be the caller.
                 *
                 * Emits an {ApprovalForAll} event.
                 */
                function setApprovalForAll(address operator, bool _approved) external;
                /**
                 * @dev Returns the account approved for `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function getApproved(uint256 tokenId) external view returns (address operator);
                /**
                 * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
                 *
                 * See {setApprovalForAll}.
                 */
                function isApprovedForAll(address owner, address operator) external view returns (bool);
                // =============================================================
                //                        IERC721Metadata
                // =============================================================
                /**
                 * @dev Returns the token collection name.
                 */
                function name() external view returns (string memory);
                /**
                 * @dev Returns the token collection symbol.
                 */
                function symbol() external view returns (string memory);
                /**
                 * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
                 */
                function tokenURI(uint256 tokenId) external view returns (string memory);
                // =============================================================
                //                           IERC2309
                // =============================================================
                /**
                 * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
                 * (inclusive) is transferred from `from` to `to`, as defined in the
                 * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
                 *
                 * See {_mintERC2309} for more details.
                 */
                event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Gas optimized ECDSA wrapper.
            /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol)
            /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol)
            /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol)
            library ECDSA {
                function recover(bytes32 hash, bytes calldata signature) internal view returns (address result) {
                    assembly {
                        if eq(signature.length, 65) {
                            // Copy the free memory pointer so that we can restore it later.
                            let m := mload(0x40)
                            // Directly copy `r` and `s` from the calldata.
                            calldatacopy(0x40, signature.offset, 0x40)
                            // If `s` in lower half order, such that the signature is not malleable.
                            // prettier-ignore
                            if iszero(gt(mload(0x60), 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) {
                                mstore(0x00, hash)
                                // Compute `v` and store it in the scratch space.
                                mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40))))
                                pop(
                                    staticcall(
                                        gas(), // Amount of gas left for the transaction.
                                        0x01, // Address of `ecrecover`.
                                        0x00, // Start of input.
                                        0x80, // Size of input.
                                        0x40, // Start of output.
                                        0x20 // Size of output.
                                    )
                                )
                                // Restore the zero slot.
                                mstore(0x60, 0)
                                // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
                                result := mload(sub(0x60, returndatasize()))
                            }
                            // Restore the free memory pointer.
                            mstore(0x40, m)
                        }
                    }
                }
                function recover(
                    bytes32 hash,
                    bytes32 r,
                    bytes32 vs
                ) internal view returns (address result) {
                    assembly {
                        // Copy the free memory pointer so that we can restore it later.
                        let m := mload(0x40)
                        // prettier-ignore
                        let s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                        // If `s` in lower half order, such that the signature is not malleable.
                        // prettier-ignore
                        if iszero(gt(s, 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)) {
                            mstore(0x00, hash)
                            mstore(0x20, add(shr(255, vs), 27))
                            mstore(0x40, r)
                            mstore(0x60, s)
                            pop(
                                staticcall(
                                    gas(), // Amount of gas left for the transaction.
                                    0x01, // Address of `ecrecover`.
                                    0x00, // Start of input.
                                    0x80, // Size of input.
                                    0x40, // Start of output.
                                    0x20 // Size of output.
                                )
                            )
                            // Restore the zero slot.
                            mstore(0x60, 0)
                            // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
                            result := mload(sub(0x60, returndatasize()))
                        }
                        // Restore the free memory pointer.
                        mstore(0x40, m)
                    }
                }
                function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
                    assembly {
                        // Store into scratch space for keccak256.
                        mstore(0x20, hash)
                        mstore(0x00, "\\x00\\x00\\x00\\x00\\x19Ethereum Signed Message:\
            32")
                        // 0x40 - 0x04 = 0x3c
                        result := keccak256(0x04, 0x3c)
                    }
                }
                function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
                    assembly {
                        // We need at most 128 bytes for Ethereum signed message header.
                        // The max length of the ASCII reprenstation of a uint256 is 78 bytes.
                        // The length of "\\x19Ethereum Signed Message:\
            " is 26 bytes (i.e. 0x1a).
                        // The next multiple of 32 above 78 + 26 is 128 (i.e. 0x80).
                        // Instead of allocating, we temporarily copy the 128 bytes before the
                        // start of `s` data to some variables.
                        let m3 := mload(sub(s, 0x60))
                        let m2 := mload(sub(s, 0x40))
                        let m1 := mload(sub(s, 0x20))
                        // The length of `s` is in bytes.
                        let sLength := mload(s)
                        let ptr := add(s, 0x20)
                        // `end` marks the end of the memory which we will compute the keccak256 of.
                        let end := add(ptr, sLength)
                        // Convert the length of the bytes to ASCII decimal representation
                        // and store it into the memory.
                        // prettier-ignore
                        for { let temp := sLength } 1 {} {
                            ptr := sub(ptr, 1)
                            mstore8(ptr, add(48, mod(temp, 10)))
                            temp := div(temp, 10)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        // Copy the header over to the memory.
                        mstore(sub(ptr, 0x20), "\\x00\\x00\\x00\\x00\\x00\\x00\\x19Ethereum Signed Message:\
            ")
                        // Compute the keccak256 of the memory.
                        result := keccak256(sub(ptr, 0x1a), sub(end, sub(ptr, 0x1a)))
                        // Restore the previous memory.
                        mstore(s, sLength)
                        mstore(sub(s, 0x20), m1)
                        mstore(sub(s, 0x40), m2)
                        mstore(sub(s, 0x60), m3)
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Library for converting numbers into strings and other string operations.
            /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
            /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
            library LibString {
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                        CUSTOM ERRORS                       */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                error HexLengthInsufficient();
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                     DECIMAL OPERATIONS                     */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                function toString(uint256 value) internal pure returns (string memory str) {
                    assembly {
                        // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                        // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                        // We will need 1 word for the trailing zeros padding, 1 word for the length,
                        // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                        let m := add(mload(0x40), 0xa0)
                        // Update the free memory pointer to allocate.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end of the memory to calculate the length later.
                        let end := str
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 1)
                            // Write the character to the pointer.
                            // The ASCII index of the '0' character is 48.
                            mstore8(str, add(48, mod(temp, 10)))
                            // Keep dividing `temp` until zero.
                            temp := div(temp, 10)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        let length := sub(end, str)
                        // Move the pointer 32 bytes leftwards to make room for the length.
                        str := sub(str, 0x20)
                        // Store the length.
                        mstore(str, length)
                    }
                }
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                   HEXADECIMAL OPERATIONS                   */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {
                    assembly {
                        let start := mload(0x40)
                        // We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes
                        // for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
                        // We add 0x20 to the total and round down to a multiple of 0x20.
                        // (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
                        let m := add(start, and(add(shl(1, length), 0x62), not(0x1f)))
                        // Allocate the memory.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end to calculate the length later.
                        let end := str
                        // Store "0123456789abcdef" in scratch space.
                        mstore(0x0f, 0x30313233343536373839616263646566)
                        let temp := value
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for {} 1 {} {
                            str := sub(str, 2)
                            mstore8(add(str, 1), mload(and(temp, 15)))
                            mstore8(str, mload(and(shr(4, temp), 15)))
                            temp := shr(8, temp)
                            length := sub(length, 1)
                            // prettier-ignore
                            if iszero(length) { break }
                        }
                        if temp {
                            // Store the function selector of `HexLengthInsufficient()`.
                            mstore(0x00, 0x2194895a)
                            // Revert with (offset, size).
                            revert(0x1c, 0x04)
                        }
                        // Compute the string's length.
                        let strLength := add(sub(end, str), 2)
                        // Move the pointer and write the "0x" prefix.
                        str := sub(str, 0x20)
                        mstore(str, 0x3078)
                        // Move the pointer and write the length.
                        str := sub(str, 2)
                        mstore(str, strLength)
                    }
                }
                function toHexString(uint256 value) internal pure returns (string memory str) {
                    assembly {
                        let start := mload(0x40)
                        // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
                        // 0x02 bytes for the prefix, and 0x40 bytes for the digits.
                        // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
                        let m := add(start, 0xa0)
                        // Allocate the memory.
                        mstore(0x40, m)
                        // Assign the `str` to the end.
                        str := sub(m, 0x20)
                        // Zeroize the slot after the string.
                        mstore(str, 0)
                        // Cache the end to calculate the length later.
                        let end := str
                        // Store "0123456789abcdef" in scratch space.
                        mstore(0x0f, 0x30313233343536373839616263646566)
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 2)
                            mstore8(add(str, 1), mload(and(temp, 15)))
                            mstore8(str, mload(and(shr(4, temp), 15)))
                            temp := shr(8, temp)
                            // prettier-ignore
                            if iszero(temp) { break }
                        }
                        // Compute the string's length.
                        let strLength := add(sub(end, str), 2)
                        // Move the pointer and write the "0x" prefix.
                        str := sub(str, 0x20)
                        mstore(str, 0x3078)
                        // Move the pointer and write the length.
                        str := sub(str, 2)
                        mstore(str, strLength)
                    }
                }
                function toHexString(address value) internal pure returns (string memory str) {
                    assembly {
                        let start := mload(0x40)
                        // We need 0x20 bytes for the length, 0x02 bytes for the prefix,
                        // and 0x28 bytes for the digits.
                        // The next multiple of 0x20 above (0x20 + 0x02 + 0x28) is 0x60.
                        str := add(start, 0x60)
                        // Allocate the memory.
                        mstore(0x40, str)
                        // Store "0123456789abcdef" in scratch space.
                        mstore(0x0f, 0x30313233343536373839616263646566)
                        let length := 20
                        // We write the string from rightmost digit to leftmost digit.
                        // The following is essentially a do-while loop that also handles the zero case.
                        // prettier-ignore
                        for { let temp := value } 1 {} {
                            str := sub(str, 2)
                            mstore8(add(str, 1), mload(and(temp, 15)))
                            mstore8(str, mload(and(shr(4, temp), 15)))
                            temp := shr(8, temp)
                            length := sub(length, 1)
                            // prettier-ignore
                            if iszero(length) { break }
                        }
                        // Move the pointer and write the "0x" prefix.
                        str := sub(str, 32)
                        mstore(str, 0x3078)
                        // Move the pointer and write the length.
                        str := sub(str, 2)
                        mstore(str, 42)
                    }
                }
                /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                /*                   OTHER STRING OPERATIONS                  */
                /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                function replace(
                    string memory subject,
                    string memory search,
                    string memory replacement
                ) internal pure returns (string memory result) {
                    assembly {
                        let subjectLength := mload(subject)
                        let searchLength := mload(search)
                        let replacementLength := mload(replacement)
                        subject := add(subject, 0x20)
                        search := add(search, 0x20)
                        replacement := add(replacement, 0x20)
                        result := add(mload(0x40), 0x20)
                        let subjectEnd := add(subject, subjectLength)
                        if iszero(gt(searchLength, subjectLength)) {
                            let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
                            let h := 0
                            if iszero(lt(searchLength, 32)) {
                                h := keccak256(search, searchLength)
                            }
                            let m := shl(3, sub(32, and(searchLength, 31)))
                            let s := mload(search)
                            // prettier-ignore
                            for {} 1 {} {
                                let t := mload(subject)
                                // Whether the first `searchLength % 32` bytes of 
                                // `subject` and `search` matches.
                                if iszero(shr(m, xor(t, s))) {
                                    if h {
                                        if iszero(eq(keccak256(subject, searchLength), h)) {
                                            mstore(result, t)
                                            result := add(result, 1)
                                            subject := add(subject, 1)
                                            // prettier-ignore
                                            if iszero(lt(subject, subjectSearchEnd)) { break }
                                            continue
                                        }
                                    }
                                    // Copy the `replacement` one word at a time.
                                    // prettier-ignore
                                    for { let o := 0 } 1 {} {
                                        mstore(add(result, o), mload(add(replacement, o)))
                                        o := add(o, 0x20)
                                        // prettier-ignore
                                        if iszero(lt(o, replacementLength)) { break }
                                    }
                                    result := add(result, replacementLength)
                                    subject := add(subject, searchLength)    
                                    if iszero(searchLength) {
                                        mstore(result, t)
                                        result := add(result, 1)
                                        subject := add(subject, 1)
                                    }
                                    // prettier-ignore
                                    if iszero(lt(subject, subjectSearchEnd)) { break }
                                    continue
                                }
                                mstore(result, t)
                                result := add(result, 1)
                                subject := add(subject, 1)
                                // prettier-ignore
                                if iszero(lt(subject, subjectSearchEnd)) { break }
                            }
                        }
                        let resultRemainder := result
                        result := add(mload(0x40), 0x20)
                        let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))
                        // Copy the rest of the string one word at a time.
                        // prettier-ignore
                        for {} lt(subject, subjectEnd) {} {
                            mstore(resultRemainder, mload(subject))
                            resultRemainder := add(resultRemainder, 0x20)
                            subject := add(subject, 0x20)
                        }
                        // Allocate memory for the length and the bytes,
                        // rounded up to a multiple of 32.
                        mstore(0x40, add(result, and(add(k, 0x40), not(0x1f))))
                        result := sub(result, 0x20)
                        mstore(result, k)
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.4;
            /// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree.
            /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)
            /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)
            /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol)
            library MerkleProofLib {
                function verify(
                    bytes32[] calldata proof,
                    bytes32 root,
                    bytes32 leaf
                ) internal pure returns (bool isValid) {
                    assembly {
                        if proof.length {
                            // Left shift by 5 is equivalent to multiplying by 0x20.
                            let end := add(proof.offset, shl(5, proof.length))
                            // Initialize `offset` to the offset of `proof` in the calldata.
                            let offset := proof.offset
                            // Iterate over proof elements to compute root hash.
                            // prettier-ignore
                            for {} 1 {} {
                                // Slot of `leaf` in scratch space.
                                // If the condition is true: 0x20, otherwise: 0x00.
                                let scratch := shl(5, gt(leaf, calldataload(offset)))
                                // Store elements to hash contiguously in scratch space.
                                // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
                                mstore(scratch, leaf)
                                mstore(xor(scratch, 0x20), calldataload(offset))
                                // Reuse `leaf` to store the hash to reduce stack operations.
                                leaf := keccak256(0x00, 0x40)
                                offset := add(offset, 0x20)
                                // prettier-ignore
                                if iszero(lt(offset, end)) { break }
                            }
                        }
                        isValid := eq(leaf, root)
                    }
                }
                function verifyMultiProof(
                    bytes32[] calldata proof,
                    bytes32 root,
                    bytes32[] calldata leafs,
                    bool[] calldata flags
                ) internal pure returns (bool isValid) {
                    // Rebuilds the root by consuming and producing values on a queue.
                    // The queue starts with the `leafs` array, and goes into a `hashes` array.
                    // After the process, the last element on the queue is verified
                    // to be equal to the `root`.
                    //
                    // The `flags` array denotes whether the sibling
                    // should be popped from the queue (`flag == true`), or
                    // should be popped from the `proof` (`flag == false`).
                    assembly {
                        // If the number of flags is correct.
                        // prettier-ignore
                        for {} eq(add(leafs.length, proof.length), add(flags.length, 1)) {} {
                            // Left shift by 5 is equivalent to multiplying by 0x20.
                            // Compute the end calldata offset of `leafs`.
                            let leafsEnd := add(leafs.offset, shl(5, leafs.length))
                            // These are the calldata offsets.
                            let leafsOffset := leafs.offset
                            let flagsOffset := flags.offset
                            let proofOffset := proof.offset
                            // We can use the free memory space for the queue.
                            // We don't need to allocate, since the queue is temporary.
                            let hashesFront := mload(0x40)
                            let hashesBack := hashesFront
                            // This is the end of the memory for the queue.
                            let end := add(hashesBack, shl(5, flags.length))
                            // For the case where `proof.length + leafs.length == 1`.
                            if iszero(flags.length) {
                                // If `proof.length` is zero, `leafs.length` is 1.
                                if iszero(proof.length) {
                                    isValid := eq(calldataload(leafsOffset), root)
                                    break
                                }
                                // If `leafs.length` is zero, `proof.length` is 1.
                                if iszero(leafs.length) {
                                    isValid := eq(calldataload(proofOffset), root)
                                    break
                                }
                            }
                            // prettier-ignore
                            for {} 1 {} {
                                let a := 0
                                // Pops a value from the queue into `a`.
                                switch lt(leafsOffset, leafsEnd)
                                case 0 {
                                    // Pop from `hashes` if there are no more leafs.
                                    a := mload(hashesFront)
                                    hashesFront := add(hashesFront, 0x20)
                                }
                                default {
                                    // Otherwise, pop from `leafs`.
                                    a := calldataload(leafsOffset)
                                    leafsOffset := add(leafsOffset, 0x20)
                                }
                                let b := 0
                                // If the flag is false, load the next proof,
                                // else, pops from the queue.
                                switch calldataload(flagsOffset)
                                case 0 {
                                    // Loads the next proof.
                                    b := calldataload(proofOffset)
                                    proofOffset := add(proofOffset, 0x20)
                                }
                                default {
                                    // Pops a value from the queue into `a`.
                                    switch lt(leafsOffset, leafsEnd)
                                    case 0 {
                                        // Pop from `hashes` if there are no more leafs.
                                        b := mload(hashesFront)
                                        hashesFront := add(hashesFront, 0x20)
                                    }
                                    default {
                                        // Otherwise, pop from `leafs`.
                                        b := calldataload(leafsOffset)
                                        leafsOffset := add(leafsOffset, 0x20)
                                    }
                                }
                                // Advance to the next flag offset.
                                flagsOffset := add(flagsOffset, 0x20)
                                // Slot of `a` in scratch space.
                                // If the condition is true: 0x20, otherwise: 0x00.
                                let scratch := shl(5, gt(a, b))
                                // Hash the scratch space and push the result onto the queue.
                                mstore(scratch, a)
                                mstore(xor(scratch, 0x20), b)
                                mstore(hashesBack, keccak256(0x00, 0x40))
                                hashesBack := add(hashesBack, 0x20)
                                // prettier-ignore
                                if iszero(lt(hashesBack, end)) { break }
                            }
                            // Checks if the last value in the queue is same as the root.
                            isValid := eq(mload(sub(hashesBack, 0x20)), root)
                            break
                        }
                    }
                }
            }