ETH Price: $2,469.33 (-5.30%)

Transaction Decoder

Block:
17645101 at Jul-07-2023 11:10:11 PM +UTC
Transaction Fee:
0.00655863349285322 ETH $16.20
Gas Used:
281,524 Gas / 23.296889405 Gwei

Account State Difference:

  Address   Before After State Difference Code
0x0fea1161...5D20cC8F2
0x8D36aeDB...c302d74C7
3.853033904541514253 Eth
Nonce: 767
3.846475271048661033 Eth
Nonce: 768
0.00655863349285322
(MEV Builder: 0xBaF...e19)
4.275659851600957095 Eth4.275961610371558967 Eth0.000301758770601872
0xe23a3091...73fD2810c

Execution Trace

TransferHelper.bulkTransfer( items=, conduitKey=0000007B02230091A7ED01230072F7006A004D60A8D4E71D599B8104250F0000 ) => ( items=, conduitKey= )
  • Conduit.execute( transfers= ) => ( transfers= )
    • AiMetaChipGen1.transferFrom( from=0x8D36aeDBD5441b43b92A7cC73C17A0ec302d74C7, to=0x4d0b880daf8bbb48001BDA3a67ea11EFb18a1854, tokenId=331 )
    • MetaBlazeMetaGoblins.transferFrom( from=0x8D36aeDBD5441b43b92A7cC73C17A0ec302d74C7, to=0x4d0b880daf8bbb48001BDA3a67ea11EFb18a1854, tokenId=3689 )
    • MetaBlazeMetaGoblins.transferFrom( from=0x8D36aeDBD5441b43b92A7cC73C17A0ec302d74C7, to=0x4d0b880daf8bbb48001BDA3a67ea11EFb18a1854, tokenId=3682 )
    • MetaBlazeMetaGoblins.transferFrom( from=0x8D36aeDBD5441b43b92A7cC73C17A0ec302d74C7, to=0x4d0b880daf8bbb48001BDA3a67ea11EFb18a1854, tokenId=3688 )
      bulkTransfer[TransferHelper (ln:57)]
      File 1 of 4: TransferHelper
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      import { IERC721Receiver } from "../interfaces/IERC721Receiver.sol";
      import "./TransferHelperStructs.sol";
      import { ConduitInterface } from "../interfaces/ConduitInterface.sol";
      import {
          ConduitControllerInterface
      } from "../interfaces/ConduitControllerInterface.sol";
      import { Conduit } from "../conduit/Conduit.sol";
      import { ConduitTransfer } from "../conduit/lib/ConduitStructs.sol";
      import {
          TransferHelperInterface
      } from "../interfaces/TransferHelperInterface.sol";
      import { TransferHelperErrors } from "../interfaces/TransferHelperErrors.sol";
      /**
       * @title TransferHelper
       * @author stephankmin, stuckinaboot, ryanio
       * @notice TransferHelper is a utility contract for transferring
       *         ERC20/ERC721/ERC1155 items in bulk to specific recipients.
       */
      contract TransferHelper is TransferHelperInterface, TransferHelperErrors {
          // Allow for interaction with the conduit controller.
          ConduitControllerInterface internal immutable _CONDUIT_CONTROLLER;
          // Set conduit creation code and runtime code hashes as immutable arguments.
          bytes32 internal immutable _CONDUIT_CREATION_CODE_HASH;
          bytes32 internal immutable _CONDUIT_RUNTIME_CODE_HASH;
          /**
           * @dev Set the supplied conduit controller and retrieve its
           *      conduit creation code hash.
           *
           *
           * @param conduitController A contract that deploys conduits, or proxies
           *                          that may optionally be used to transfer approved
           *                          ERC20/721/1155 tokens.
           */
          constructor(address conduitController) {
              // Get the conduit creation code and runtime code hashes from the
              // supplied conduit controller and set them as an immutable.
              ConduitControllerInterface controller = ConduitControllerInterface(
                  conduitController
              );
              (_CONDUIT_CREATION_CODE_HASH, _CONDUIT_RUNTIME_CODE_HASH) = controller
                  .getConduitCodeHashes();
              // Set the supplied conduit controller as an immutable.
              _CONDUIT_CONTROLLER = controller;
          }
          /**
           * @notice Transfer multiple ERC20/ERC721/ERC1155 items to
           *         specified recipients.
           *
           * @param items      The items to transfer to an intended recipient.
           * @param conduitKey An optional conduit key referring to a conduit through
           *                   which the bulk transfer should occur.
           *
           * @return magicValue A value indicating that the transfers were successful.
           */
          function bulkTransfer(
              TransferHelperItemsWithRecipient[] calldata items,
              bytes32 conduitKey
          ) external override returns (bytes4 magicValue) {
              // Ensure that a conduit key has been supplied.
              if (conduitKey == bytes32(0)) {
                  revert InvalidConduit(conduitKey, address(0));
              }
              // Use conduit derived from supplied conduit key to perform transfers.
              _performTransfersWithConduit(items, conduitKey);
              // Return a magic value indicating that the transfers were performed.
              magicValue = this.bulkTransfer.selector;
          }
          /**
           * @notice Perform multiple transfers to specified recipients via the
           *         conduit derived from the provided conduit key.
           *
           * @param transfers  The items to transfer.
           * @param conduitKey The conduit key referring to the conduit through
           *                   which the bulk transfer should occur.
           */
          function _performTransfersWithConduit(
              TransferHelperItemsWithRecipient[] calldata transfers,
              bytes32 conduitKey
          ) internal {
              // Retrieve total number of transfers and place on stack.
              uint256 numTransfers = transfers.length;
              // Derive the conduit address from the deployer, conduit key
              // and creation code hash.
              address conduit = address(
                  uint160(
                      uint256(
                          keccak256(
                              abi.encodePacked(
                                  bytes1(0xff),
                                  address(_CONDUIT_CONTROLLER),
                                  conduitKey,
                                  _CONDUIT_CREATION_CODE_HASH
                              )
                          )
                      )
                  )
              );
              // Declare a variable to store the sum of all items across transfers.
              uint256 sumOfItemsAcrossAllTransfers;
              // Skip overflow checks: all for loops are indexed starting at zero.
              unchecked {
                  // Iterate over each transfer.
                  for (uint256 i = 0; i < numTransfers; ++i) {
                      // Retrieve the transfer in question.
                      TransferHelperItemsWithRecipient calldata transfer = transfers[
                          i
                      ];
                      // Increment totalItems by the number of items in the transfer.
                      sumOfItemsAcrossAllTransfers += transfer.items.length;
                  }
              }
              // Declare a new array in memory with length totalItems to populate with
              // each conduit transfer.
              ConduitTransfer[] memory conduitTransfers = new ConduitTransfer[](
                  sumOfItemsAcrossAllTransfers
              );
              // Declare an index for storing ConduitTransfers in conduitTransfers.
              uint256 itemIndex;
              // Skip overflow checks: all for loops are indexed starting at zero.
              unchecked {
                  // Iterate over each transfer.
                  for (uint256 i = 0; i < numTransfers; ++i) {
                      // Retrieve the transfer in question.
                      TransferHelperItemsWithRecipient calldata transfer = transfers[
                          i
                      ];
                      // Retrieve the items of the transfer in question.
                      TransferHelperItem[] calldata transferItems = transfer.items;
                      // Ensure recipient is not the zero address.
                      _checkRecipientIsNotZeroAddress(transfer.recipient);
                      // Create a boolean indicating whether validateERC721Receiver
                      // is true and recipient is a contract.
                      bool callERC721Receiver = transfer.validateERC721Receiver &&
                          transfer.recipient.code.length != 0;
                      // Retrieve the total number of items in the transfer and
                      // place on stack.
                      uint256 numItemsInTransfer = transferItems.length;
                      // Iterate over each item in the transfer to create a
                      // corresponding ConduitTransfer.
                      for (uint256 j = 0; j < numItemsInTransfer; ++j) {
                          // Retrieve the item from the transfer.
                          TransferHelperItem calldata item = transferItems[j];
                          if (item.itemType == ConduitItemType.ERC20) {
                              // Ensure that the identifier of an ERC20 token is 0.
                              if (item.identifier != 0) {
                                  revert InvalidERC20Identifier();
                              }
                          }
                          // If the item is an ERC721 token and
                          // callERC721Receiver is true...
                          if (item.itemType == ConduitItemType.ERC721) {
                              if (callERC721Receiver) {
                                  // Check if the recipient implements
                                  // onERC721Received for the given tokenId.
                                  _checkERC721Receiver(
                                      conduit,
                                      transfer.recipient,
                                      item.identifier
                                  );
                              }
                          }
                          // Create a ConduitTransfer corresponding to each
                          // TransferHelperItem.
                          conduitTransfers[itemIndex] = ConduitTransfer(
                              item.itemType,
                              item.token,
                              msg.sender,
                              transfer.recipient,
                              item.identifier,
                              item.amount
                          );
                          // Increment the index for storing ConduitTransfers.
                          ++itemIndex;
                      }
                  }
              }
              // Attempt the external call to transfer tokens via the derived conduit.
              try ConduitInterface(conduit).execute(conduitTransfers) returns (
                  bytes4 conduitMagicValue
              ) {
                  // Check if the value returned from the external call matches
                  // the conduit `execute` selector.
                  if (conduitMagicValue != ConduitInterface.execute.selector) {
                      // If the external call fails, revert with the conduit key
                      // and conduit address.
                      revert InvalidConduit(conduitKey, conduit);
                  }
              } catch Error(string memory reason) {
                  // Catch reverts with a provided reason string and
                  // revert with the reason, conduit key and conduit address.
                  revert ConduitErrorRevertString(reason, conduitKey, conduit);
              } catch (bytes memory data) {
                  // Conduits will throw a custom error when attempting to transfer
                  // native token item types or an ERC721 item amount other than 1.
                  // Bubble up these custom errors when encountered. Note that the
                  // conduit itself will bubble up revert reasons from transfers as
                  // well, meaning that these errors are not necessarily indicative of
                  // an issue with the item type or amount in cases where the same
                  // custom error signature is encountered during a conduit transfer.
                  // Set initial value of first four bytes of revert data to the mask.
                  bytes4 customErrorSelector = bytes4(0xffffffff);
                  // Utilize assembly to read first four bytes (if present) directly.
                  assembly {
                      // Combine original mask with first four bytes of revert data.
                      customErrorSelector := and(
                          mload(add(data, 0x20)), // Data begins after length offset.
                          customErrorSelector
                      )
                  }
                  // Pass through the custom error in question if the revert data is
                  // the correct length and matches an expected custom error selector.
                  if (
                      data.length == 4 &&
                      (customErrorSelector == InvalidItemType.selector ||
                          customErrorSelector == InvalidERC721TransferAmount.selector)
                  ) {
                      // "Bubble up" the revert reason.
                      assembly {
                          revert(add(data, 0x20), 0x04)
                      }
                  }
                  // Catch all other reverts from the external call to the conduit and
                  // include the conduit's raw revert reason as a data argument to a
                  // new custom error.
                  revert ConduitErrorRevertBytes(data, conduitKey, conduit);
              }
          }
          /**
           * @notice An internal function to check if a recipient address implements
           *         onERC721Received for a given tokenId. Note that this check does
           *         not adhere to the safe transfer specification and is only meant
           *         to provide an additional layer of assurance that the recipient
           *         can receive the tokens — any hooks or post-transfer checks will
           *         fail and the caller will be the transfer helper rather than the
           *         ERC721 contract. Note that the conduit is set as the operator, as
           *         it will be the caller once the transfer is performed.
           *
           * @param conduit   The conduit to provide as the operator when calling
           *                  onERC721Received.
           * @param recipient The ERC721 recipient on which to call onERC721Received.
           * @param tokenId   The ERC721 tokenId of the token being transferred.
           */
          function _checkERC721Receiver(
              address conduit,
              address recipient,
              uint256 tokenId
          ) internal {
              // Check if recipient can receive ERC721 tokens.
              try
                  IERC721Receiver(recipient).onERC721Received(
                      conduit,
                      msg.sender,
                      tokenId,
                      ""
                  )
              returns (bytes4 selector) {
                  // Check if onERC721Received selector is valid.
                  if (selector != IERC721Receiver.onERC721Received.selector) {
                      // Revert if recipient cannot accept
                      // ERC721 tokens.
                      revert InvalidERC721Recipient(recipient);
                  }
              } catch (bytes memory data) {
                  // "Bubble up" recipient's revert reason.
                  revert ERC721ReceiverErrorRevertBytes(
                      data,
                      recipient,
                      msg.sender,
                      tokenId
                  );
              } catch Error(string memory reason) {
                  // "Bubble up" recipient's revert reason.
                  revert ERC721ReceiverErrorRevertString(
                      reason,
                      recipient,
                      msg.sender,
                      tokenId
                  );
              }
          }
          /**
           * @notice An internal function that reverts if the passed-in recipient
           *         is the zero address.
           *
           * @param recipient The recipient on which to perform the check.
           */
          function _checkRecipientIsNotZeroAddress(address recipient) internal pure {
              // Revert if the recipient is the zero address.
              if (recipient == address(0x0)) {
                  revert RecipientCannotBeZeroAddress();
              }
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      interface IERC721Receiver {
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      import { ConduitItemType } from "../conduit/lib/ConduitEnums.sol";
      /**
       * @dev A TransferHelperItem specifies the itemType (ERC20/ERC721/ERC1155),
       *      token address, token identifier, and amount of the token to be
       *      transferred via the TransferHelper. For ERC20 tokens, identifier
       *      must be 0. For ERC721 tokens, amount must be 1.
       */
      struct TransferHelperItem {
          ConduitItemType itemType;
          address token;
          uint256 identifier;
          uint256 amount;
      }
      /**
       * @dev A TransferHelperItemsWithRecipient specifies the tokens to transfer
       *      via the TransferHelper, their intended recipient, and a boolean flag
       *      indicating whether onERC721Received should be called on a recipient
       *      contract.
       */
      struct TransferHelperItemsWithRecipient {
          TransferHelperItem[] items;
          address recipient;
          bool validateERC721Receiver;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      import {
          ConduitTransfer,
          ConduitBatch1155Transfer
      } from "../conduit/lib/ConduitStructs.sol";
      /**
       * @title ConduitInterface
       * @author 0age
       * @notice ConduitInterface contains all external function interfaces, events,
       *         and errors for conduit contracts.
       */
      interface ConduitInterface {
          /**
           * @dev Revert with an error when attempting to execute transfers using a
           *      caller that does not have an open channel.
           */
          error ChannelClosed(address channel);
          /**
           * @dev Revert with an error when attempting to update a channel to the
           *      current status of that channel.
           */
          error ChannelStatusAlreadySet(address channel, bool isOpen);
          /**
           * @dev Revert with an error when attempting to execute a transfer for an
           *      item that does not have an ERC20/721/1155 item type.
           */
          error InvalidItemType();
          /**
           * @dev Revert with an error when attempting to update the status of a
           *      channel from a caller that is not the conduit controller.
           */
          error InvalidController();
          /**
           * @dev Emit an event whenever a channel is opened or closed.
           *
           * @param channel The channel that has been updated.
           * @param open    A boolean indicating whether the conduit is open or not.
           */
          event ChannelUpdated(address indexed channel, bool open);
          /**
           * @notice Execute a sequence of ERC20/721/1155 transfers. Only a caller
           *         with an open channel can call this function.
           *
           * @param transfers The ERC20/721/1155 transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function execute(ConduitTransfer[] calldata transfers)
              external
              returns (bytes4 magicValue);
          /**
           * @notice Execute a sequence of batch 1155 transfers. Only a caller with an
           *         open channel can call this function.
           *
           * @param batch1155Transfers The 1155 batch transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function executeBatch1155(
              ConduitBatch1155Transfer[] calldata batch1155Transfers
          ) external returns (bytes4 magicValue);
          /**
           * @notice Execute a sequence of transfers, both single and batch 1155. Only
           *         a caller with an open channel can call this function.
           *
           * @param standardTransfers  The ERC20/721/1155 transfers to perform.
           * @param batch1155Transfers The 1155 batch transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function executeWithBatch1155(
              ConduitTransfer[] calldata standardTransfers,
              ConduitBatch1155Transfer[] calldata batch1155Transfers
          ) external returns (bytes4 magicValue);
          /**
           * @notice Open or close a given channel. Only callable by the controller.
           *
           * @param channel The channel to open or close.
           * @param isOpen  The status of the channel (either open or closed).
           */
          function updateChannel(address channel, bool isOpen) external;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      /**
       * @title ConduitControllerInterface
       * @author 0age
       * @notice ConduitControllerInterface contains all external function interfaces,
       *         structs, events, and errors for the conduit controller.
       */
      interface ConduitControllerInterface {
          /**
           * @dev Track the conduit key, current owner, new potential owner, and open
           *      channels for each deployed conduit.
           */
          struct ConduitProperties {
              bytes32 key;
              address owner;
              address potentialOwner;
              address[] channels;
              mapping(address => uint256) channelIndexesPlusOne;
          }
          /**
           * @dev Emit an event whenever a new conduit is created.
           *
           * @param conduit    The newly created conduit.
           * @param conduitKey The conduit key used to create the new conduit.
           */
          event NewConduit(address conduit, bytes32 conduitKey);
          /**
           * @dev Emit an event whenever conduit ownership is transferred.
           *
           * @param conduit       The conduit for which ownership has been
           *                      transferred.
           * @param previousOwner The previous owner of the conduit.
           * @param newOwner      The new owner of the conduit.
           */
          event OwnershipTransferred(
              address indexed conduit,
              address indexed previousOwner,
              address indexed newOwner
          );
          /**
           * @dev Emit an event whenever a conduit owner registers a new potential
           *      owner for that conduit.
           *
           * @param newPotentialOwner The new potential owner of the conduit.
           */
          event PotentialOwnerUpdated(address indexed newPotentialOwner);
          /**
           * @dev Revert with an error when attempting to create a new conduit using a
           *      conduit key where the first twenty bytes of the key do not match the
           *      address of the caller.
           */
          error InvalidCreator();
          /**
           * @dev Revert with an error when attempting to create a new conduit when no
           *      initial owner address is supplied.
           */
          error InvalidInitialOwner();
          /**
           * @dev Revert with an error when attempting to set a new potential owner
           *      that is already set.
           */
          error NewPotentialOwnerAlreadySet(
              address conduit,
              address newPotentialOwner
          );
          /**
           * @dev Revert with an error when attempting to cancel ownership transfer
           *      when no new potential owner is currently set.
           */
          error NoPotentialOwnerCurrentlySet(address conduit);
          /**
           * @dev Revert with an error when attempting to interact with a conduit that
           *      does not yet exist.
           */
          error NoConduit();
          /**
           * @dev Revert with an error when attempting to create a conduit that
           *      already exists.
           */
          error ConduitAlreadyExists(address conduit);
          /**
           * @dev Revert with an error when attempting to update channels or transfer
           *      ownership of a conduit when the caller is not the owner of the
           *      conduit in question.
           */
          error CallerIsNotOwner(address conduit);
          /**
           * @dev Revert with an error when attempting to register a new potential
           *      owner and supplying the null address.
           */
          error NewPotentialOwnerIsZeroAddress(address conduit);
          /**
           * @dev Revert with an error when attempting to claim ownership of a conduit
           *      with a caller that is not the current potential owner for the
           *      conduit in question.
           */
          error CallerIsNotNewPotentialOwner(address conduit);
          /**
           * @dev Revert with an error when attempting to retrieve a channel using an
           *      index that is out of range.
           */
          error ChannelOutOfRange(address conduit);
          /**
           * @notice Deploy a new conduit using a supplied conduit key and assigning
           *         an initial owner for the deployed conduit. Note that the first
           *         twenty bytes of the supplied conduit key must match the caller
           *         and that a new conduit cannot be created if one has already been
           *         deployed using the same conduit key.
           *
           * @param conduitKey   The conduit key used to deploy the conduit. Note that
           *                     the first twenty bytes of the conduit key must match
           *                     the caller of this contract.
           * @param initialOwner The initial owner to set for the new conduit.
           *
           * @return conduit The address of the newly deployed conduit.
           */
          function createConduit(bytes32 conduitKey, address initialOwner)
              external
              returns (address conduit);
          /**
           * @notice Open or close a channel on a given conduit, thereby allowing the
           *         specified account to execute transfers against that conduit.
           *         Extreme care must be taken when updating channels, as malicious
           *         or vulnerable channels can transfer any ERC20, ERC721 and ERC1155
           *         tokens where the token holder has granted the conduit approval.
           *         Only the owner of the conduit in question may call this function.
           *
           * @param conduit The conduit for which to open or close the channel.
           * @param channel The channel to open or close on the conduit.
           * @param isOpen  A boolean indicating whether to open or close the channel.
           */
          function updateChannel(
              address conduit,
              address channel,
              bool isOpen
          ) external;
          /**
           * @notice Initiate conduit ownership transfer by assigning a new potential
           *         owner for the given conduit. Once set, the new potential owner
           *         may call `acceptOwnership` to claim ownership of the conduit.
           *         Only the owner of the conduit in question may call this function.
           *
           * @param conduit The conduit for which to initiate ownership transfer.
           * @param newPotentialOwner The new potential owner of the conduit.
           */
          function transferOwnership(address conduit, address newPotentialOwner)
              external;
          /**
           * @notice Clear the currently set potential owner, if any, from a conduit.
           *         Only the owner of the conduit in question may call this function.
           *
           * @param conduit The conduit for which to cancel ownership transfer.
           */
          function cancelOwnershipTransfer(address conduit) external;
          /**
           * @notice Accept ownership of a supplied conduit. Only accounts that the
           *         current owner has set as the new potential owner may call this
           *         function.
           *
           * @param conduit The conduit for which to accept ownership.
           */
          function acceptOwnership(address conduit) external;
          /**
           * @notice Retrieve the current owner of a deployed conduit.
           *
           * @param conduit The conduit for which to retrieve the associated owner.
           *
           * @return owner The owner of the supplied conduit.
           */
          function ownerOf(address conduit) external view returns (address owner);
          /**
           * @notice Retrieve the conduit key for a deployed conduit via reverse
           *         lookup.
           *
           * @param conduit The conduit for which to retrieve the associated conduit
           *                key.
           *
           * @return conduitKey The conduit key used to deploy the supplied conduit.
           */
          function getKey(address conduit) external view returns (bytes32 conduitKey);
          /**
           * @notice Derive the conduit associated with a given conduit key and
           *         determine whether that conduit exists (i.e. whether it has been
           *         deployed).
           *
           * @param conduitKey The conduit key used to derive the conduit.
           *
           * @return conduit The derived address of the conduit.
           * @return exists  A boolean indicating whether the derived conduit has been
           *                 deployed or not.
           */
          function getConduit(bytes32 conduitKey)
              external
              view
              returns (address conduit, bool exists);
          /**
           * @notice Retrieve the potential owner, if any, for a given conduit. The
           *         current owner may set a new potential owner via
           *         `transferOwnership` and that owner may then accept ownership of
           *         the conduit in question via `acceptOwnership`.
           *
           * @param conduit The conduit for which to retrieve the potential owner.
           *
           * @return potentialOwner The potential owner, if any, for the conduit.
           */
          function getPotentialOwner(address conduit)
              external
              view
              returns (address potentialOwner);
          /**
           * @notice Retrieve the status (either open or closed) of a given channel on
           *         a conduit.
           *
           * @param conduit The conduit for which to retrieve the channel status.
           * @param channel The channel for which to retrieve the status.
           *
           * @return isOpen The status of the channel on the given conduit.
           */
          function getChannelStatus(address conduit, address channel)
              external
              view
              returns (bool isOpen);
          /**
           * @notice Retrieve the total number of open channels for a given conduit.
           *
           * @param conduit The conduit for which to retrieve the total channel count.
           *
           * @return totalChannels The total number of open channels for the conduit.
           */
          function getTotalChannels(address conduit)
              external
              view
              returns (uint256 totalChannels);
          /**
           * @notice Retrieve an open channel at a specific index for a given conduit.
           *         Note that the index of a channel can change as a result of other
           *         channels being closed on the conduit.
           *
           * @param conduit      The conduit for which to retrieve the open channel.
           * @param channelIndex The index of the channel in question.
           *
           * @return channel The open channel, if any, at the specified channel index.
           */
          function getChannel(address conduit, uint256 channelIndex)
              external
              view
              returns (address channel);
          /**
           * @notice Retrieve all open channels for a given conduit. Note that calling
           *         this function for a conduit with many channels will revert with
           *         an out-of-gas error.
           *
           * @param conduit The conduit for which to retrieve open channels.
           *
           * @return channels An array of open channels on the given conduit.
           */
          function getChannels(address conduit)
              external
              view
              returns (address[] memory channels);
          /**
           * @dev Retrieve the conduit creation code and runtime code hashes.
           */
          function getConduitCodeHashes()
              external
              view
              returns (bytes32 creationCodeHash, bytes32 runtimeCodeHash);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      import { ConduitInterface } from "../interfaces/ConduitInterface.sol";
      import { ConduitItemType } from "./lib/ConduitEnums.sol";
      import { TokenTransferrer } from "../lib/TokenTransferrer.sol";
      import {
          ConduitTransfer,
          ConduitBatch1155Transfer
      } from "./lib/ConduitStructs.sol";
      import "./lib/ConduitConstants.sol";
      /**
       * @title Conduit
       * @author 0age
       * @notice This contract serves as an originator for "proxied" transfers. Each
       *         conduit is deployed and controlled by a "conduit controller" that can
       *         add and remove "channels" or contracts that can instruct the conduit
       *         to transfer approved ERC20/721/1155 tokens. *IMPORTANT NOTE: each
       *         conduit has an owner that can arbitrarily add or remove channels, and
       *         a malicious or negligent owner can add a channel that allows for any
       *         approved ERC20/721/1155 tokens to be taken immediately — be extremely
       *         cautious with what conduits you give token approvals to!*
       */
      contract Conduit is ConduitInterface, TokenTransferrer {
          // Set deployer as an immutable controller that can update channel statuses.
          address private immutable _controller;
          // Track the status of each channel.
          mapping(address => bool) private _channels;
          /**
           * @notice Ensure that the caller is currently registered as an open channel
           *         on the conduit.
           */
          modifier onlyOpenChannel() {
              // Utilize assembly to access channel storage mapping directly.
              assembly {
                  // Write the caller to scratch space.
                  mstore(ChannelKey_channel_ptr, caller())
                  // Write the storage slot for _channels to scratch space.
                  mstore(ChannelKey_slot_ptr, _channels.slot)
                  // Derive the position in storage of _channels[msg.sender]
                  // and check if the stored value is zero.
                  if iszero(
                      sload(keccak256(ChannelKey_channel_ptr, ChannelKey_length))
                  ) {
                      // The caller is not an open channel; revert with
                      // ChannelClosed(caller). First, set error signature in memory.
                      mstore(ChannelClosed_error_ptr, ChannelClosed_error_signature)
                      // Next, set the caller as the argument.
                      mstore(ChannelClosed_channel_ptr, caller())
                      // Finally, revert, returning full custom error with argument.
                      revert(ChannelClosed_error_ptr, ChannelClosed_error_length)
                  }
              }
              // Continue with function execution.
              _;
          }
          /**
           * @notice In the constructor, set the deployer as the controller.
           */
          constructor() {
              // Set the deployer as the controller.
              _controller = msg.sender;
          }
          /**
           * @notice Execute a sequence of ERC20/721/1155 transfers. Only a caller
           *         with an open channel can call this function. Note that channels
           *         are expected to implement reentrancy protection if desired, and
           *         that cross-channel reentrancy may be possible if the conduit has
           *         multiple open channels at once. Also note that channels are
           *         expected to implement checks against transferring any zero-amount
           *         items if that constraint is desired.
           *
           * @param transfers The ERC20/721/1155 transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function execute(ConduitTransfer[] calldata transfers)
              external
              override
              onlyOpenChannel
              returns (bytes4 magicValue)
          {
              // Retrieve the total number of transfers and place on the stack.
              uint256 totalStandardTransfers = transfers.length;
              // Iterate over each transfer.
              for (uint256 i = 0; i < totalStandardTransfers; ) {
                  // Retrieve the transfer in question and perform the transfer.
                  _transfer(transfers[i]);
                  // Skip overflow check as for loop is indexed starting at zero.
                  unchecked {
                      ++i;
                  }
              }
              // Return a magic value indicating that the transfers were performed.
              magicValue = this.execute.selector;
          }
          /**
           * @notice Execute a sequence of batch 1155 item transfers. Only a caller
           *         with an open channel can call this function. Note that channels
           *         are expected to implement reentrancy protection if desired, and
           *         that cross-channel reentrancy may be possible if the conduit has
           *         multiple open channels at once. Also note that channels are
           *         expected to implement checks against transferring any zero-amount
           *         items if that constraint is desired.
           *
           * @param batchTransfers The 1155 batch item transfers to perform.
           *
           * @return magicValue A magic value indicating that the item transfers were
           *                    performed successfully.
           */
          function executeBatch1155(
              ConduitBatch1155Transfer[] calldata batchTransfers
          ) external override onlyOpenChannel returns (bytes4 magicValue) {
              // Perform 1155 batch transfers. Note that memory should be considered
              // entirely corrupted from this point forward.
              _performERC1155BatchTransfers(batchTransfers);
              // Return a magic value indicating that the transfers were performed.
              magicValue = this.executeBatch1155.selector;
          }
          /**
           * @notice Execute a sequence of transfers, both single ERC20/721/1155 item
           *         transfers as well as batch 1155 item transfers. Only a caller
           *         with an open channel can call this function. Note that channels
           *         are expected to implement reentrancy protection if desired, and
           *         that cross-channel reentrancy may be possible if the conduit has
           *         multiple open channels at once. Also note that channels are
           *         expected to implement checks against transferring any zero-amount
           *         items if that constraint is desired.
           *
           * @param standardTransfers The ERC20/721/1155 item transfers to perform.
           * @param batchTransfers    The 1155 batch item transfers to perform.
           *
           * @return magicValue A magic value indicating that the item transfers were
           *                    performed successfully.
           */
          function executeWithBatch1155(
              ConduitTransfer[] calldata standardTransfers,
              ConduitBatch1155Transfer[] calldata batchTransfers
          ) external override onlyOpenChannel returns (bytes4 magicValue) {
              // Retrieve the total number of transfers and place on the stack.
              uint256 totalStandardTransfers = standardTransfers.length;
              // Iterate over each standard transfer.
              for (uint256 i = 0; i < totalStandardTransfers; ) {
                  // Retrieve the transfer in question and perform the transfer.
                  _transfer(standardTransfers[i]);
                  // Skip overflow check as for loop is indexed starting at zero.
                  unchecked {
                      ++i;
                  }
              }
              // Perform 1155 batch transfers. Note that memory should be considered
              // entirely corrupted from this point forward aside from the free memory
              // pointer having the default value.
              _performERC1155BatchTransfers(batchTransfers);
              // Return a magic value indicating that the transfers were performed.
              magicValue = this.executeWithBatch1155.selector;
          }
          /**
           * @notice Open or close a given channel. Only callable by the controller.
           *
           * @param channel The channel to open or close.
           * @param isOpen  The status of the channel (either open or closed).
           */
          function updateChannel(address channel, bool isOpen) external override {
              // Ensure that the caller is the controller of this contract.
              if (msg.sender != _controller) {
                  revert InvalidController();
              }
              // Ensure that the channel does not already have the indicated status.
              if (_channels[channel] == isOpen) {
                  revert ChannelStatusAlreadySet(channel, isOpen);
              }
              // Update the status of the channel.
              _channels[channel] = isOpen;
              // Emit a corresponding event.
              emit ChannelUpdated(channel, isOpen);
          }
          /**
           * @dev Internal function to transfer a given ERC20/721/1155 item. Note that
           *      channels are expected to implement checks against transferring any
           *      zero-amount items if that constraint is desired.
           *
           * @param item The ERC20/721/1155 item to transfer.
           */
          function _transfer(ConduitTransfer calldata item) internal {
              // Determine the transfer method based on the respective item type.
              if (item.itemType == ConduitItemType.ERC20) {
                  // Transfer ERC20 token. Note that item.identifier is ignored and
                  // therefore ERC20 transfer items are potentially malleable — this
                  // check should be performed by the calling channel if a constraint
                  // on item malleability is desired.
                  _performERC20Transfer(item.token, item.from, item.to, item.amount);
              } else if (item.itemType == ConduitItemType.ERC721) {
                  // Ensure that exactly one 721 item is being transferred.
                  if (item.amount != 1) {
                      revert InvalidERC721TransferAmount();
                  }
                  // Transfer ERC721 token.
                  _performERC721Transfer(
                      item.token,
                      item.from,
                      item.to,
                      item.identifier
                  );
              } else if (item.itemType == ConduitItemType.ERC1155) {
                  // Transfer ERC1155 token.
                  _performERC1155Transfer(
                      item.token,
                      item.from,
                      item.to,
                      item.identifier,
                      item.amount
                  );
              } else {
                  // Throw with an error.
                  revert InvalidItemType();
              }
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      import { ConduitItemType } from "./ConduitEnums.sol";
      struct ConduitTransfer {
          ConduitItemType itemType;
          address token;
          address from;
          address to;
          uint256 identifier;
          uint256 amount;
      }
      struct ConduitBatch1155Transfer {
          address token;
          address from;
          address to;
          uint256[] ids;
          uint256[] amounts;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      import {
          TransferHelperItem,
          TransferHelperItemsWithRecipient
      } from "../helpers/TransferHelperStructs.sol";
      interface TransferHelperInterface {
          /**
           * @notice Transfer multiple items to a single recipient.
           *
           * @param items The items to transfer.
           * @param conduitKey  The key of the conduit performing the bulk transfer.
           */
          function bulkTransfer(
              TransferHelperItemsWithRecipient[] calldata items,
              bytes32 conduitKey
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      /**
       * @title TransferHelperErrors
       */
      interface TransferHelperErrors {
          /**
           * @dev Revert with an error when attempting to execute transfers with a
           *      NATIVE itemType.
           */
          error InvalidItemType();
          /**
           * @dev Revert with an error when an ERC721 transfer with amount other than
           *      one is attempted.
           */
          error InvalidERC721TransferAmount();
          /**
           * @dev Revert with an error when attempting to execute an ERC721 transfer
           *      to an invalid recipient.
           */
          error InvalidERC721Recipient(address recipient);
          /**
           * @dev Revert with an error when a call to a ERC721 receiver reverts with
           *      bytes data.
           */
          error ERC721ReceiverErrorRevertBytes(
              bytes reason,
              address receiver,
              address sender,
              uint256 identifier
          );
          /**
           * @dev Revert with an error when a call to a ERC721 receiver reverts with
           *      string reason.
           */
          error ERC721ReceiverErrorRevertString(
              string reason,
              address receiver,
              address sender,
              uint256 identifier
          );
          /**
           * @dev Revert with an error when an ERC20 token has an invalid identifier.
           */
          error InvalidERC20Identifier();
          /**
           * @dev Revert with an error if the recipient is the zero address.
           */
          error RecipientCannotBeZeroAddress();
          /**
           * @dev Revert with an error when attempting to fill an order referencing an
           *      invalid conduit (i.e. one that has not been deployed).
           */
          error InvalidConduit(bytes32 conduitKey, address conduit);
          /**
           * @dev Revert with an error when a call to a conduit reverts with a
           *      reason string.
           */
          error ConduitErrorRevertString(
              string reason,
              bytes32 conduitKey,
              address conduit
          );
          /**
           * @dev Revert with an error when a call to a conduit reverts with bytes
           *      data.
           */
          error ConduitErrorRevertBytes(
              bytes reason,
              bytes32 conduitKey,
              address conduit
          );
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      enum ConduitItemType {
          NATIVE, // unused
          ERC20,
          ERC721,
          ERC1155
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      import "./TokenTransferrerConstants.sol";
      import {
          TokenTransferrerErrors
      } from "../interfaces/TokenTransferrerErrors.sol";
      import { ConduitBatch1155Transfer } from "../conduit/lib/ConduitStructs.sol";
      /**
       * @title TokenTransferrer
       * @author 0age
       * @custom:coauthor d1ll0n
       * @custom:coauthor transmissions11
       * @notice TokenTransferrer is a library for performing optimized ERC20, ERC721,
       *         ERC1155, and batch ERC1155 transfers, used by both Seaport as well as
       *         by conduits deployed by the ConduitController. Use great caution when
       *         considering these functions for use in other codebases, as there are
       *         significant side effects and edge cases that need to be thoroughly
       *         understood and carefully addressed.
       */
      contract TokenTransferrer is TokenTransferrerErrors {
          /**
           * @dev Internal function to transfer ERC20 tokens from a given originator
           *      to a given recipient. Sufficient approvals must be set on the
           *      contract performing the transfer.
           *
           * @param token      The ERC20 token to transfer.
           * @param from       The originator of the transfer.
           * @param to         The recipient of the transfer.
           * @param amount     The amount to transfer.
           */
          function _performERC20Transfer(
              address token,
              address from,
              address to,
              uint256 amount
          ) internal {
              // Utilize assembly to perform an optimized ERC20 token transfer.
              assembly {
                  // The free memory pointer memory slot will be used when populating
                  // call data for the transfer; read the value and restore it later.
                  let memPointer := mload(FreeMemoryPointerSlot)
                  // Write call data into memory, starting with function selector.
                  mstore(ERC20_transferFrom_sig_ptr, ERC20_transferFrom_signature)
                  mstore(ERC20_transferFrom_from_ptr, from)
                  mstore(ERC20_transferFrom_to_ptr, to)
                  mstore(ERC20_transferFrom_amount_ptr, amount)
                  // Make call & copy up to 32 bytes of return data to scratch space.
                  // Scratch space does not need to be cleared ahead of time, as the
                  // subsequent check will ensure that either at least a full word of
                  // return data is received (in which case it will be overwritten) or
                  // that no data is received (in which case scratch space will be
                  // ignored) on a successful call to the given token.
                  let callStatus := call(
                      gas(),
                      token,
                      0,
                      ERC20_transferFrom_sig_ptr,
                      ERC20_transferFrom_length,
                      0,
                      OneWord
                  )
                  // Determine whether transfer was successful using status & result.
                  let success := and(
                      // Set success to whether the call reverted, if not check it
                      // either returned exactly 1 (can't just be non-zero data), or
                      // had no return data.
                      or(
                          and(eq(mload(0), 1), gt(returndatasize(), 31)),
                          iszero(returndatasize())
                      ),
                      callStatus
                  )
                  // Handle cases where either the transfer failed or no data was
                  // returned. Group these, as most transfers will succeed with data.
                  // Equivalent to `or(iszero(success), iszero(returndatasize()))`
                  // but after it's inverted for JUMPI this expression is cheaper.
                  if iszero(and(success, iszero(iszero(returndatasize())))) {
                      // If the token has no code or the transfer failed: Equivalent
                      // to `or(iszero(success), iszero(extcodesize(token)))` but
                      // after it's inverted for JUMPI this expression is cheaper.
                      if iszero(and(iszero(iszero(extcodesize(token))), success)) {
                          // If the transfer failed:
                          if iszero(success) {
                              // If it was due to a revert:
                              if iszero(callStatus) {
                                  // If it returned a message, bubble it up as long as
                                  // sufficient gas remains to do so:
                                  if returndatasize() {
                                      // Ensure that sufficient gas is available to
                                      // copy returndata while expanding memory where
                                      // necessary. Start by computing the word size
                                      // of returndata and allocated memory. Round up
                                      // to the nearest full word.
                                      let returnDataWords := div(
                                          add(returndatasize(), AlmostOneWord),
                                          OneWord
                                      )
                                      // Note: use the free memory pointer in place of
                                      // msize() to work around a Yul warning that
                                      // prevents accessing msize directly when the IR
                                      // pipeline is activated.
                                      let msizeWords := div(memPointer, OneWord)
                                      // Next, compute the cost of the returndatacopy.
                                      let cost := mul(CostPerWord, returnDataWords)
                                      // Then, compute cost of new memory allocation.
                                      if gt(returnDataWords, msizeWords) {
                                          cost := add(
                                              cost,
                                              add(
                                                  mul(
                                                      sub(
                                                          returnDataWords,
                                                          msizeWords
                                                      ),
                                                      CostPerWord
                                                  ),
                                                  div(
                                                      sub(
                                                          mul(
                                                              returnDataWords,
                                                              returnDataWords
                                                          ),
                                                          mul(msizeWords, msizeWords)
                                                      ),
                                                      MemoryExpansionCoefficient
                                                  )
                                              )
                                          )
                                      }
                                      // Finally, add a small constant and compare to
                                      // gas remaining; bubble up the revert data if
                                      // enough gas is still available.
                                      if lt(add(cost, ExtraGasBuffer), gas()) {
                                          // Copy returndata to memory; overwrite
                                          // existing memory.
                                          returndatacopy(0, 0, returndatasize())
                                          // Revert, specifying memory region with
                                          // copied returndata.
                                          revert(0, returndatasize())
                                      }
                                  }
                                  // Otherwise revert with a generic error message.
                                  mstore(
                                      TokenTransferGenericFailure_error_sig_ptr,
                                      TokenTransferGenericFailure_error_signature
                                  )
                                  mstore(
                                      TokenTransferGenericFailure_error_token_ptr,
                                      token
                                  )
                                  mstore(
                                      TokenTransferGenericFailure_error_from_ptr,
                                      from
                                  )
                                  mstore(TokenTransferGenericFailure_error_to_ptr, to)
                                  mstore(TokenTransferGenericFailure_error_id_ptr, 0)
                                  mstore(
                                      TokenTransferGenericFailure_error_amount_ptr,
                                      amount
                                  )
                                  revert(
                                      TokenTransferGenericFailure_error_sig_ptr,
                                      TokenTransferGenericFailure_error_length
                                  )
                              }
                              // Otherwise revert with a message about the token
                              // returning false or non-compliant return values.
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_sig_ptr,
                                  BadReturnValueFromERC20OnTransfer_error_signature
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_token_ptr,
                                  token
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_from_ptr,
                                  from
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_to_ptr,
                                  to
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_amount_ptr,
                                  amount
                              )
                              revert(
                                  BadReturnValueFromERC20OnTransfer_error_sig_ptr,
                                  BadReturnValueFromERC20OnTransfer_error_length
                              )
                          }
                          // Otherwise, revert with error about token not having code:
                          mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                          mstore(NoContract_error_token_ptr, token)
                          revert(NoContract_error_sig_ptr, NoContract_error_length)
                      }
                      // Otherwise, the token just returned no data despite the call
                      // having succeeded; no need to optimize for this as it's not
                      // technically ERC20 compliant.
                  }
                  // Restore the original free memory pointer.
                  mstore(FreeMemoryPointerSlot, memPointer)
                  // Restore the zero slot to zero.
                  mstore(ZeroSlot, 0)
              }
          }
          /**
           * @dev Internal function to transfer an ERC721 token from a given
           *      originator to a given recipient. Sufficient approvals must be set on
           *      the contract performing the transfer. Note that this function does
           *      not check whether the receiver can accept the ERC721 token (i.e. it
           *      does not use `safeTransferFrom`).
           *
           * @param token      The ERC721 token to transfer.
           * @param from       The originator of the transfer.
           * @param to         The recipient of the transfer.
           * @param identifier The tokenId to transfer.
           */
          function _performERC721Transfer(
              address token,
              address from,
              address to,
              uint256 identifier
          ) internal {
              // Utilize assembly to perform an optimized ERC721 token transfer.
              assembly {
                  // If the token has no code, revert.
                  if iszero(extcodesize(token)) {
                      mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                      mstore(NoContract_error_token_ptr, token)
                      revert(NoContract_error_sig_ptr, NoContract_error_length)
                  }
                  // The free memory pointer memory slot will be used when populating
                  // call data for the transfer; read the value and restore it later.
                  let memPointer := mload(FreeMemoryPointerSlot)
                  // Write call data to memory starting with function selector.
                  mstore(ERC721_transferFrom_sig_ptr, ERC721_transferFrom_signature)
                  mstore(ERC721_transferFrom_from_ptr, from)
                  mstore(ERC721_transferFrom_to_ptr, to)
                  mstore(ERC721_transferFrom_id_ptr, identifier)
                  // Perform the call, ignoring return data.
                  let success := call(
                      gas(),
                      token,
                      0,
                      ERC721_transferFrom_sig_ptr,
                      ERC721_transferFrom_length,
                      0,
                      0
                  )
                  // If the transfer reverted:
                  if iszero(success) {
                      // If it returned a message, bubble it up as long as sufficient
                      // gas remains to do so:
                      if returndatasize() {
                          // Ensure that sufficient gas is available to copy
                          // returndata while expanding memory where necessary. Start
                          // by computing word size of returndata & allocated memory.
                          // Round up to the nearest full word.
                          let returnDataWords := div(
                              add(returndatasize(), AlmostOneWord),
                              OneWord
                          )
                          // Note: use the free memory pointer in place of msize() to
                          // work around a Yul warning that prevents accessing msize
                          // directly when the IR pipeline is activated.
                          let msizeWords := div(memPointer, OneWord)
                          // Next, compute the cost of the returndatacopy.
                          let cost := mul(CostPerWord, returnDataWords)
                          // Then, compute cost of new memory allocation.
                          if gt(returnDataWords, msizeWords) {
                              cost := add(
                                  cost,
                                  add(
                                      mul(
                                          sub(returnDataWords, msizeWords),
                                          CostPerWord
                                      ),
                                      div(
                                          sub(
                                              mul(returnDataWords, returnDataWords),
                                              mul(msizeWords, msizeWords)
                                          ),
                                          MemoryExpansionCoefficient
                                      )
                                  )
                              )
                          }
                          // Finally, add a small constant and compare to gas
                          // remaining; bubble up the revert data if enough gas is
                          // still available.
                          if lt(add(cost, ExtraGasBuffer), gas()) {
                              // Copy returndata to memory; overwrite existing memory.
                              returndatacopy(0, 0, returndatasize())
                              // Revert, giving memory region with copied returndata.
                              revert(0, returndatasize())
                          }
                      }
                      // Otherwise revert with a generic error message.
                      mstore(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_signature
                      )
                      mstore(TokenTransferGenericFailure_error_token_ptr, token)
                      mstore(TokenTransferGenericFailure_error_from_ptr, from)
                      mstore(TokenTransferGenericFailure_error_to_ptr, to)
                      mstore(TokenTransferGenericFailure_error_id_ptr, identifier)
                      mstore(TokenTransferGenericFailure_error_amount_ptr, 1)
                      revert(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_length
                      )
                  }
                  // Restore the original free memory pointer.
                  mstore(FreeMemoryPointerSlot, memPointer)
                  // Restore the zero slot to zero.
                  mstore(ZeroSlot, 0)
              }
          }
          /**
           * @dev Internal function to transfer ERC1155 tokens from a given
           *      originator to a given recipient. Sufficient approvals must be set on
           *      the contract performing the transfer and contract recipients must
           *      implement the ERC1155TokenReceiver interface to indicate that they
           *      are willing to accept the transfer.
           *
           * @param token      The ERC1155 token to transfer.
           * @param from       The originator of the transfer.
           * @param to         The recipient of the transfer.
           * @param identifier The id to transfer.
           * @param amount     The amount to transfer.
           */
          function _performERC1155Transfer(
              address token,
              address from,
              address to,
              uint256 identifier,
              uint256 amount
          ) internal {
              // Utilize assembly to perform an optimized ERC1155 token transfer.
              assembly {
                  // If the token has no code, revert.
                  if iszero(extcodesize(token)) {
                      mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                      mstore(NoContract_error_token_ptr, token)
                      revert(NoContract_error_sig_ptr, NoContract_error_length)
                  }
                  // The following memory slots will be used when populating call data
                  // for the transfer; read the values and restore them later.
                  let memPointer := mload(FreeMemoryPointerSlot)
                  let slot0x80 := mload(Slot0x80)
                  let slot0xA0 := mload(Slot0xA0)
                  let slot0xC0 := mload(Slot0xC0)
                  // Write call data into memory, beginning with function selector.
                  mstore(
                      ERC1155_safeTransferFrom_sig_ptr,
                      ERC1155_safeTransferFrom_signature
                  )
                  mstore(ERC1155_safeTransferFrom_from_ptr, from)
                  mstore(ERC1155_safeTransferFrom_to_ptr, to)
                  mstore(ERC1155_safeTransferFrom_id_ptr, identifier)
                  mstore(ERC1155_safeTransferFrom_amount_ptr, amount)
                  mstore(
                      ERC1155_safeTransferFrom_data_offset_ptr,
                      ERC1155_safeTransferFrom_data_length_offset
                  )
                  mstore(ERC1155_safeTransferFrom_data_length_ptr, 0)
                  // Perform the call, ignoring return data.
                  let success := call(
                      gas(),
                      token,
                      0,
                      ERC1155_safeTransferFrom_sig_ptr,
                      ERC1155_safeTransferFrom_length,
                      0,
                      0
                  )
                  // If the transfer reverted:
                  if iszero(success) {
                      // If it returned a message, bubble it up as long as sufficient
                      // gas remains to do so:
                      if returndatasize() {
                          // Ensure that sufficient gas is available to copy
                          // returndata while expanding memory where necessary. Start
                          // by computing word size of returndata & allocated memory.
                          // Round up to the nearest full word.
                          let returnDataWords := div(
                              add(returndatasize(), AlmostOneWord),
                              OneWord
                          )
                          // Note: use the free memory pointer in place of msize() to
                          // work around a Yul warning that prevents accessing msize
                          // directly when the IR pipeline is activated.
                          let msizeWords := div(memPointer, OneWord)
                          // Next, compute the cost of the returndatacopy.
                          let cost := mul(CostPerWord, returnDataWords)
                          // Then, compute cost of new memory allocation.
                          if gt(returnDataWords, msizeWords) {
                              cost := add(
                                  cost,
                                  add(
                                      mul(
                                          sub(returnDataWords, msizeWords),
                                          CostPerWord
                                      ),
                                      div(
                                          sub(
                                              mul(returnDataWords, returnDataWords),
                                              mul(msizeWords, msizeWords)
                                          ),
                                          MemoryExpansionCoefficient
                                      )
                                  )
                              )
                          }
                          // Finally, add a small constant and compare to gas
                          // remaining; bubble up the revert data if enough gas is
                          // still available.
                          if lt(add(cost, ExtraGasBuffer), gas()) {
                              // Copy returndata to memory; overwrite existing memory.
                              returndatacopy(0, 0, returndatasize())
                              // Revert, giving memory region with copied returndata.
                              revert(0, returndatasize())
                          }
                      }
                      // Otherwise revert with a generic error message.
                      mstore(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_signature
                      )
                      mstore(TokenTransferGenericFailure_error_token_ptr, token)
                      mstore(TokenTransferGenericFailure_error_from_ptr, from)
                      mstore(TokenTransferGenericFailure_error_to_ptr, to)
                      mstore(TokenTransferGenericFailure_error_id_ptr, identifier)
                      mstore(TokenTransferGenericFailure_error_amount_ptr, amount)
                      revert(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_length
                      )
                  }
                  mstore(Slot0x80, slot0x80) // Restore slot 0x80.
                  mstore(Slot0xA0, slot0xA0) // Restore slot 0xA0.
                  mstore(Slot0xC0, slot0xC0) // Restore slot 0xC0.
                  // Restore the original free memory pointer.
                  mstore(FreeMemoryPointerSlot, memPointer)
                  // Restore the zero slot to zero.
                  mstore(ZeroSlot, 0)
              }
          }
          /**
           * @dev Internal function to transfer ERC1155 tokens from a given
           *      originator to a given recipient. Sufficient approvals must be set on
           *      the contract performing the transfer and contract recipients must
           *      implement the ERC1155TokenReceiver interface to indicate that they
           *      are willing to accept the transfer. NOTE: this function is not
           *      memory-safe; it will overwrite existing memory, restore the free
           *      memory pointer to the default value, and overwrite the zero slot.
           *      This function should only be called once memory is no longer
           *      required and when uninitialized arrays are not utilized, and memory
           *      should be considered fully corrupted (aside from the existence of a
           *      default-value free memory pointer) after calling this function.
           *
           * @param batchTransfers The group of 1155 batch transfers to perform.
           */
          function _performERC1155BatchTransfers(
              ConduitBatch1155Transfer[] calldata batchTransfers
          ) internal {
              // Utilize assembly to perform optimized batch 1155 transfers.
              assembly {
                  let len := batchTransfers.length
                  // Pointer to first head in the array, which is offset to the struct
                  // at each index. This gets incremented after each loop to avoid
                  // multiplying by 32 to get the offset for each element.
                  let nextElementHeadPtr := batchTransfers.offset
                  // Pointer to beginning of the head of the array. This is the
                  // reference position each offset references. It's held static to
                  // let each loop calculate the data position for an element.
                  let arrayHeadPtr := nextElementHeadPtr
                  // Write the function selector, which will be reused for each call:
                  // safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)
                  mstore(
                      ConduitBatch1155Transfer_from_offset,
                      ERC1155_safeBatchTransferFrom_signature
                  )
                  // Iterate over each batch transfer.
                  for {
                      let i := 0
                  } lt(i, len) {
                      i := add(i, 1)
                  } {
                      // Read the offset to the beginning of the element and add
                      // it to pointer to the beginning of the array head to get
                      // the absolute position of the element in calldata.
                      let elementPtr := add(
                          arrayHeadPtr,
                          calldataload(nextElementHeadPtr)
                      )
                      // Retrieve the token from calldata.
                      let token := calldataload(elementPtr)
                      // If the token has no code, revert.
                      if iszero(extcodesize(token)) {
                          mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                          mstore(NoContract_error_token_ptr, token)
                          revert(NoContract_error_sig_ptr, NoContract_error_length)
                      }
                      // Get the total number of supplied ids.
                      let idsLength := calldataload(
                          add(elementPtr, ConduitBatch1155Transfer_ids_length_offset)
                      )
                      // Determine the expected offset for the amounts array.
                      let expectedAmountsOffset := add(
                          ConduitBatch1155Transfer_amounts_length_baseOffset,
                          mul(idsLength, OneWord)
                      )
                      // Validate struct encoding.
                      let invalidEncoding := iszero(
                          and(
                              // ids.length == amounts.length
                              eq(
                                  idsLength,
                                  calldataload(add(elementPtr, expectedAmountsOffset))
                              ),
                              and(
                                  // ids_offset == 0xa0
                                  eq(
                                      calldataload(
                                          add(
                                              elementPtr,
                                              ConduitBatch1155Transfer_ids_head_offset
                                          )
                                      ),
                                      ConduitBatch1155Transfer_ids_length_offset
                                  ),
                                  // amounts_offset == 0xc0 + ids.length*32
                                  eq(
                                      calldataload(
                                          add(
                                              elementPtr,
                                              ConduitBatchTransfer_amounts_head_offset
                                          )
                                      ),
                                      expectedAmountsOffset
                                  )
                              )
                          )
                      )
                      // Revert with an error if the encoding is not valid.
                      if invalidEncoding {
                          mstore(
                              Invalid1155BatchTransferEncoding_ptr,
                              Invalid1155BatchTransferEncoding_selector
                          )
                          revert(
                              Invalid1155BatchTransferEncoding_ptr,
                              Invalid1155BatchTransferEncoding_length
                          )
                      }
                      // Update the offset position for the next loop
                      nextElementHeadPtr := add(nextElementHeadPtr, OneWord)
                      // Copy the first section of calldata (before dynamic values).
                      calldatacopy(
                          BatchTransfer1155Params_ptr,
                          add(elementPtr, ConduitBatch1155Transfer_from_offset),
                          ConduitBatch1155Transfer_usable_head_size
                      )
                      // Determine size of calldata required for ids and amounts. Note
                      // that the size includes both lengths as well as the data.
                      let idsAndAmountsSize := add(TwoWords, mul(idsLength, TwoWords))
                      // Update the offset for the data array in memory.
                      mstore(
                          BatchTransfer1155Params_data_head_ptr,
                          add(
                              BatchTransfer1155Params_ids_length_offset,
                              idsAndAmountsSize
                          )
                      )
                      // Set the length of the data array in memory to zero.
                      mstore(
                          add(
                              BatchTransfer1155Params_data_length_basePtr,
                              idsAndAmountsSize
                          ),
                          0
                      )
                      // Determine the total calldata size for the call to transfer.
                      let transferDataSize := add(
                          BatchTransfer1155Params_calldata_baseSize,
                          idsAndAmountsSize
                      )
                      // Copy second section of calldata (including dynamic values).
                      calldatacopy(
                          BatchTransfer1155Params_ids_length_ptr,
                          add(elementPtr, ConduitBatch1155Transfer_ids_length_offset),
                          idsAndAmountsSize
                      )
                      // Perform the call to transfer 1155 tokens.
                      let success := call(
                          gas(),
                          token,
                          0,
                          ConduitBatch1155Transfer_from_offset, // Data portion start.
                          transferDataSize, // Location of the length of callData.
                          0,
                          0
                      )
                      // If the transfer reverted:
                      if iszero(success) {
                          // If it returned a message, bubble it up as long as
                          // sufficient gas remains to do so:
                          if returndatasize() {
                              // Ensure that sufficient gas is available to copy
                              // returndata while expanding memory where necessary.
                              // Start by computing word size of returndata and
                              // allocated memory. Round up to the nearest full word.
                              let returnDataWords := div(
                                  add(returndatasize(), AlmostOneWord),
                                  OneWord
                              )
                              // Note: use transferDataSize in place of msize() to
                              // work around a Yul warning that prevents accessing
                              // msize directly when the IR pipeline is activated.
                              // The free memory pointer is not used here because
                              // this function does almost all memory management
                              // manually and does not update it, and transferDataSize
                              // should be the largest memory value used (unless a
                              // previous batch was larger).
                              let msizeWords := div(transferDataSize, OneWord)
                              // Next, compute the cost of the returndatacopy.
                              let cost := mul(CostPerWord, returnDataWords)
                              // Then, compute cost of new memory allocation.
                              if gt(returnDataWords, msizeWords) {
                                  cost := add(
                                      cost,
                                      add(
                                          mul(
                                              sub(returnDataWords, msizeWords),
                                              CostPerWord
                                          ),
                                          div(
                                              sub(
                                                  mul(
                                                      returnDataWords,
                                                      returnDataWords
                                                  ),
                                                  mul(msizeWords, msizeWords)
                                              ),
                                              MemoryExpansionCoefficient
                                          )
                                      )
                                  )
                              }
                              // Finally, add a small constant and compare to gas
                              // remaining; bubble up the revert data if enough gas is
                              // still available.
                              if lt(add(cost, ExtraGasBuffer), gas()) {
                                  // Copy returndata to memory; overwrite existing.
                                  returndatacopy(0, 0, returndatasize())
                                  // Revert with memory region containing returndata.
                                  revert(0, returndatasize())
                              }
                          }
                          // Set the error signature.
                          mstore(
                              0,
                              ERC1155BatchTransferGenericFailure_error_signature
                          )
                          // Write the token.
                          mstore(ERC1155BatchTransferGenericFailure_token_ptr, token)
                          // Increase the offset to ids by 32.
                          mstore(
                              BatchTransfer1155Params_ids_head_ptr,
                              ERC1155BatchTransferGenericFailure_ids_offset
                          )
                          // Increase the offset to amounts by 32.
                          mstore(
                              BatchTransfer1155Params_amounts_head_ptr,
                              add(
                                  OneWord,
                                  mload(BatchTransfer1155Params_amounts_head_ptr)
                              )
                          )
                          // Return modified region. The total size stays the same as
                          // `token` uses the same number of bytes as `data.length`.
                          revert(0, transferDataSize)
                      }
                  }
                  // Reset the free memory pointer to the default value; memory must
                  // be assumed to be dirtied and not reused from this point forward.
                  // Also note that the zero slot is not reset to zero, meaning empty
                  // arrays cannot be safely created or utilized until it is restored.
                  mstore(FreeMemoryPointerSlot, DefaultFreeMemoryPointer)
              }
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      // error ChannelClosed(address channel)
      uint256 constant ChannelClosed_error_signature = (
          0x93daadf200000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ChannelClosed_error_ptr = 0x00;
      uint256 constant ChannelClosed_channel_ptr = 0x4;
      uint256 constant ChannelClosed_error_length = 0x24;
      // For the mapping:
      // mapping(address => bool) channels
      // The position in storage for a particular account is:
      // keccak256(abi.encode(account, channels.slot))
      uint256 constant ChannelKey_channel_ptr = 0x00;
      uint256 constant ChannelKey_slot_ptr = 0x20;
      uint256 constant ChannelKey_length = 0x40;
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      /*
       * -------------------------- Disambiguation & Other Notes ---------------------
       *    - The term "head" is used as it is in the documentation for ABI encoding,
       *      but only in reference to dynamic types, i.e. it always refers to the
       *      offset or pointer to the body of a dynamic type. In calldata, the head
       *      is always an offset (relative to the parent object), while in memory,
       *      the head is always the pointer to the body. More information found here:
       *      https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#argument-encoding
       *        - Note that the length of an array is separate from and precedes the
       *          head of the array.
       *
       *    - The term "body" is used in place of the term "head" used in the ABI
       *      documentation. It refers to the start of the data for a dynamic type,
       *      e.g. the first word of a struct or the first word of the first element
       *      in an array.
       *
       *    - The term "pointer" is used to describe the absolute position of a value
       *      and never an offset relative to another value.
       *        - The suffix "_ptr" refers to a memory pointer.
       *        - The suffix "_cdPtr" refers to a calldata pointer.
       *
       *    - The term "offset" is used to describe the position of a value relative
       *      to some parent value. For example, OrderParameters_conduit_offset is the
       *      offset to the "conduit" value in the OrderParameters struct relative to
       *      the start of the body.
       *        - Note: Offsets are used to derive pointers.
       *
       *    - Some structs have pointers defined for all of their fields in this file.
       *      Lines which are commented out are fields that are not used in the
       *      codebase but have been left in for readability.
       */
      uint256 constant AlmostOneWord = 0x1f;
      uint256 constant OneWord = 0x20;
      uint256 constant TwoWords = 0x40;
      uint256 constant ThreeWords = 0x60;
      uint256 constant FreeMemoryPointerSlot = 0x40;
      uint256 constant ZeroSlot = 0x60;
      uint256 constant DefaultFreeMemoryPointer = 0x80;
      uint256 constant Slot0x80 = 0x80;
      uint256 constant Slot0xA0 = 0xa0;
      uint256 constant Slot0xC0 = 0xc0;
      // abi.encodeWithSignature("transferFrom(address,address,uint256)")
      uint256 constant ERC20_transferFrom_signature = (
          0x23b872dd00000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC20_transferFrom_sig_ptr = 0x0;
      uint256 constant ERC20_transferFrom_from_ptr = 0x04;
      uint256 constant ERC20_transferFrom_to_ptr = 0x24;
      uint256 constant ERC20_transferFrom_amount_ptr = 0x44;
      uint256 constant ERC20_transferFrom_length = 0x64; // 4 + 32 * 3 == 100
      // abi.encodeWithSignature(
      //     "safeTransferFrom(address,address,uint256,uint256,bytes)"
      // )
      uint256 constant ERC1155_safeTransferFrom_signature = (
          0xf242432a00000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC1155_safeTransferFrom_sig_ptr = 0x0;
      uint256 constant ERC1155_safeTransferFrom_from_ptr = 0x04;
      uint256 constant ERC1155_safeTransferFrom_to_ptr = 0x24;
      uint256 constant ERC1155_safeTransferFrom_id_ptr = 0x44;
      uint256 constant ERC1155_safeTransferFrom_amount_ptr = 0x64;
      uint256 constant ERC1155_safeTransferFrom_data_offset_ptr = 0x84;
      uint256 constant ERC1155_safeTransferFrom_data_length_ptr = 0xa4;
      uint256 constant ERC1155_safeTransferFrom_length = 0xc4; // 4 + 32 * 6 == 196
      uint256 constant ERC1155_safeTransferFrom_data_length_offset = 0xa0;
      // abi.encodeWithSignature(
      //     "safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)"
      // )
      uint256 constant ERC1155_safeBatchTransferFrom_signature = (
          0x2eb2c2d600000000000000000000000000000000000000000000000000000000
      );
      bytes4 constant ERC1155_safeBatchTransferFrom_selector = bytes4(
          bytes32(ERC1155_safeBatchTransferFrom_signature)
      );
      uint256 constant ERC721_transferFrom_signature = ERC20_transferFrom_signature;
      uint256 constant ERC721_transferFrom_sig_ptr = 0x0;
      uint256 constant ERC721_transferFrom_from_ptr = 0x04;
      uint256 constant ERC721_transferFrom_to_ptr = 0x24;
      uint256 constant ERC721_transferFrom_id_ptr = 0x44;
      uint256 constant ERC721_transferFrom_length = 0x64; // 4 + 32 * 3 == 100
      // abi.encodeWithSignature("NoContract(address)")
      uint256 constant NoContract_error_signature = (
          0x5f15d67200000000000000000000000000000000000000000000000000000000
      );
      uint256 constant NoContract_error_sig_ptr = 0x0;
      uint256 constant NoContract_error_token_ptr = 0x4;
      uint256 constant NoContract_error_length = 0x24; // 4 + 32 == 36
      // abi.encodeWithSignature(
      //     "TokenTransferGenericFailure(address,address,address,uint256,uint256)"
      // )
      uint256 constant TokenTransferGenericFailure_error_signature = (
          0xf486bc8700000000000000000000000000000000000000000000000000000000
      );
      uint256 constant TokenTransferGenericFailure_error_sig_ptr = 0x0;
      uint256 constant TokenTransferGenericFailure_error_token_ptr = 0x4;
      uint256 constant TokenTransferGenericFailure_error_from_ptr = 0x24;
      uint256 constant TokenTransferGenericFailure_error_to_ptr = 0x44;
      uint256 constant TokenTransferGenericFailure_error_id_ptr = 0x64;
      uint256 constant TokenTransferGenericFailure_error_amount_ptr = 0x84;
      // 4 + 32 * 5 == 164
      uint256 constant TokenTransferGenericFailure_error_length = 0xa4;
      // abi.encodeWithSignature(
      //     "BadReturnValueFromERC20OnTransfer(address,address,address,uint256)"
      // )
      uint256 constant BadReturnValueFromERC20OnTransfer_error_signature = (
          0x9889192300000000000000000000000000000000000000000000000000000000
      );
      uint256 constant BadReturnValueFromERC20OnTransfer_error_sig_ptr = 0x0;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_token_ptr = 0x4;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_from_ptr = 0x24;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_to_ptr = 0x44;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_amount_ptr = 0x64;
      // 4 + 32 * 4 == 132
      uint256 constant BadReturnValueFromERC20OnTransfer_error_length = 0x84;
      uint256 constant ExtraGasBuffer = 0x20;
      uint256 constant CostPerWord = 3;
      uint256 constant MemoryExpansionCoefficient = 0x200;
      // Values are offset by 32 bytes in order to write the token to the beginning
      // in the event of a revert
      uint256 constant BatchTransfer1155Params_ptr = 0x24;
      uint256 constant BatchTransfer1155Params_ids_head_ptr = 0x64;
      uint256 constant BatchTransfer1155Params_amounts_head_ptr = 0x84;
      uint256 constant BatchTransfer1155Params_data_head_ptr = 0xa4;
      uint256 constant BatchTransfer1155Params_data_length_basePtr = 0xc4;
      uint256 constant BatchTransfer1155Params_calldata_baseSize = 0xc4;
      uint256 constant BatchTransfer1155Params_ids_length_ptr = 0xc4;
      uint256 constant BatchTransfer1155Params_ids_length_offset = 0xa0;
      uint256 constant BatchTransfer1155Params_amounts_length_baseOffset = 0xc0;
      uint256 constant BatchTransfer1155Params_data_length_baseOffset = 0xe0;
      uint256 constant ConduitBatch1155Transfer_usable_head_size = 0x80;
      uint256 constant ConduitBatch1155Transfer_from_offset = 0x20;
      uint256 constant ConduitBatch1155Transfer_ids_head_offset = 0x60;
      uint256 constant ConduitBatch1155Transfer_amounts_head_offset = 0x80;
      uint256 constant ConduitBatch1155Transfer_ids_length_offset = 0xa0;
      uint256 constant ConduitBatch1155Transfer_amounts_length_baseOffset = 0xc0;
      uint256 constant ConduitBatch1155Transfer_calldata_baseSize = 0xc0;
      // Note: abbreviated version of above constant to adhere to line length limit.
      uint256 constant ConduitBatchTransfer_amounts_head_offset = 0x80;
      uint256 constant Invalid1155BatchTransferEncoding_ptr = 0x00;
      uint256 constant Invalid1155BatchTransferEncoding_length = 0x04;
      uint256 constant Invalid1155BatchTransferEncoding_selector = (
          0xeba2084c00000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC1155BatchTransferGenericFailure_error_signature = (
          0xafc445e200000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC1155BatchTransferGenericFailure_token_ptr = 0x04;
      uint256 constant ERC1155BatchTransferGenericFailure_ids_offset = 0xc0;
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.7;
      /**
       * @title TokenTransferrerErrors
       */
      interface TokenTransferrerErrors {
          /**
           * @dev Revert with an error when an ERC721 transfer with amount other than
           *      one is attempted.
           */
          error InvalidERC721TransferAmount();
          /**
           * @dev Revert with an error when attempting to fulfill an order where an
           *      item has an amount of zero.
           */
          error MissingItemAmount();
          /**
           * @dev Revert with an error when attempting to fulfill an order where an
           *      item has unused parameters. This includes both the token and the
           *      identifier parameters for native transfers as well as the identifier
           *      parameter for ERC20 transfers. Note that the conduit does not
           *      perform this check, leaving it up to the calling channel to enforce
           *      when desired.
           */
          error UnusedItemParameters();
          /**
           * @dev Revert with an error when an ERC20, ERC721, or ERC1155 token
           *      transfer reverts.
           *
           * @param token      The token for which the transfer was attempted.
           * @param from       The source of the attempted transfer.
           * @param to         The recipient of the attempted transfer.
           * @param identifier The identifier for the attempted transfer.
           * @param amount     The amount for the attempted transfer.
           */
          error TokenTransferGenericFailure(
              address token,
              address from,
              address to,
              uint256 identifier,
              uint256 amount
          );
          /**
           * @dev Revert with an error when a batch ERC1155 token transfer reverts.
           *
           * @param token       The token for which the transfer was attempted.
           * @param from        The source of the attempted transfer.
           * @param to          The recipient of the attempted transfer.
           * @param identifiers The identifiers for the attempted transfer.
           * @param amounts     The amounts for the attempted transfer.
           */
          error ERC1155BatchTransferGenericFailure(
              address token,
              address from,
              address to,
              uint256[] identifiers,
              uint256[] amounts
          );
          /**
           * @dev Revert with an error when an ERC20 token transfer returns a falsey
           *      value.
           *
           * @param token      The token for which the ERC20 transfer was attempted.
           * @param from       The source of the attempted ERC20 transfer.
           * @param to         The recipient of the attempted ERC20 transfer.
           * @param amount     The amount for the attempted ERC20 transfer.
           */
          error BadReturnValueFromERC20OnTransfer(
              address token,
              address from,
              address to,
              uint256 amount
          );
          /**
           * @dev Revert with an error when an account being called as an assumed
           *      contract does not have code and returns no data.
           *
           * @param account The account that should contain code.
           */
          error NoContract(address account);
          /**
           * @dev Revert with an error when attempting to execute an 1155 batch
           *      transfer using calldata not produced by default ABI encoding or with
           *      different lengths for ids and amounts arrays.
           */
          error Invalid1155BatchTransferEncoding();
      }
      

      File 2 of 4: AiMetaChipGen1
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
      pragma solidity ^0.8.0;
      import "./IAccessControl.sol";
      import "../utils/Context.sol";
      import "../utils/Strings.sol";
      import "../utils/introspection/ERC165.sol";
      /**
       * @dev Contract module that allows children to implement role-based access
       * control mechanisms. This is a lightweight version that doesn't allow enumerating role
       * members except through off-chain means by accessing the contract event logs. Some
       * applications may benefit from on-chain enumerability, for those cases see
       * {AccessControlEnumerable}.
       *
       * Roles are referred to by their `bytes32` identifier. These should be exposed
       * in the external API and be unique. The best way to achieve this is by
       * using `public constant` hash digests:
       *
       * ```
       * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
       * ```
       *
       * Roles can be used to represent a set of permissions. To restrict access to a
       * function call, use {hasRole}:
       *
       * ```
       * function foo() public {
       *     require(hasRole(MY_ROLE, msg.sender));
       *     ...
       * }
       * ```
       *
       * Roles can be granted and revoked dynamically via the {grantRole} and
       * {revokeRole} functions. Each role has an associated admin role, and only
       * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
       *
       * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
       * that only accounts with this role will be able to grant or revoke other
       * roles. More complex role relationships can be created by using
       * {_setRoleAdmin}.
       *
       * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
       * grant and revoke this role. Extra precautions should be taken to secure
       * accounts that have been granted it.
       */
      abstract contract AccessControl is Context, IAccessControl, ERC165 {
          struct RoleData {
              mapping(address => bool) members;
              bytes32 adminRole;
          }
          mapping(bytes32 => RoleData) private _roles;
          bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
          /**
           * @dev Modifier that checks that an account has a specific role. Reverts
           * with a standardized message including the required role.
           *
           * The format of the revert reason is given by the following regular expression:
           *
           *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
           *
           * _Available since v4.1._
           */
          modifier onlyRole(bytes32 role) {
              _checkRole(role);
              _;
          }
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
          }
          /**
           * @dev Returns `true` if `account` has been granted `role`.
           */
          function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
              return _roles[role].members[account];
          }
          /**
           * @dev Revert with a standard message if `_msgSender()` is missing `role`.
           * Overriding this function changes the behavior of the {onlyRole} modifier.
           *
           * Format of the revert message is described in {_checkRole}.
           *
           * _Available since v4.6._
           */
          function _checkRole(bytes32 role) internal view virtual {
              _checkRole(role, _msgSender());
          }
          /**
           * @dev Revert with a standard message if `account` is missing `role`.
           *
           * The format of the revert reason is given by the following regular expression:
           *
           *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
           */
          function _checkRole(bytes32 role, address account) internal view virtual {
              if (!hasRole(role, account)) {
                  revert(
                      string(
                          abi.encodePacked(
                              "AccessControl: account ",
                              Strings.toHexString(account),
                              " is missing role ",
                              Strings.toHexString(uint256(role), 32)
                          )
                      )
                  );
              }
          }
          /**
           * @dev Returns the admin role that controls `role`. See {grantRole} and
           * {revokeRole}.
           *
           * To change a role's admin, use {_setRoleAdmin}.
           */
          function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
              return _roles[role].adminRole;
          }
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           *
           * May emit a {RoleGranted} event.
           */
          function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
              _grantRole(role, account);
          }
          /**
           * @dev Revokes `role` from `account`.
           *
           * If `account` had been granted `role`, emits a {RoleRevoked} event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           *
           * May emit a {RoleRevoked} event.
           */
          function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
              _revokeRole(role, account);
          }
          /**
           * @dev Revokes `role` from the calling account.
           *
           * Roles are often managed via {grantRole} and {revokeRole}: this function's
           * purpose is to provide a mechanism for accounts to lose their privileges
           * if they are compromised (such as when a trusted device is misplaced).
           *
           * If the calling account had been revoked `role`, emits a {RoleRevoked}
           * event.
           *
           * Requirements:
           *
           * - the caller must be `account`.
           *
           * May emit a {RoleRevoked} event.
           */
          function renounceRole(bytes32 role, address account) public virtual override {
              require(account == _msgSender(), "AccessControl: can only renounce roles for self");
              _revokeRole(role, account);
          }
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event. Note that unlike {grantRole}, this function doesn't perform any
           * checks on the calling account.
           *
           * May emit a {RoleGranted} event.
           *
           * [WARNING]
           * ====
           * This function should only be called from the constructor when setting
           * up the initial roles for the system.
           *
           * Using this function in any other way is effectively circumventing the admin
           * system imposed by {AccessControl}.
           * ====
           *
           * NOTE: This function is deprecated in favor of {_grantRole}.
           */
          function _setupRole(bytes32 role, address account) internal virtual {
              _grantRole(role, account);
          }
          /**
           * @dev Sets `adminRole` as ``role``'s admin role.
           *
           * Emits a {RoleAdminChanged} event.
           */
          function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
              bytes32 previousAdminRole = getRoleAdmin(role);
              _roles[role].adminRole = adminRole;
              emit RoleAdminChanged(role, previousAdminRole, adminRole);
          }
          /**
           * @dev Grants `role` to `account`.
           *
           * Internal function without access restriction.
           *
           * May emit a {RoleGranted} event.
           */
          function _grantRole(bytes32 role, address account) internal virtual {
              if (!hasRole(role, account)) {
                  _roles[role].members[account] = true;
                  emit RoleGranted(role, account, _msgSender());
              }
          }
          /**
           * @dev Revokes `role` from `account`.
           *
           * Internal function without access restriction.
           *
           * May emit a {RoleRevoked} event.
           */
          function _revokeRole(bytes32 role, address account) internal virtual {
              if (hasRole(role, account)) {
                  _roles[role].members[account] = false;
                  emit RoleRevoked(role, account, _msgSender());
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev External interface of AccessControl declared to support ERC165 detection.
       */
      interface IAccessControl {
          /**
           * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
           *
           * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
           * {RoleAdminChanged} not being emitted signaling this.
           *
           * _Available since v3.1._
           */
          event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
          /**
           * @dev Emitted when `account` is granted `role`.
           *
           * `sender` is the account that originated the contract call, an admin role
           * bearer except when using {AccessControl-_setupRole}.
           */
          event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
          /**
           * @dev Emitted when `account` is revoked `role`.
           *
           * `sender` is the account that originated the contract call:
           *   - if using `revokeRole`, it is the admin role bearer
           *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
           */
          event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
          /**
           * @dev Returns `true` if `account` has been granted `role`.
           */
          function hasRole(bytes32 role, address account) external view returns (bool);
          /**
           * @dev Returns the admin role that controls `role`. See {grantRole} and
           * {revokeRole}.
           *
           * To change a role's admin, use {AccessControl-_setRoleAdmin}.
           */
          function getRoleAdmin(bytes32 role) external view returns (bytes32);
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           */
          function grantRole(bytes32 role, address account) external;
          /**
           * @dev Revokes `role` from `account`.
           *
           * If `account` had been granted `role`, emits a {RoleRevoked} event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           */
          function revokeRole(bytes32 role, address account) external;
          /**
           * @dev Revokes `role` from the calling account.
           *
           * Roles are often managed via {grantRole} and {revokeRole}: this function's
           * purpose is to provide a mechanism for accounts to lose their privileges
           * if they are compromised (such as when a trusted device is misplaced).
           *
           * If the calling account had been granted `role`, emits a {RoleRevoked}
           * event.
           *
           * Requirements:
           *
           * - the caller must be `account`.
           */
          function renounceRole(bytes32 role, address account) external;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.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 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);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
      pragma solidity ^0.8.0;
      import "../utils/introspection/IERC165.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 IERC2981 is IERC165 {
          /**
           * @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.7.0) (token/common/ERC2981.sol)
      pragma solidity ^0.8.0;
      import "../../interfaces/IERC2981.sol";
      import "../../utils/introspection/ERC165.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 ERC2981 is IERC2981, ERC165 {
          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(IERC165, ERC165) returns (bool) {
              return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
          }
          /**
           * @inheritdoc IERC2981
           */
          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];
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
      pragma solidity ^0.8.0;
      import "../IERC721.sol";
      /**
       * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
       * @dev See https://eips.ethereum.org/EIPS/eip-721
       */
      interface IERC721Enumerable is IERC721 {
          /**
           * @dev Returns the total amount of tokens stored by the contract.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
           * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
           */
          function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
          /**
           * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
           * Use along with {totalSupply} to enumerate all tokens.
           */
          function tokenByIndex(uint256 index) external view returns (uint256);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
      pragma solidity ^0.8.0;
      import "../IERC721.sol";
      /**
       * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
       * @dev See https://eips.ethereum.org/EIPS/eip-721
       */
      interface IERC721Metadata is IERC721 {
          /**
           * @dev Returns the token collection name.
           */
          function name() external view returns (string memory);
          /**
           * @dev Returns the token collection symbol.
           */
          function symbol() external view returns (string memory);
          /**
           * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
           */
          function tokenURI(uint256 tokenId) external view returns (string memory);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165.sol";
      /**
       * @dev Required interface of an ERC721 compliant contract.
       */
      interface IERC721 is IERC165 {
          /**
           * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
           */
          event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
           */
          event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
           */
          event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
          /**
           * @dev Returns the number of tokens in ``owner``'s account.
           */
          function balanceOf(address owner) external view returns (uint256 balance);
          /**
           * @dev Returns the owner of the `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function ownerOf(uint256 tokenId) external view returns (address owner);
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              bytes calldata data
          ) external;
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
           * are aware of the ERC721 protocol to prevent tokens from being forever locked.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Transfers `tokenId` token from `from` to `to`.
           *
           * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
           * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
           * understand this adds an external call which potentially creates a reentrancy vulnerability.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Gives permission to `to` to transfer `tokenId` token to another account.
           * The approval is cleared when the token is transferred.
           *
           * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
           *
           * Requirements:
           *
           * - The caller must own the token or be an approved operator.
           * - `tokenId` must exist.
           *
           * Emits an {Approval} event.
           */
          function approve(address to, uint256 tokenId) external;
          /**
           * @dev Approve or remove `operator` as an operator for the caller.
           * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
           *
           * Requirements:
           *
           * - The `operator` cannot be the caller.
           *
           * Emits an {ApprovalForAll} event.
           */
          function setApprovalForAll(address operator, bool _approved) external;
          /**
           * @dev Returns the account approved for `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function getApproved(uint256 tokenId) external view returns (address operator);
          /**
           * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
           *
           * See {setApprovalForAll}
           */
          function isApprovedForAll(address owner, address operator) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
      pragma solidity ^0.8.0;
      /**
       * @title ERC721 token receiver interface
       * @dev Interface for any contract that wants to support safeTransfers
       * from ERC721 asset contracts.
       */
      interface IERC721Receiver {
          /**
           * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
           * by `operator` from `from`, this function is called.
           *
           * It must return its Solidity selector to confirm the token transfer.
           * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
           *
           * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      // 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 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 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 v4.4.1 (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;
          }
      }
      // 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: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Standard math utilities missing in the Solidity language.
       */
      library Math {
          enum Rounding {
              Down, // Toward negative infinity
              Up, // Toward infinity
              Zero // Toward zero
          }
          /**
           * @dev Returns the largest of two numbers.
           */
          function max(uint256 a, uint256 b) internal pure returns (uint256) {
              return a > b ? a : b;
          }
          /**
           * @dev Returns the smallest of two numbers.
           */
          function min(uint256 a, uint256 b) internal pure returns (uint256) {
              return a < b ? a : b;
          }
          /**
           * @dev Returns the average of two numbers. The result is rounded towards
           * zero.
           */
          function average(uint256 a, uint256 b) internal pure returns (uint256) {
              // (a + b) / 2 can overflow.
              return (a & b) + (a ^ b) / 2;
          }
          /**
           * @dev Returns the ceiling of the division of two numbers.
           *
           * This differs from standard division with `/` in that it rounds up instead
           * of rounding down.
           */
          function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
              // (a + b - 1) / b can overflow on addition, so we distribute.
              return a == 0 ? 0 : (a - 1) / b + 1;
          }
          /**
           * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
           * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
           * with further edits by Uniswap Labs also under MIT license.
           */
          function mulDiv(
              uint256 x,
              uint256 y,
              uint256 denominator
          ) internal pure returns (uint256 result) {
              unchecked {
                  // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                  // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                  // variables such that product = prod1 * 2^256 + prod0.
                  uint256 prod0; // Least significant 256 bits of the product
                  uint256 prod1; // Most significant 256 bits of the product
                  assembly {
                      let mm := mulmod(x, y, not(0))
                      prod0 := mul(x, y)
                      prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                  }
                  // Handle non-overflow cases, 256 by 256 division.
                  if (prod1 == 0) {
                      return prod0 / denominator;
                  }
                  // Make sure the result is less than 2^256. Also prevents denominator == 0.
                  require(denominator > prod1);
                  ///////////////////////////////////////////////
                  // 512 by 256 division.
                  ///////////////////////////////////////////////
                  // Make division exact by subtracting the remainder from [prod1 prod0].
                  uint256 remainder;
                  assembly {
                      // Compute remainder using mulmod.
                      remainder := mulmod(x, y, denominator)
                      // Subtract 256 bit number from 512 bit number.
                      prod1 := sub(prod1, gt(remainder, prod0))
                      prod0 := sub(prod0, remainder)
                  }
                  // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                  // See https://cs.stackexchange.com/q/138556/92363.
                  // Does not overflow because the denominator cannot be zero at this stage in the function.
                  uint256 twos = denominator & (~denominator + 1);
                  assembly {
                      // Divide denominator by twos.
                      denominator := div(denominator, twos)
                      // Divide [prod1 prod0] by twos.
                      prod0 := div(prod0, twos)
                      // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                      twos := add(div(sub(0, twos), twos), 1)
                  }
                  // Shift in bits from prod1 into prod0.
                  prod0 |= prod1 * twos;
                  // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                  // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                  // four bits. That is, denominator * inv = 1 mod 2^4.
                  uint256 inverse = (3 * denominator) ^ 2;
                  // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                  // in modular arithmetic, doubling the correct bits in each step.
                  inverse *= 2 - denominator * inverse; // inverse mod 2^8
                  inverse *= 2 - denominator * inverse; // inverse mod 2^16
                  inverse *= 2 - denominator * inverse; // inverse mod 2^32
                  inverse *= 2 - denominator * inverse; // inverse mod 2^64
                  inverse *= 2 - denominator * inverse; // inverse mod 2^128
                  inverse *= 2 - denominator * inverse; // inverse mod 2^256
                  // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                  // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                  // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                  // is no longer required.
                  result = prod0 * inverse;
                  return result;
              }
          }
          /**
           * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
           */
          function mulDiv(
              uint256 x,
              uint256 y,
              uint256 denominator,
              Rounding rounding
          ) internal pure returns (uint256) {
              uint256 result = mulDiv(x, y, denominator);
              if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                  result += 1;
              }
              return result;
          }
          /**
           * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
           *
           * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
           */
          function sqrt(uint256 a) internal pure returns (uint256) {
              if (a == 0) {
                  return 0;
              }
              // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
              //
              // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
              // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
              //
              // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
              // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
              // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
              //
              // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
              uint256 result = 1 << (log2(a) >> 1);
              // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
              // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
              // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
              // into the expected uint128 result.
              unchecked {
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  result = (result + a / result) >> 1;
                  return min(result, a / result);
              }
          }
          /**
           * @notice Calculates sqrt(a), following the selected rounding direction.
           */
          function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = sqrt(a);
                  return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 2, rounded down, of a positive value.
           * Returns 0 if given 0.
           */
          function log2(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >> 128 > 0) {
                      value >>= 128;
                      result += 128;
                  }
                  if (value >> 64 > 0) {
                      value >>= 64;
                      result += 64;
                  }
                  if (value >> 32 > 0) {
                      value >>= 32;
                      result += 32;
                  }
                  if (value >> 16 > 0) {
                      value >>= 16;
                      result += 16;
                  }
                  if (value >> 8 > 0) {
                      value >>= 8;
                      result += 8;
                  }
                  if (value >> 4 > 0) {
                      value >>= 4;
                      result += 4;
                  }
                  if (value >> 2 > 0) {
                      value >>= 2;
                      result += 2;
                  }
                  if (value >> 1 > 0) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log2(value);
                  return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 10, rounded down, of a positive value.
           * Returns 0 if given 0.
           */
          function log10(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >= 10**64) {
                      value /= 10**64;
                      result += 64;
                  }
                  if (value >= 10**32) {
                      value /= 10**32;
                      result += 32;
                  }
                  if (value >= 10**16) {
                      value /= 10**16;
                      result += 16;
                  }
                  if (value >= 10**8) {
                      value /= 10**8;
                      result += 8;
                  }
                  if (value >= 10**4) {
                      value /= 10**4;
                      result += 4;
                  }
                  if (value >= 10**2) {
                      value /= 10**2;
                      result += 2;
                  }
                  if (value >= 10**1) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log10(value);
                  return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
              }
          }
          /**
           * @dev Return the log in base 256, rounded down, of a positive value.
           * Returns 0 if given 0.
           *
           * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
           */
          function log256(uint256 value) internal pure returns (uint256) {
              uint256 result = 0;
              unchecked {
                  if (value >> 128 > 0) {
                      value >>= 128;
                      result += 16;
                  }
                  if (value >> 64 > 0) {
                      value >>= 64;
                      result += 8;
                  }
                  if (value >> 32 > 0) {
                      value >>= 32;
                      result += 4;
                  }
                  if (value >> 16 > 0) {
                      value >>= 16;
                      result += 2;
                  }
                  if (value >> 8 > 0) {
                      result += 1;
                  }
              }
              return result;
          }
          /**
           * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
           * Returns 0 if given 0.
           */
          function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
              unchecked {
                  uint256 result = log256(value);
                  return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
      pragma solidity ^0.8.0;
      import "./math/Math.sol";
      /**
       * @dev String operations.
       */
      library Strings {
          bytes16 private constant _SYMBOLS = "0123456789abcdef";
          uint8 private constant _ADDRESS_LENGTH = 20;
          /**
           * @dev Converts a `uint256` to its ASCII `string` decimal representation.
           */
          function toString(uint256 value) internal pure returns (string memory) {
              unchecked {
                  uint256 length = Math.log10(value) + 1;
                  string memory buffer = new string(length);
                  uint256 ptr;
                  /// @solidity memory-safe-assembly
                  assembly {
                      ptr := add(buffer, add(32, length))
                  }
                  while (true) {
                      ptr--;
                      /// @solidity memory-safe-assembly
                      assembly {
                          mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                      }
                      value /= 10;
                      if (value == 0) break;
                  }
                  return buffer;
              }
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
           */
          function toHexString(uint256 value) internal pure returns (string memory) {
              unchecked {
                  return toHexString(value, Math.log256(value) + 1);
              }
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
           */
          function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
              bytes memory buffer = new bytes(2 * length + 2);
              buffer[0] = "0";
              buffer[1] = "x";
              for (uint256 i = 2 * length + 1; i > 1; --i) {
                  buffer[i] = _SYMBOLS[value & 0xf];
                  value >>= 4;
              }
              require(value == 0, "Strings: hex length insufficient");
              return string(buffer);
          }
          /**
           * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
           */
          function toHexString(address addr) internal pure returns (string memory) {
              return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
          }
      }
      /*
      Crafted with love by
      Metablaze.xyz
      */
      //SPDX-License-Identifier: MIT
      pragma solidity ^0.8.13;
      import '@openzeppelin/contracts/access/Ownable.sol';
      import "@openzeppelin/contracts/access/AccessControl.sol";
      import '@openzeppelin/contracts/utils/Strings.sol';
      import "./ERC721ARoyalty.sol";
      contract AiMetaChipGen1 is ERC721ARoyalty, Ownable, AccessControl {
        
          using Strings for uint256;
          uint256 private constant MAX_AIRDROP = 150;
          uint256 private constant AIRDROP_SIZE = 600;
          uint256 public _maxSupply = 1000;
          uint256 public salePrice = 0.07 ether;
          uint256 public _airdroppedTokens;
          string private _baseUri;
          bytes32 public constant AIRDROP_ROLE = keccak256("AIRDROP_ROLE");
          constructor(
              string memory name,
              string memory symbol,
              uint96 feeNumerator,
              address royaltyReceiver,
              address airdropRole
          ) ERC721A(name, symbol) {
              _setDefaultRoyalty(royaltyReceiver, feeNumerator);
              _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
              _setupRole(AIRDROP_ROLE, airdropRole);
          }
          function setBaseURI(string memory baseUri) external onlyOwner {
              _baseUri = baseUri;
          }
          function _baseURI() internal view override returns (string memory) {
              return _baseUri;
          }
          function setSalePrice(uint256 newSalePrice) external onlyOwner {
              require(newSalePrice > 0, "Wrong sale price");
              salePrice = newSalePrice;
          }
          function reduceMaxSupply(uint256 newMaxSupply) external onlyOwner {
              require(newMaxSupply < _maxSupply, "New max supply exceeds max supply");
              require(totalSupply() <= newMaxSupply, "Total supply exceeds new max supply");
              _maxSupply = newMaxSupply;
          }
          function mint(uint256 quantity) external payable {
              require(quantity > 0, "Wrong Quantity");
              require(totalSupply() + quantity <= _maxSupply, "Exceeds max supply");
              require(msg.value == salePrice*quantity, "Wrong mint price");
              address sender = _msgSender();
              _safeMint(sender, quantity);
          }
          function airdrop(address[] memory receivers) external onlyRole(AIRDROP_ROLE) {
              uint256 size = receivers.length;
              require(size <= MAX_AIRDROP, "Receiver array too long");
              require(_airdroppedTokens + size <= AIRDROP_SIZE, "Exceeds airdrop size");
              require(totalSupply() + size <= _maxSupply, "Exceeds max supply");
              _airdroppedTokens += size;
              for(uint16 i; i < size; i++) {
                  _safeMint(receivers[i], 1);
              }
          }
          /** Royalties */
          function setDefaultRoyalty(address receiver, uint96 feeNumerator) external onlyOwner {
              _setDefaultRoyalty(receiver, feeNumerator);
          }
          function withdraw(address payable receiver) external onlyOwner {
              receiver.transfer(address(this).balance);
          }
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721ARoyalty, AccessControl) returns (bool) {
              return super.supportsInterface(interfaceId);
          }
          function tokenURI(uint256 tokenId) override public view returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                string memory baseURI = _baseURI();
                return bytes(baseURI).length != 0 ? string(
                      abi.encodePacked(
                          baseURI,
                          tokenId.toString(),
                          ".json"
                      )) : '';
          }
      }
      // SPDX-License-Identifier: MIT
      // Creator: Chiru Labs
      // Fork of ERC721A.sol (it's not the same one as on npm package erc721a because this one has extension methods removed)
      pragma solidity ^0.8.4;
      import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
      import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
      import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
      import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
      import '@openzeppelin/contracts/utils/Address.sol';
      import '@openzeppelin/contracts/utils/Context.sol';
      import '@openzeppelin/contracts/utils/Strings.sol';
      import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
      error ApprovalCallerNotOwnerNorApproved();
      error ApprovalQueryForNonexistentToken();
      error ApproveToCaller();
      error ApprovalToCurrentOwner();
      error BalanceQueryForZeroAddress();
      error MintedQueryForZeroAddress();
      error BurnedQueryForZeroAddress();
      error MintToZeroAddress();
      error MintZeroQuantity();
      error OwnerIndexOutOfBounds();
      error OwnerQueryForNonexistentToken();
      error TokenIndexOutOfBounds();
      error TransferCallerNotOwnerNorApproved();
      error TransferFromIncorrectOwner();
      error TransferToNonERC721ReceiverImplementer();
      error TransferToZeroAddress();
      error URIQueryForNonexistentToken();
      /**
       * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
       * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
       *
       * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
       *
       * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
       *
       * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
       */
      contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
          using Address for address;
          using Strings for uint256;
          // Compiler will pack this into a single 256bit word.
          struct TokenOwnership {
              // The address of the owner.
              address addr;
              // Keeps track of the start time of ownership with minimal overhead for tokenomics.
              uint64 startTimestamp;
              // Whether the token has been burned.
              bool burned;
          }
          // Compiler will pack this into a single 256bit word.
          struct AddressData {
              // Realistically, 2**64-1 is more than enough.
              uint64 balance;
              // Keeps track of mint count with minimal overhead for tokenomics.
              uint64 numberMinted;
              // Keeps track of burn count with minimal overhead for tokenomics.
              uint64 numberBurned;
          }
          // The tokenId of the next token to be minted.
          uint256 internal _currentIndex;
          // The number of tokens burned.
          uint256 internal _burnCounter;
          // Token name
          string private _name;
          // Token symbol
          string private _symbol;
          // Mapping from token ID to ownership details
          // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
          mapping(uint256 => TokenOwnership) internal _ownerships;
          // Mapping owner address to address data
          mapping(address => AddressData) private _addressData;
          // Mapping from token ID to approved address
          mapping(uint256 => address) private _tokenApprovals;
          // Mapping from owner to operator approvals
          mapping(address => mapping(address => bool)) private _operatorApprovals;
          constructor(string memory name_, string memory symbol_) {
              _name = name_;
              _symbol = symbol_;
          }
          /**
           * @dev See {IERC721Enumerable-totalSupply}.
           */
          function totalSupply() public view returns (uint256) {
              // Counter underflow is impossible as _burnCounter cannot be incremented
              // more than _currentIndex times
              unchecked {
                  return _currentIndex - _burnCounter;
              }
          }
          /**
           * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
           * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
           * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
           */
          function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
              if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds();
              uint256 numMintedSoFar = _currentIndex;
              uint256 tokenIdsIdx;
              address currOwnershipAddr;
              // Counter overflow is impossible as the loop breaks when
              // uint256 i is equal to another uint256 numMintedSoFar.
              unchecked {
                  for (uint256 i; i < numMintedSoFar; i++) {
                      TokenOwnership memory ownership = _ownerships[i];
                      if (ownership.burned) {
                          continue;
                      }
                      if (ownership.addr != address(0)) {
                          currOwnershipAddr = ownership.addr;
                      }
                      if (currOwnershipAddr == owner) {
                          if (tokenIdsIdx == index) {
                              return i;
                          }
                          tokenIdsIdx++;
                      }
                  }
              }
              // Execution should never reach this point.
              revert();
          }
          /**
           * @dev See {IERC721Enumerable-tokenByIndex}.
           * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
           * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
           */
          function tokenByIndex(uint256 index) public view override returns (uint256) {
              uint256 numMintedSoFar = _currentIndex;
              uint256 tokenIdsIdx;
              // Counter overflow is impossible as the loop breaks when
              // uint256 i is equal to another uint256 numMintedSoFar.
              unchecked {
                  for (uint256 i; i < numMintedSoFar; i++) {
                      TokenOwnership memory ownership = _ownerships[i];
                      if (!ownership.burned) {
                          if (tokenIdsIdx == index) {
                              return i;
                          }
                          tokenIdsIdx++;
                      }
                  }
              }
              revert TokenIndexOutOfBounds();
          }
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return
                  interfaceId == type(IERC721).interfaceId ||
                  interfaceId == type(IERC721Metadata).interfaceId ||
                  super.supportsInterface(interfaceId);
          }
          /**
           * @dev See {IERC721-balanceOf}.
           */
          function balanceOf(address owner) public view override returns (uint256) {
              if (owner == address(0)) revert BalanceQueryForZeroAddress();
              return uint256(_addressData[owner].balance);
          }
          function _numberMinted(address owner) internal view returns (uint256) {
              if (owner == address(0)) revert MintedQueryForZeroAddress();
              return uint256(_addressData[owner].numberMinted);
          }
          function _numberBurned(address owner) internal view returns (uint256) {
              if (owner == address(0)) revert BurnedQueryForZeroAddress();
              return uint256(_addressData[owner].numberBurned);
          }
          /**
           * Gas spent here starts off proportional to the maximum mint batch size.
           * It gradually moves to O(1) as tokens get transferred around in the collection over time.
           */
          function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
              uint256 curr = tokenId;
              unchecked {
                  if (curr < _currentIndex) {
                      TokenOwnership memory ownership = _ownerships[curr];
                      if (!ownership.burned) {
                          if (ownership.addr != address(0)) {
                              return ownership;
                          }
                          // Invariant:
                          // There will always be an ownership that has an address and is not burned
                          // before an ownership that does not have an address and is not burned.
                          // Hence, curr will not underflow.
                          while (true) {
                              curr--;
                              ownership = _ownerships[curr];
                              if (ownership.addr != address(0)) {
                                  return ownership;
                              }
                          }
                      }
                  }
              }
              revert OwnerQueryForNonexistentToken();
          }
          /**
           * @dev See {IERC721-ownerOf}.
           */
          function ownerOf(uint256 tokenId) public view override returns (address) {
              return ownershipOf(tokenId).addr;
          }
          /**
           * @dev See {IERC721Metadata-name}.
           */
          function name() public view virtual override returns (string memory) {
              return _name;
          }
          /**
           * @dev See {IERC721Metadata-symbol}.
           */
          function symbol() public view virtual override returns (string memory) {
              return _symbol;
          }
          /**
           * @dev See {IERC721Metadata-tokenURI}.
           */
          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, tokenId.toString())) : '';
          }
          /**
           * @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, can be overriden in child contracts.
           */
          function _baseURI() internal view virtual returns (string memory) {
              return '';
          }
          /**
           * @dev See {IERC721-approve}.
           */
          function approve(address to, uint256 tokenId) public override {
              address owner = ERC721A.ownerOf(tokenId);
              if (to == owner) revert ApprovalToCurrentOwner();
              if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
                  revert ApprovalCallerNotOwnerNorApproved();
              }
              _approve(to, tokenId, owner);
          }
          /**
           * @dev See {IERC721-getApproved}.
           */
          function getApproved(uint256 tokenId) public view override returns (address) {
              if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
              return _tokenApprovals[tokenId];
          }
          /**
           * @dev See {IERC721-setApprovalForAll}.
           */
          function setApprovalForAll(address operator, bool approved) public override {
              if (operator == _msgSender()) revert ApproveToCaller();
              _operatorApprovals[_msgSender()][operator] = approved;
              emit ApprovalForAll(_msgSender(), operator, approved);
          }
          /**
           * @dev See {IERC721-isApprovedForAll}.
           */
          function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
              return _operatorApprovals[owner][operator];
          }
          /**
           * @dev See {IERC721-transferFrom}.
           */
          function transferFrom(
              address from,
              address to,
              uint256 tokenId
          ) public virtual override {
              _transfer(from, to, tokenId);
          }
          /**
           * @dev See {IERC721-safeTransferFrom}.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) public virtual override {
              _transfer(from, to, tokenId);
              if (!_checkOnERC721Received(from, to, tokenId, "")) {
                  revert TransferToNonERC721ReceiverImplementer();
              }
          }
          /**
           * @dev See {IERC721-safeTransferFrom}.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              bytes memory _data
          ) public virtual override {
              _transfer(from, to, tokenId);
              if (!_checkOnERC721Received(from, to, tokenId, _data)) {
                  revert TransferToNonERC721ReceiverImplementer();
              }
          }
          /**
           * @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 (`_mint`),
           */
          function _exists(uint256 tokenId) internal view returns (bool) {
              return tokenId < _currentIndex && !_ownerships[tokenId].burned;
          }
          function _safeMint(address to, uint256 quantity) internal {
              _safeMint(to, 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.
           *
           * Emits a {Transfer} event.
           */
          function _safeMint(
              address to,
              uint256 quantity,
              bytes memory _data
          ) internal {
              _mint(to, quantity, _data, true);
          }
          /**
           * @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.
           */
          function _mint(
              address to,
              uint256 quantity,
              bytes memory _data,
              bool safe
          ) internal {
              uint256 startTokenId = _currentIndex;
              if (to == address(0)) revert MintToZeroAddress();
              if (quantity == 0) revert MintZeroQuantity();
              _beforeTokenTransfers(address(0), to, startTokenId, quantity);
              // Overflows are incredibly unrealistic.
              // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
              // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
              unchecked {
                  _addressData[to].balance += uint64(quantity);
                  _addressData[to].numberMinted += uint64(quantity);
                  _ownerships[startTokenId].addr = to;
                  _ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
                  uint256 updatedIndex = startTokenId;
                  for (uint256 i; i < quantity; i++) {
                      emit Transfer(address(0), to, updatedIndex);
                      if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
                          revert TransferToNonERC721ReceiverImplementer();
                      }
                      updatedIndex++;
                  }
                  _currentIndex = updatedIndex;
              }
              _afterTokenTransfers(address(0), to, startTokenId, quantity);
          }
          /**
           * @dev Transfers `tokenId` from `from` to `to`.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `tokenId` token must be owned by `from`.
           *
           * Emits a {Transfer} event.
           */
          function _transfer(
              address from,
              address to,
              uint256 tokenId
          ) private {
              TokenOwnership memory prevOwnership = ownershipOf(tokenId);
              bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
                  isApprovedForAll(prevOwnership.addr, _msgSender()) ||
                  getApproved(tokenId) == _msgSender());
              if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
              if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
              if (to == address(0)) revert TransferToZeroAddress();
              _beforeTokenTransfers(from, to, tokenId, 1);
              // Clear approvals from the previous owner
              _approve(address(0), tokenId, prevOwnership.addr);
              // 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 {
                  _addressData[from].balance -= 1;
                  _addressData[to].balance += 1;
                  _ownerships[tokenId].addr = to;
                  _ownerships[tokenId].startTimestamp = uint64(block.timestamp);
                  // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
                  // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
                  uint256 nextTokenId = tokenId + 1;
                  if (_ownerships[nextTokenId].addr == address(0)) {
                      // This will suffice for checking _exists(nextTokenId),
                      // as a burned slot cannot contain the zero address.
                      if (nextTokenId < _currentIndex) {
                          _ownerships[nextTokenId].addr = prevOwnership.addr;
                          _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
                      }
                  }
              }
              emit Transfer(from, to, tokenId);
              _afterTokenTransfers(from, to, tokenId, 1);
          }
          /**
           * @dev Destroys `tokenId`.
           * The approval is cleared when the token is burned.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           *
           * Emits a {Transfer} event.
           */
          function _burn(uint256 tokenId) internal virtual {
              TokenOwnership memory prevOwnership = ownershipOf(tokenId);
              _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
              // Clear approvals from the previous owner
              _approve(address(0), tokenId, prevOwnership.addr);
              // 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 {
                  _addressData[prevOwnership.addr].balance -= 1;
                  _addressData[prevOwnership.addr].numberBurned += 1;
                  // Keep track of who burned the token, and the timestamp of burning.
                  _ownerships[tokenId].addr = prevOwnership.addr;
                  _ownerships[tokenId].startTimestamp = uint64(block.timestamp);
                  _ownerships[tokenId].burned = true;
                  // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
                  // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
                  uint256 nextTokenId = tokenId + 1;
                  if (_ownerships[nextTokenId].addr == address(0)) {
                      // This will suffice for checking _exists(nextTokenId),
                      // as a burned slot cannot contain the zero address.
                      if (nextTokenId < _currentIndex) {
                          _ownerships[nextTokenId].addr = prevOwnership.addr;
                          _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
                      }
                  }
              }
              emit Transfer(prevOwnership.addr, address(0), tokenId);
              _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
              // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
              unchecked {
                  _burnCounter++;
              }
          }
          /**
           * @dev Approve `to` to operate on `tokenId`
           *
           * Emits a {Approval} event.
           */
          function _approve(
              address to,
              uint256 tokenId,
              address owner
          ) private {
              _tokenApprovals[tokenId] = to;
              emit Approval(owner, to, tokenId);
          }
          /**
           * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
           * The call is not executed if the target address is not a contract.
           *
           * @param from address representing the previous owner of the given token ID
           * @param to target address that will receive the tokens
           * @param tokenId uint256 ID of the token to be transferred
           * @param _data bytes optional data to send along with the call
           * @return bool whether the call correctly returned the expected magic value
           */
          function _checkOnERC721Received(
              address from,
              address to,
              uint256 tokenId,
              bytes memory _data
          ) private returns (bool) {
              if (to.isContract()) {
                  try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                      return retval == IERC721Receiver(to).onERC721Received.selector;
                  } catch (bytes memory reason) {
                      if (reason.length == 0) {
                          revert TransferToNonERC721ReceiverImplementer();
                      } else {
                          assembly {
                              revert(add(32, reason), mload(reason))
                          }
                      }
                  }
              } else {
                  return true;
              }
          }
          /**
           * @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 {}
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol)
      pragma solidity ^0.8.0;
      import "@openzeppelin/contracts/token/common/ERC2981.sol";
      import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
      import "./ERC721A.sol";
      /**
       * @dev Extension of ERC721 with the ERC2981 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.
       *
       * 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 ERC721ARoyalty is ERC2981, ERC721A {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A, ERC2981) returns (bool) {
              return super.supportsInterface(interfaceId);
          }
          /**
           * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token.
           */
          function _burn(uint256 tokenId) internal virtual override {
              super._burn(tokenId);
              _resetTokenRoyalty(tokenId);
          }
      }
      

      File 3 of 4: MetaBlazeMetaGoblins
      /*
      Crafted with love by
      Metablaze
      */
      //SPDX-License-Identifier: MIT
      pragma solidity ^0.8.13;
      //200NFTs contract, receive the royalties from 10000NFTs contract
      import '@openzeppelin/contracts/access/Ownable.sol';
      import "@openzeppelin/contracts/access/AccessControl.sol";
      import '@openzeppelin/contracts/utils/Strings.sol';
      import "./ERC721ARoyalty.sol";
      contract MetaBlazeMetaGoblins is ERC721ARoyalty, Ownable, AccessControl {
          event NewPhase(uint8 phase);
          using Strings for uint256;
          // 10 phases of 1000 Nfts each
          uint256 private constant PHASE_SIZE = 1000;
          uint256 private constant AIRDROP_SIZE = 1000;
          uint256 private constant MAX_AIRDROP = 250;
          uint256 private _maxSupply = 10000;
          uint256 private _airdroppedTokens;
          bytes32 public constant AIRDROP_ROLE = keccak256("AIRDROP_ROLE");
          uint8 public currentPhase;
          uint256 public salePrice = 0.2 ether;
          string private _baseUri;
          mapping(uint8 => uint256) public phaseMintedTokens;
          constructor(
              string memory name,
              string memory symbol,
              uint96 feeNumerator,
              address royaltyReceiver,
              address airdropRole
          ) ERC721A(name, symbol) {
              _setDefaultRoyalty(royaltyReceiver, feeNumerator);
              _setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
              _setupRole(AIRDROP_ROLE, airdropRole);
          }
          function setBaseURI(string memory baseUri) external onlyOwner {
              _baseUri = baseUri;
          }
          /// @dev override base uri. It will be combined with token ID
          function _baseURI() internal view override returns (string memory) {
              return _baseUri;
          }
          function setNextPhase() external onlyOwner {
              require(currentPhase < 8, "All phases done");
              currentPhase += 1;
              emit NewPhase(currentPhase);
          }
          function setSalePrice(uint256 newSalePrice) external onlyOwner {
              require(newSalePrice > 0, "Wrong sale price");
              salePrice = newSalePrice;
          }
          function reduceMaxSupply(uint256 newMaxSupply) external onlyOwner {
              require(newMaxSupply < _maxSupply, "New max supply exceeds max supply");
              require(totalSupply() <= newMaxSupply, "Total supply exceeds new max supply");
              _maxSupply = newMaxSupply;
          }
          function airdrop(address[] memory receivers) external onlyRole(AIRDROP_ROLE) {
              uint256 size = receivers.length;
              require(size <= MAX_AIRDROP, "Receiver array too long");
              require(_airdroppedTokens + size <= AIRDROP_SIZE, "Exceeds airdrop size");
              require(totalSupply() + size <= _maxSupply, "Exceeds max supply");
              _airdroppedTokens += size;
              for(uint16 i; i < size; i++) {
                  _safeMint(receivers[i], 1);
              }
          }
          function mint(uint256 quantity) external payable {
              uint8 phase = currentPhase;
              require(quantity > 0, "Wrong Quantity");
              require(totalSupply() + quantity <= _maxSupply, "Exceeds max supply");
              require(msg.value == salePrice*quantity, "Wrong mint price");
              address sender = _msgSender();
              phaseMintedTokens[phase] += quantity;
              require(phaseMintedTokens[phase] <= PHASE_SIZE, "Reached phase size");
              _safeMint(sender, quantity);
          }
          /** Royalties */
          function setDefaultRoyalty(address receiver, uint96 feeNumerator) external onlyOwner {
              _setDefaultRoyalty(receiver, feeNumerator);
          }
          function withdraw(address payable receiver) external onlyOwner {
              receiver.transfer(address(this).balance);
          }
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721ARoyalty, AccessControl) returns (bool) {
              return super.supportsInterface(interfaceId);
          }
          function tokenURI(uint256 tokenId) override public view returns (string memory) {
                if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
                string memory baseURI = _baseURI();
                return bytes(baseURI).length != 0 ? string(
                      abi.encodePacked(
                          baseURI,
                          tokenId.toString(),
                          ".json"
                      )) : '';
              }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol)
      pragma solidity ^0.8.0;
      import "@openzeppelin/contracts/token/common/ERC2981.sol";
      import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
      import "./ERC721A.sol";
      /**
       * @dev Extension of ERC721 with the ERC2981 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.
       *
       * 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 ERC721ARoyalty is ERC2981, ERC721A {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A, ERC2981) returns (bool) {
              return super.supportsInterface(interfaceId);
          }
          /**
           * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token.
           */
          function _burn(uint256 tokenId) internal virtual override {
              super._burn(tokenId);
              _resetTokenRoyalty(tokenId);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)
      pragma solidity ^0.8.0;
      import "./IAccessControl.sol";
      import "../utils/Context.sol";
      import "../utils/Strings.sol";
      import "../utils/introspection/ERC165.sol";
      /**
       * @dev Contract module that allows children to implement role-based access
       * control mechanisms. This is a lightweight version that doesn't allow enumerating role
       * members except through off-chain means by accessing the contract event logs. Some
       * applications may benefit from on-chain enumerability, for those cases see
       * {AccessControlEnumerable}.
       *
       * Roles are referred to by their `bytes32` identifier. These should be exposed
       * in the external API and be unique. The best way to achieve this is by
       * using `public constant` hash digests:
       *
       * ```
       * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
       * ```
       *
       * Roles can be used to represent a set of permissions. To restrict access to a
       * function call, use {hasRole}:
       *
       * ```
       * function foo() public {
       *     require(hasRole(MY_ROLE, msg.sender));
       *     ...
       * }
       * ```
       *
       * Roles can be granted and revoked dynamically via the {grantRole} and
       * {revokeRole} functions. Each role has an associated admin role, and only
       * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
       *
       * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
       * that only accounts with this role will be able to grant or revoke other
       * roles. More complex role relationships can be created by using
       * {_setRoleAdmin}.
       *
       * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
       * grant and revoke this role. Extra precautions should be taken to secure
       * accounts that have been granted it.
       */
      abstract contract AccessControl is Context, IAccessControl, ERC165 {
          struct RoleData {
              mapping(address => bool) members;
              bytes32 adminRole;
          }
          mapping(bytes32 => RoleData) private _roles;
          bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
          /**
           * @dev Modifier that checks that an account has a specific role. Reverts
           * with a standardized message including the required role.
           *
           * The format of the revert reason is given by the following regular expression:
           *
           *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
           *
           * _Available since v4.1._
           */
          modifier onlyRole(bytes32 role) {
              _checkRole(role);
              _;
          }
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
          }
          /**
           * @dev Returns `true` if `account` has been granted `role`.
           */
          function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
              return _roles[role].members[account];
          }
          /**
           * @dev Revert with a standard message if `_msgSender()` is missing `role`.
           * Overriding this function changes the behavior of the {onlyRole} modifier.
           *
           * Format of the revert message is described in {_checkRole}.
           *
           * _Available since v4.6._
           */
          function _checkRole(bytes32 role) internal view virtual {
              _checkRole(role, _msgSender());
          }
          /**
           * @dev Revert with a standard message if `account` is missing `role`.
           *
           * The format of the revert reason is given by the following regular expression:
           *
           *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
           */
          function _checkRole(bytes32 role, address account) internal view virtual {
              if (!hasRole(role, account)) {
                  revert(
                      string(
                          abi.encodePacked(
                              "AccessControl: account ",
                              Strings.toHexString(uint160(account), 20),
                              " is missing role ",
                              Strings.toHexString(uint256(role), 32)
                          )
                      )
                  );
              }
          }
          /**
           * @dev Returns the admin role that controls `role`. See {grantRole} and
           * {revokeRole}.
           *
           * To change a role's admin, use {_setRoleAdmin}.
           */
          function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
              return _roles[role].adminRole;
          }
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           *
           * May emit a {RoleGranted} event.
           */
          function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
              _grantRole(role, account);
          }
          /**
           * @dev Revokes `role` from `account`.
           *
           * If `account` had been granted `role`, emits a {RoleRevoked} event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           *
           * May emit a {RoleRevoked} event.
           */
          function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
              _revokeRole(role, account);
          }
          /**
           * @dev Revokes `role` from the calling account.
           *
           * Roles are often managed via {grantRole} and {revokeRole}: this function's
           * purpose is to provide a mechanism for accounts to lose their privileges
           * if they are compromised (such as when a trusted device is misplaced).
           *
           * If the calling account had been revoked `role`, emits a {RoleRevoked}
           * event.
           *
           * Requirements:
           *
           * - the caller must be `account`.
           *
           * May emit a {RoleRevoked} event.
           */
          function renounceRole(bytes32 role, address account) public virtual override {
              require(account == _msgSender(), "AccessControl: can only renounce roles for self");
              _revokeRole(role, account);
          }
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event. Note that unlike {grantRole}, this function doesn't perform any
           * checks on the calling account.
           *
           * May emit a {RoleGranted} event.
           *
           * [WARNING]
           * ====
           * This function should only be called from the constructor when setting
           * up the initial roles for the system.
           *
           * Using this function in any other way is effectively circumventing the admin
           * system imposed by {AccessControl}.
           * ====
           *
           * NOTE: This function is deprecated in favor of {_grantRole}.
           */
          function _setupRole(bytes32 role, address account) internal virtual {
              _grantRole(role, account);
          }
          /**
           * @dev Sets `adminRole` as ``role``'s admin role.
           *
           * Emits a {RoleAdminChanged} event.
           */
          function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
              bytes32 previousAdminRole = getRoleAdmin(role);
              _roles[role].adminRole = adminRole;
              emit RoleAdminChanged(role, previousAdminRole, adminRole);
          }
          /**
           * @dev Grants `role` to `account`.
           *
           * Internal function without access restriction.
           *
           * May emit a {RoleGranted} event.
           */
          function _grantRole(bytes32 role, address account) internal virtual {
              if (!hasRole(role, account)) {
                  _roles[role].members[account] = true;
                  emit RoleGranted(role, account, _msgSender());
              }
          }
          /**
           * @dev Revokes `role` from `account`.
           *
           * Internal function without access restriction.
           *
           * May emit a {RoleRevoked} event.
           */
          function _revokeRole(bytes32 role, address account) internal virtual {
              if (hasRole(role, account)) {
                  _roles[role].members[account] = false;
                  emit RoleRevoked(role, account, _msgSender());
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.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 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);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev String operations.
       */
      library Strings {
          bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
          uint8 private constant _ADDRESS_LENGTH = 20;
          /**
           * @dev Converts a `uint256` to its ASCII `string` decimal representation.
           */
          function toString(uint256 value) internal pure returns (string memory) {
              // Inspired by OraclizeAPI's implementation - MIT licence
              // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
              if (value == 0) {
                  return "0";
              }
              uint256 temp = value;
              uint256 digits;
              while (temp != 0) {
                  digits++;
                  temp /= 10;
              }
              bytes memory buffer = new bytes(digits);
              while (value != 0) {
                  digits -= 1;
                  buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                  value /= 10;
              }
              return string(buffer);
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
           */
          function toHexString(uint256 value) internal pure returns (string memory) {
              if (value == 0) {
                  return "0x00";
              }
              uint256 temp = value;
              uint256 length = 0;
              while (temp != 0) {
                  length++;
                  temp >>= 8;
              }
              return toHexString(value, length);
          }
          /**
           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
           */
          function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
              bytes memory buffer = new bytes(2 * length + 2);
              buffer[0] = "0";
              buffer[1] = "x";
              for (uint256 i = 2 * length + 1; i > 1; --i) {
                  buffer[i] = _HEX_SYMBOLS[value & 0xf];
                  value >>= 4;
              }
              require(value == 0, "Strings: hex length insufficient");
              return string(buffer);
          }
          /**
           * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
           */
          function toHexString(address addr) internal pure returns (string memory) {
              return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
          }
      }
      // SPDX-License-Identifier: MIT
      // Creator: Chiru Labs
      // Fork of ERC721A.sol (it's not the same one as on npm package erc721a because this one has extension methods removed)
      pragma solidity ^0.8.4;
      import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
      import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
      import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
      import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
      import '@openzeppelin/contracts/utils/Address.sol';
      import '@openzeppelin/contracts/utils/Context.sol';
      import '@openzeppelin/contracts/utils/Strings.sol';
      import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
      error ApprovalCallerNotOwnerNorApproved();
      error ApprovalQueryForNonexistentToken();
      error ApproveToCaller();
      error ApprovalToCurrentOwner();
      error BalanceQueryForZeroAddress();
      error MintedQueryForZeroAddress();
      error BurnedQueryForZeroAddress();
      error MintToZeroAddress();
      error MintZeroQuantity();
      error OwnerIndexOutOfBounds();
      error OwnerQueryForNonexistentToken();
      error TokenIndexOutOfBounds();
      error TransferCallerNotOwnerNorApproved();
      error TransferFromIncorrectOwner();
      error TransferToNonERC721ReceiverImplementer();
      error TransferToZeroAddress();
      error URIQueryForNonexistentToken();
      /**
       * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
       * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
       *
       * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
       *
       * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
       *
       * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
       */
      contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
          using Address for address;
          using Strings for uint256;
          // Compiler will pack this into a single 256bit word.
          struct TokenOwnership {
              // The address of the owner.
              address addr;
              // Keeps track of the start time of ownership with minimal overhead for tokenomics.
              uint64 startTimestamp;
              // Whether the token has been burned.
              bool burned;
          }
          // Compiler will pack this into a single 256bit word.
          struct AddressData {
              // Realistically, 2**64-1 is more than enough.
              uint64 balance;
              // Keeps track of mint count with minimal overhead for tokenomics.
              uint64 numberMinted;
              // Keeps track of burn count with minimal overhead for tokenomics.
              uint64 numberBurned;
          }
          // The tokenId of the next token to be minted.
          uint256 internal _currentIndex;
          // The number of tokens burned.
          uint256 internal _burnCounter;
          // Token name
          string private _name;
          // Token symbol
          string private _symbol;
          // Mapping from token ID to ownership details
          // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
          mapping(uint256 => TokenOwnership) internal _ownerships;
          // Mapping owner address to address data
          mapping(address => AddressData) private _addressData;
          // Mapping from token ID to approved address
          mapping(uint256 => address) private _tokenApprovals;
          // Mapping from owner to operator approvals
          mapping(address => mapping(address => bool)) private _operatorApprovals;
          constructor(string memory name_, string memory symbol_) {
              _name = name_;
              _symbol = symbol_;
          }
          /**
           * @dev See {IERC721Enumerable-totalSupply}.
           */
          function totalSupply() public view returns (uint256) {
              // Counter underflow is impossible as _burnCounter cannot be incremented
              // more than _currentIndex times
              unchecked {
                  return _currentIndex - _burnCounter;
              }
          }
          /**
           * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
           * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
           * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
           */
          function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
              if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds();
              uint256 numMintedSoFar = _currentIndex;
              uint256 tokenIdsIdx;
              address currOwnershipAddr;
              // Counter overflow is impossible as the loop breaks when
              // uint256 i is equal to another uint256 numMintedSoFar.
              unchecked {
                  for (uint256 i; i < numMintedSoFar; i++) {
                      TokenOwnership memory ownership = _ownerships[i];
                      if (ownership.burned) {
                          continue;
                      }
                      if (ownership.addr != address(0)) {
                          currOwnershipAddr = ownership.addr;
                      }
                      if (currOwnershipAddr == owner) {
                          if (tokenIdsIdx == index) {
                              return i;
                          }
                          tokenIdsIdx++;
                      }
                  }
              }
              // Execution should never reach this point.
              revert();
          }
          /**
           * @dev See {IERC721Enumerable-tokenByIndex}.
           * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
           * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
           */
          function tokenByIndex(uint256 index) public view override returns (uint256) {
              uint256 numMintedSoFar = _currentIndex;
              uint256 tokenIdsIdx;
              // Counter overflow is impossible as the loop breaks when
              // uint256 i is equal to another uint256 numMintedSoFar.
              unchecked {
                  for (uint256 i; i < numMintedSoFar; i++) {
                      TokenOwnership memory ownership = _ownerships[i];
                      if (!ownership.burned) {
                          if (tokenIdsIdx == index) {
                              return i;
                          }
                          tokenIdsIdx++;
                      }
                  }
              }
              revert TokenIndexOutOfBounds();
          }
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return
                  interfaceId == type(IERC721).interfaceId ||
                  interfaceId == type(IERC721Metadata).interfaceId ||
                  super.supportsInterface(interfaceId);
          }
          /**
           * @dev See {IERC721-balanceOf}.
           */
          function balanceOf(address owner) public view override returns (uint256) {
              if (owner == address(0)) revert BalanceQueryForZeroAddress();
              return uint256(_addressData[owner].balance);
          }
          function _numberMinted(address owner) internal view returns (uint256) {
              if (owner == address(0)) revert MintedQueryForZeroAddress();
              return uint256(_addressData[owner].numberMinted);
          }
          function _numberBurned(address owner) internal view returns (uint256) {
              if (owner == address(0)) revert BurnedQueryForZeroAddress();
              return uint256(_addressData[owner].numberBurned);
          }
          /**
           * Gas spent here starts off proportional to the maximum mint batch size.
           * It gradually moves to O(1) as tokens get transferred around in the collection over time.
           */
          function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
              uint256 curr = tokenId;
              unchecked {
                  if (curr < _currentIndex) {
                      TokenOwnership memory ownership = _ownerships[curr];
                      if (!ownership.burned) {
                          if (ownership.addr != address(0)) {
                              return ownership;
                          }
                          // Invariant:
                          // There will always be an ownership that has an address and is not burned
                          // before an ownership that does not have an address and is not burned.
                          // Hence, curr will not underflow.
                          while (true) {
                              curr--;
                              ownership = _ownerships[curr];
                              if (ownership.addr != address(0)) {
                                  return ownership;
                              }
                          }
                      }
                  }
              }
              revert OwnerQueryForNonexistentToken();
          }
          /**
           * @dev See {IERC721-ownerOf}.
           */
          function ownerOf(uint256 tokenId) public view override returns (address) {
              return ownershipOf(tokenId).addr;
          }
          /**
           * @dev See {IERC721Metadata-name}.
           */
          function name() public view virtual override returns (string memory) {
              return _name;
          }
          /**
           * @dev See {IERC721Metadata-symbol}.
           */
          function symbol() public view virtual override returns (string memory) {
              return _symbol;
          }
          /**
           * @dev See {IERC721Metadata-tokenURI}.
           */
          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, tokenId.toString())) : '';
          }
          /**
           * @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, can be overriden in child contracts.
           */
          function _baseURI() internal view virtual returns (string memory) {
              return '';
          }
          /**
           * @dev See {IERC721-approve}.
           */
          function approve(address to, uint256 tokenId) public override {
              address owner = ERC721A.ownerOf(tokenId);
              if (to == owner) revert ApprovalToCurrentOwner();
              if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
                  revert ApprovalCallerNotOwnerNorApproved();
              }
              _approve(to, tokenId, owner);
          }
          /**
           * @dev See {IERC721-getApproved}.
           */
          function getApproved(uint256 tokenId) public view override returns (address) {
              if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
              return _tokenApprovals[tokenId];
          }
          /**
           * @dev See {IERC721-setApprovalForAll}.
           */
          function setApprovalForAll(address operator, bool approved) public override {
              if (operator == _msgSender()) revert ApproveToCaller();
              _operatorApprovals[_msgSender()][operator] = approved;
              emit ApprovalForAll(_msgSender(), operator, approved);
          }
          /**
           * @dev See {IERC721-isApprovedForAll}.
           */
          function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
              return _operatorApprovals[owner][operator];
          }
          /**
           * @dev See {IERC721-transferFrom}.
           */
          function transferFrom(
              address from,
              address to,
              uint256 tokenId
          ) public virtual override {
              _transfer(from, to, tokenId);
          }
          /**
           * @dev See {IERC721-safeTransferFrom}.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) public virtual override {
              _transfer(from, to, tokenId);
              if (!_checkOnERC721Received(from, to, tokenId, "")) {
                  revert TransferToNonERC721ReceiverImplementer();
              }
          }
          /**
           * @dev See {IERC721-safeTransferFrom}.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              bytes memory _data
          ) public virtual override {
              _transfer(from, to, tokenId);
              if (!_checkOnERC721Received(from, to, tokenId, _data)) {
                  revert TransferToNonERC721ReceiverImplementer();
              }
          }
          /**
           * @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 (`_mint`),
           */
          function _exists(uint256 tokenId) internal view returns (bool) {
              return tokenId < _currentIndex && !_ownerships[tokenId].burned;
          }
          function _safeMint(address to, uint256 quantity) internal {
              _safeMint(to, 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.
           *
           * Emits a {Transfer} event.
           */
          function _safeMint(
              address to,
              uint256 quantity,
              bytes memory _data
          ) internal {
              _mint(to, quantity, _data, true);
          }
          /**
           * @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.
           */
          function _mint(
              address to,
              uint256 quantity,
              bytes memory _data,
              bool safe
          ) internal {
              uint256 startTokenId = _currentIndex;
              if (to == address(0)) revert MintToZeroAddress();
              if (quantity == 0) revert MintZeroQuantity();
              _beforeTokenTransfers(address(0), to, startTokenId, quantity);
              // Overflows are incredibly unrealistic.
              // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
              // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
              unchecked {
                  _addressData[to].balance += uint64(quantity);
                  _addressData[to].numberMinted += uint64(quantity);
                  _ownerships[startTokenId].addr = to;
                  _ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
                  uint256 updatedIndex = startTokenId;
                  for (uint256 i; i < quantity; i++) {
                      emit Transfer(address(0), to, updatedIndex);
                      if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
                          revert TransferToNonERC721ReceiverImplementer();
                      }
                      updatedIndex++;
                  }
                  _currentIndex = updatedIndex;
              }
              _afterTokenTransfers(address(0), to, startTokenId, quantity);
          }
          /**
           * @dev Transfers `tokenId` from `from` to `to`.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `tokenId` token must be owned by `from`.
           *
           * Emits a {Transfer} event.
           */
          function _transfer(
              address from,
              address to,
              uint256 tokenId
          ) private {
              TokenOwnership memory prevOwnership = ownershipOf(tokenId);
              bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
                  isApprovedForAll(prevOwnership.addr, _msgSender()) ||
                  getApproved(tokenId) == _msgSender());
              if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
              if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
              if (to == address(0)) revert TransferToZeroAddress();
              _beforeTokenTransfers(from, to, tokenId, 1);
              // Clear approvals from the previous owner
              _approve(address(0), tokenId, prevOwnership.addr);
              // 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 {
                  _addressData[from].balance -= 1;
                  _addressData[to].balance += 1;
                  _ownerships[tokenId].addr = to;
                  _ownerships[tokenId].startTimestamp = uint64(block.timestamp);
                  // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
                  // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
                  uint256 nextTokenId = tokenId + 1;
                  if (_ownerships[nextTokenId].addr == address(0)) {
                      // This will suffice for checking _exists(nextTokenId),
                      // as a burned slot cannot contain the zero address.
                      if (nextTokenId < _currentIndex) {
                          _ownerships[nextTokenId].addr = prevOwnership.addr;
                          _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
                      }
                  }
              }
              emit Transfer(from, to, tokenId);
              _afterTokenTransfers(from, to, tokenId, 1);
          }
          /**
           * @dev Destroys `tokenId`.
           * The approval is cleared when the token is burned.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           *
           * Emits a {Transfer} event.
           */
          function _burn(uint256 tokenId) internal virtual {
              TokenOwnership memory prevOwnership = ownershipOf(tokenId);
              _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
              // Clear approvals from the previous owner
              _approve(address(0), tokenId, prevOwnership.addr);
              // 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 {
                  _addressData[prevOwnership.addr].balance -= 1;
                  _addressData[prevOwnership.addr].numberBurned += 1;
                  // Keep track of who burned the token, and the timestamp of burning.
                  _ownerships[tokenId].addr = prevOwnership.addr;
                  _ownerships[tokenId].startTimestamp = uint64(block.timestamp);
                  _ownerships[tokenId].burned = true;
                  // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
                  // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
                  uint256 nextTokenId = tokenId + 1;
                  if (_ownerships[nextTokenId].addr == address(0)) {
                      // This will suffice for checking _exists(nextTokenId),
                      // as a burned slot cannot contain the zero address.
                      if (nextTokenId < _currentIndex) {
                          _ownerships[nextTokenId].addr = prevOwnership.addr;
                          _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
                      }
                  }
              }
              emit Transfer(prevOwnership.addr, address(0), tokenId);
              _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
              // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
              unchecked {
                  _burnCounter++;
              }
          }
          /**
           * @dev Approve `to` to operate on `tokenId`
           *
           * Emits a {Approval} event.
           */
          function _approve(
              address to,
              uint256 tokenId,
              address owner
          ) private {
              _tokenApprovals[tokenId] = to;
              emit Approval(owner, to, tokenId);
          }
          /**
           * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
           * The call is not executed if the target address is not a contract.
           *
           * @param from address representing the previous owner of the given token ID
           * @param to target address that will receive the tokens
           * @param tokenId uint256 ID of the token to be transferred
           * @param _data bytes optional data to send along with the call
           * @return bool whether the call correctly returned the expected magic value
           */
          function _checkOnERC721Received(
              address from,
              address to,
              uint256 tokenId,
              bytes memory _data
          ) private returns (bool) {
              if (to.isContract()) {
                  try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                      return retval == IERC721Receiver(to).onERC721Received.selector;
                  } catch (bytes memory reason) {
                      if (reason.length == 0) {
                          revert TransferToNonERC721ReceiverImplementer();
                      } else {
                          assembly {
                              revert(add(32, reason), mload(reason))
                          }
                      }
                  }
              } else {
                  return true;
              }
          }
          /**
           * @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 {}
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
      pragma solidity ^0.8.0;
      import "../../interfaces/IERC2981.sol";
      import "../../utils/introspection/ERC165.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 ERC2981 is IERC2981, ERC165 {
          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(IERC165, ERC165) returns (bool) {
              return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
          }
          /**
           * @inheritdoc IERC2981
           */
          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];
          }
      }
      // 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 (last updated v4.7.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
                      /// @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.7.0) (token/ERC721/IERC721.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165.sol";
      /**
       * @dev Required interface of an ERC721 compliant contract.
       */
      interface IERC721 is IERC165 {
          /**
           * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
           */
          event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
           */
          event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
           */
          event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
          /**
           * @dev Returns the number of tokens in ``owner``'s account.
           */
          function balanceOf(address owner) external view returns (uint256 balance);
          /**
           * @dev Returns the owner of the `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function ownerOf(uint256 tokenId) external view returns (address owner);
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              bytes calldata data
          ) external;
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
           * are aware of the ERC721 protocol to prevent tokens from being forever locked.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Transfers `tokenId` token from `from` to `to`.
           *
           * WARNING: 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;
          /**
           * @dev Gives permission to `to` to transfer `tokenId` token to another account.
           * The approval is cleared when the token is transferred.
           *
           * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
           *
           * Requirements:
           *
           * - The caller must own the token or be an approved operator.
           * - `tokenId` must exist.
           *
           * Emits an {Approval} event.
           */
          function approve(address to, uint256 tokenId) external;
          /**
           * @dev Approve or remove `operator` as an operator for the caller.
           * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
           *
           * Requirements:
           *
           * - The `operator` cannot be the caller.
           *
           * Emits an {ApprovalForAll} event.
           */
          function setApprovalForAll(address operator, bool _approved) external;
          /**
           * @dev Returns the account approved for `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function getApproved(uint256 tokenId) external view returns (address operator);
          /**
           * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
           *
           * See {setApprovalForAll}
           */
          function isApprovedForAll(address owner, address operator) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
      pragma solidity ^0.8.0;
      /**
       * @title ERC721 token receiver interface
       * @dev Interface for any contract that wants to support safeTransfers
       * from ERC721 asset contracts.
       */
      interface IERC721Receiver {
          /**
           * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
           * by `operator` from `from`, this function is called.
           *
           * It must return its Solidity selector to confirm the token transfer.
           * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
           *
           * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
      pragma solidity ^0.8.0;
      import "../IERC721.sol";
      /**
       * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
       * @dev See https://eips.ethereum.org/EIPS/eip-721
       */
      interface IERC721Metadata is IERC721 {
          /**
           * @dev Returns the token collection name.
           */
          function name() external view returns (string memory);
          /**
           * @dev Returns the token collection symbol.
           */
          function symbol() external view returns (string memory);
          /**
           * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
           */
          function tokenURI(uint256 tokenId) external view returns (string memory);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
      pragma solidity ^0.8.0;
      import "../IERC721.sol";
      /**
       * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
       * @dev See https://eips.ethereum.org/EIPS/eip-721
       */
      interface IERC721Enumerable is IERC721 {
          /**
           * @dev Returns the total amount of tokens stored by the contract.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
           * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
           */
          function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
          /**
           * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
           * Use along with {totalSupply} to enumerate all tokens.
           */
          function tokenByIndex(uint256 index) external view returns (uint256);
      }
      // 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: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
      pragma solidity ^0.8.0;
      import "../utils/introspection/IERC165.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 IERC2981 is IERC165 {
          /**
           * @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 v4.4.1 (access/IAccessControl.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev External interface of AccessControl declared to support ERC165 detection.
       */
      interface IAccessControl {
          /**
           * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
           *
           * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
           * {RoleAdminChanged} not being emitted signaling this.
           *
           * _Available since v3.1._
           */
          event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
          /**
           * @dev Emitted when `account` is granted `role`.
           *
           * `sender` is the account that originated the contract call, an admin role
           * bearer except when using {AccessControl-_setupRole}.
           */
          event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
          /**
           * @dev Emitted when `account` is revoked `role`.
           *
           * `sender` is the account that originated the contract call:
           *   - if using `revokeRole`, it is the admin role bearer
           *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
           */
          event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
          /**
           * @dev Returns `true` if `account` has been granted `role`.
           */
          function hasRole(bytes32 role, address account) external view returns (bool);
          /**
           * @dev Returns the admin role that controls `role`. See {grantRole} and
           * {revokeRole}.
           *
           * To change a role's admin, use {AccessControl-_setRoleAdmin}.
           */
          function getRoleAdmin(bytes32 role) external view returns (bytes32);
          /**
           * @dev Grants `role` to `account`.
           *
           * If `account` had not been already granted `role`, emits a {RoleGranted}
           * event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           */
          function grantRole(bytes32 role, address account) external;
          /**
           * @dev Revokes `role` from `account`.
           *
           * If `account` had been granted `role`, emits a {RoleRevoked} event.
           *
           * Requirements:
           *
           * - the caller must have ``role``'s admin role.
           */
          function revokeRole(bytes32 role, address account) external;
          /**
           * @dev Revokes `role` from the calling account.
           *
           * Roles are often managed via {grantRole} and {revokeRole}: this function's
           * purpose is to provide a mechanism for accounts to lose their privileges
           * if they are compromised (such as when a trusted device is misplaced).
           *
           * If the calling account had been granted `role`, emits a {RoleRevoked}
           * event.
           *
           * Requirements:
           *
           * - the caller must be `account`.
           */
          function renounceRole(bytes32 role, address account) external;
      }
      

      File 4 of 4: Conduit
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      import { ConduitInterface } from "../interfaces/ConduitInterface.sol";
      import { ConduitItemType } from "./lib/ConduitEnums.sol";
      import { TokenTransferrer } from "../lib/TokenTransferrer.sol";
      // prettier-ignore
      import {
          ConduitTransfer,
          ConduitBatch1155Transfer
      } from "./lib/ConduitStructs.sol";
      import "./lib/ConduitConstants.sol";
      /**
       * @title Conduit
       * @author 0age
       * @notice This contract serves as an originator for "proxied" transfers. Each
       *         conduit is deployed and controlled by a "conduit controller" that can
       *         add and remove "channels" or contracts that can instruct the conduit
       *         to transfer approved ERC20/721/1155 tokens. *IMPORTANT NOTE: each
       *         conduit has an owner that can arbitrarily add or remove channels, and
       *         a malicious or negligent owner can add a channel that allows for any
       *         approved ERC20/721/1155 tokens to be taken immediately — be extremely
       *         cautious with what conduits you give token approvals to!*
       */
      contract Conduit is ConduitInterface, TokenTransferrer {
          // Set deployer as an immutable controller that can update channel statuses.
          address private immutable _controller;
          // Track the status of each channel.
          mapping(address => bool) private _channels;
          /**
           * @notice Ensure that the caller is currently registered as an open channel
           *         on the conduit.
           */
          modifier onlyOpenChannel() {
              // Utilize assembly to access channel storage mapping directly.
              assembly {
                  // Write the caller to scratch space.
                  mstore(ChannelKey_channel_ptr, caller())
                  // Write the storage slot for _channels to scratch space.
                  mstore(ChannelKey_slot_ptr, _channels.slot)
                  // Derive the position in storage of _channels[msg.sender]
                  // and check if the stored value is zero.
                  if iszero(
                      sload(keccak256(ChannelKey_channel_ptr, ChannelKey_length))
                  ) {
                      // The caller is not an open channel; revert with
                      // ChannelClosed(caller). First, set error signature in memory.
                      mstore(ChannelClosed_error_ptr, ChannelClosed_error_signature)
                      // Next, set the caller as the argument.
                      mstore(ChannelClosed_channel_ptr, caller())
                      // Finally, revert, returning full custom error with argument.
                      revert(ChannelClosed_error_ptr, ChannelClosed_error_length)
                  }
              }
              // Continue with function execution.
              _;
          }
          /**
           * @notice In the constructor, set the deployer as the controller.
           */
          constructor() {
              // Set the deployer as the controller.
              _controller = msg.sender;
          }
          /**
           * @notice Execute a sequence of ERC20/721/1155 transfers. Only a caller
           *         with an open channel can call this function. Note that channels
           *         are expected to implement reentrancy protection if desired, and
           *         that cross-channel reentrancy may be possible if the conduit has
           *         multiple open channels at once. Also note that channels are
           *         expected to implement checks against transferring any zero-amount
           *         items if that constraint is desired.
           *
           * @param transfers The ERC20/721/1155 transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function execute(ConduitTransfer[] calldata transfers)
              external
              override
              onlyOpenChannel
              returns (bytes4 magicValue)
          {
              // Retrieve the total number of transfers and place on the stack.
              uint256 totalStandardTransfers = transfers.length;
              // Iterate over each transfer.
              for (uint256 i = 0; i < totalStandardTransfers; ) {
                  // Retrieve the transfer in question and perform the transfer.
                  _transfer(transfers[i]);
                  // Skip overflow check as for loop is indexed starting at zero.
                  unchecked {
                      ++i;
                  }
              }
              // Return a magic value indicating that the transfers were performed.
              magicValue = this.execute.selector;
          }
          /**
           * @notice Execute a sequence of batch 1155 item transfers. Only a caller
           *         with an open channel can call this function. Note that channels
           *         are expected to implement reentrancy protection if desired, and
           *         that cross-channel reentrancy may be possible if the conduit has
           *         multiple open channels at once. Also note that channels are
           *         expected to implement checks against transferring any zero-amount
           *         items if that constraint is desired.
           *
           * @param batchTransfers The 1155 batch item transfers to perform.
           *
           * @return magicValue A magic value indicating that the item transfers were
           *                    performed successfully.
           */
          function executeBatch1155(
              ConduitBatch1155Transfer[] calldata batchTransfers
          ) external override onlyOpenChannel returns (bytes4 magicValue) {
              // Perform 1155 batch transfers. Note that memory should be considered
              // entirely corrupted from this point forward.
              _performERC1155BatchTransfers(batchTransfers);
              // Return a magic value indicating that the transfers were performed.
              magicValue = this.executeBatch1155.selector;
          }
          /**
           * @notice Execute a sequence of transfers, both single ERC20/721/1155 item
           *         transfers as well as batch 1155 item transfers. Only a caller
           *         with an open channel can call this function. Note that channels
           *         are expected to implement reentrancy protection if desired, and
           *         that cross-channel reentrancy may be possible if the conduit has
           *         multiple open channels at once. Also note that channels are
           *         expected to implement checks against transferring any zero-amount
           *         items if that constraint is desired.
           *
           * @param standardTransfers The ERC20/721/1155 item transfers to perform.
           * @param batchTransfers    The 1155 batch item transfers to perform.
           *
           * @return magicValue A magic value indicating that the item transfers were
           *                    performed successfully.
           */
          function executeWithBatch1155(
              ConduitTransfer[] calldata standardTransfers,
              ConduitBatch1155Transfer[] calldata batchTransfers
          ) external override onlyOpenChannel returns (bytes4 magicValue) {
              // Retrieve the total number of transfers and place on the stack.
              uint256 totalStandardTransfers = standardTransfers.length;
              // Iterate over each standard transfer.
              for (uint256 i = 0; i < totalStandardTransfers; ) {
                  // Retrieve the transfer in question and perform the transfer.
                  _transfer(standardTransfers[i]);
                  // Skip overflow check as for loop is indexed starting at zero.
                  unchecked {
                      ++i;
                  }
              }
              // Perform 1155 batch transfers. Note that memory should be considered
              // entirely corrupted from this point forward aside from the free memory
              // pointer having the default value.
              _performERC1155BatchTransfers(batchTransfers);
              // Return a magic value indicating that the transfers were performed.
              magicValue = this.executeWithBatch1155.selector;
          }
          /**
           * @notice Open or close a given channel. Only callable by the controller.
           *
           * @param channel The channel to open or close.
           * @param isOpen  The status of the channel (either open or closed).
           */
          function updateChannel(address channel, bool isOpen) external override {
              // Ensure that the caller is the controller of this contract.
              if (msg.sender != _controller) {
                  revert InvalidController();
              }
              // Ensure that the channel does not already have the indicated status.
              if (_channels[channel] == isOpen) {
                  revert ChannelStatusAlreadySet(channel, isOpen);
              }
              // Update the status of the channel.
              _channels[channel] = isOpen;
              // Emit a corresponding event.
              emit ChannelUpdated(channel, isOpen);
          }
          /**
           * @dev Internal function to transfer a given ERC20/721/1155 item. Note that
           *      channels are expected to implement checks against transferring any
           *      zero-amount items if that constraint is desired.
           *
           * @param item The ERC20/721/1155 item to transfer.
           */
          function _transfer(ConduitTransfer calldata item) internal {
              // Determine the transfer method based on the respective item type.
              if (item.itemType == ConduitItemType.ERC20) {
                  // Transfer ERC20 token. Note that item.identifier is ignored and
                  // therefore ERC20 transfer items are potentially malleable — this
                  // check should be performed by the calling channel if a constraint
                  // on item malleability is desired.
                  _performERC20Transfer(item.token, item.from, item.to, item.amount);
              } else if (item.itemType == ConduitItemType.ERC721) {
                  // Ensure that exactly one 721 item is being transferred.
                  if (item.amount != 1) {
                      revert InvalidERC721TransferAmount();
                  }
                  // Transfer ERC721 token.
                  _performERC721Transfer(
                      item.token,
                      item.from,
                      item.to,
                      item.identifier
                  );
              } else if (item.itemType == ConduitItemType.ERC1155) {
                  // Transfer ERC1155 token.
                  _performERC1155Transfer(
                      item.token,
                      item.from,
                      item.to,
                      item.identifier,
                      item.amount
                  );
              } else {
                  // Throw with an error.
                  revert InvalidItemType();
              }
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      // prettier-ignore
      import {
          ConduitTransfer,
          ConduitBatch1155Transfer
      } from "../conduit/lib/ConduitStructs.sol";
      /**
       * @title ConduitInterface
       * @author 0age
       * @notice ConduitInterface contains all external function interfaces, events,
       *         and errors for conduit contracts.
       */
      interface ConduitInterface {
          /**
           * @dev Revert with an error when attempting to execute transfers using a
           *      caller that does not have an open channel.
           */
          error ChannelClosed(address channel);
          /**
           * @dev Revert with an error when attempting to update a channel to the
           *      current status of that channel.
           */
          error ChannelStatusAlreadySet(address channel, bool isOpen);
          /**
           * @dev Revert with an error when attempting to execute a transfer for an
           *      item that does not have an ERC20/721/1155 item type.
           */
          error InvalidItemType();
          /**
           * @dev Revert with an error when attempting to update the status of a
           *      channel from a caller that is not the conduit controller.
           */
          error InvalidController();
          /**
           * @dev Emit an event whenever a channel is opened or closed.
           *
           * @param channel The channel that has been updated.
           * @param open    A boolean indicating whether the conduit is open or not.
           */
          event ChannelUpdated(address indexed channel, bool open);
          /**
           * @notice Execute a sequence of ERC20/721/1155 transfers. Only a caller
           *         with an open channel can call this function.
           *
           * @param transfers The ERC20/721/1155 transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function execute(ConduitTransfer[] calldata transfers)
              external
              returns (bytes4 magicValue);
          /**
           * @notice Execute a sequence of batch 1155 transfers. Only a caller with an
           *         open channel can call this function.
           *
           * @param batch1155Transfers The 1155 batch transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function executeBatch1155(
              ConduitBatch1155Transfer[] calldata batch1155Transfers
          ) external returns (bytes4 magicValue);
          /**
           * @notice Execute a sequence of transfers, both single and batch 1155. Only
           *         a caller with an open channel can call this function.
           *
           * @param standardTransfers  The ERC20/721/1155 transfers to perform.
           * @param batch1155Transfers The 1155 batch transfers to perform.
           *
           * @return magicValue A magic value indicating that the transfers were
           *                    performed successfully.
           */
          function executeWithBatch1155(
              ConduitTransfer[] calldata standardTransfers,
              ConduitBatch1155Transfer[] calldata batch1155Transfers
          ) external returns (bytes4 magicValue);
          /**
           * @notice Open or close a given channel. Only callable by the controller.
           *
           * @param channel The channel to open or close.
           * @param isOpen  The status of the channel (either open or closed).
           */
          function updateChannel(address channel, bool isOpen) external;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      enum ConduitItemType {
          NATIVE, // unused
          ERC20,
          ERC721,
          ERC1155
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      import "./TokenTransferrerConstants.sol";
      // prettier-ignore
      import {
          TokenTransferrerErrors
      } from "../interfaces/TokenTransferrerErrors.sol";
      import { ConduitBatch1155Transfer } from "../conduit/lib/ConduitStructs.sol";
      /**
       * @title TokenTransferrer
       * @author 0age
       * @custom:coauthor d1ll0n
       * @custom:coauthor transmissions11
       * @notice TokenTransferrer is a library for performing optimized ERC20, ERC721,
       *         ERC1155, and batch ERC1155 transfers, used by both Seaport as well as
       *         by conduits deployed by the ConduitController. Use great caution when
       *         considering these functions for use in other codebases, as there are
       *         significant side effects and edge cases that need to be thoroughly
       *         understood and carefully addressed.
       */
      contract TokenTransferrer is TokenTransferrerErrors {
          /**
           * @dev Internal function to transfer ERC20 tokens from a given originator
           *      to a given recipient. Sufficient approvals must be set on the
           *      contract performing the transfer.
           *
           * @param token      The ERC20 token to transfer.
           * @param from       The originator of the transfer.
           * @param to         The recipient of the transfer.
           * @param amount     The amount to transfer.
           */
          function _performERC20Transfer(
              address token,
              address from,
              address to,
              uint256 amount
          ) internal {
              // Utilize assembly to perform an optimized ERC20 token transfer.
              assembly {
                  // The free memory pointer memory slot will be used when populating
                  // call data for the transfer; read the value and restore it later.
                  let memPointer := mload(FreeMemoryPointerSlot)
                  // Write call data into memory, starting with function selector.
                  mstore(ERC20_transferFrom_sig_ptr, ERC20_transferFrom_signature)
                  mstore(ERC20_transferFrom_from_ptr, from)
                  mstore(ERC20_transferFrom_to_ptr, to)
                  mstore(ERC20_transferFrom_amount_ptr, amount)
                  // Make call & copy up to 32 bytes of return data to scratch space.
                  // Scratch space does not need to be cleared ahead of time, as the
                  // subsequent check will ensure that either at least a full word of
                  // return data is received (in which case it will be overwritten) or
                  // that no data is received (in which case scratch space will be
                  // ignored) on a successful call to the given token.
                  let callStatus := call(
                      gas(),
                      token,
                      0,
                      ERC20_transferFrom_sig_ptr,
                      ERC20_transferFrom_length,
                      0,
                      OneWord
                  )
                  // Determine whether transfer was successful using status & result.
                  let success := and(
                      // Set success to whether the call reverted, if not check it
                      // either returned exactly 1 (can't just be non-zero data), or
                      // had no return data.
                      or(
                          and(eq(mload(0), 1), gt(returndatasize(), 31)),
                          iszero(returndatasize())
                      ),
                      callStatus
                  )
                  // Handle cases where either the transfer failed or no data was
                  // returned. Group these, as most transfers will succeed with data.
                  // Equivalent to `or(iszero(success), iszero(returndatasize()))`
                  // but after it's inverted for JUMPI this expression is cheaper.
                  if iszero(and(success, iszero(iszero(returndatasize())))) {
                      // If the token has no code or the transfer failed: Equivalent
                      // to `or(iszero(success), iszero(extcodesize(token)))` but
                      // after it's inverted for JUMPI this expression is cheaper.
                      if iszero(and(iszero(iszero(extcodesize(token))), success)) {
                          // If the transfer failed:
                          if iszero(success) {
                              // If it was due to a revert:
                              if iszero(callStatus) {
                                  // If it returned a message, bubble it up as long as
                                  // sufficient gas remains to do so:
                                  if returndatasize() {
                                      // Ensure that sufficient gas is available to
                                      // copy returndata while expanding memory where
                                      // necessary. Start by computing the word size
                                      // of returndata and allocated memory. Round up
                                      // to the nearest full word.
                                      let returnDataWords := div(
                                          add(returndatasize(), AlmostOneWord),
                                          OneWord
                                      )
                                      // Note: use the free memory pointer in place of
                                      // msize() to work around a Yul warning that
                                      // prevents accessing msize directly when the IR
                                      // pipeline is activated.
                                      let msizeWords := div(memPointer, OneWord)
                                      // Next, compute the cost of the returndatacopy.
                                      let cost := mul(CostPerWord, returnDataWords)
                                      // Then, compute cost of new memory allocation.
                                      if gt(returnDataWords, msizeWords) {
                                          cost := add(
                                              cost,
                                              add(
                                                  mul(
                                                      sub(
                                                          returnDataWords,
                                                          msizeWords
                                                      ),
                                                      CostPerWord
                                                  ),
                                                  div(
                                                      sub(
                                                          mul(
                                                              returnDataWords,
                                                              returnDataWords
                                                          ),
                                                          mul(msizeWords, msizeWords)
                                                      ),
                                                      MemoryExpansionCoefficient
                                                  )
                                              )
                                          )
                                      }
                                      // Finally, add a small constant and compare to
                                      // gas remaining; bubble up the revert data if
                                      // enough gas is still available.
                                      if lt(add(cost, ExtraGasBuffer), gas()) {
                                          // Copy returndata to memory; overwrite
                                          // existing memory.
                                          returndatacopy(0, 0, returndatasize())
                                          // Revert, specifying memory region with
                                          // copied returndata.
                                          revert(0, returndatasize())
                                      }
                                  }
                                  // Otherwise revert with a generic error message.
                                  mstore(
                                      TokenTransferGenericFailure_error_sig_ptr,
                                      TokenTransferGenericFailure_error_signature
                                  )
                                  mstore(
                                      TokenTransferGenericFailure_error_token_ptr,
                                      token
                                  )
                                  mstore(
                                      TokenTransferGenericFailure_error_from_ptr,
                                      from
                                  )
                                  mstore(TokenTransferGenericFailure_error_to_ptr, to)
                                  mstore(TokenTransferGenericFailure_error_id_ptr, 0)
                                  mstore(
                                      TokenTransferGenericFailure_error_amount_ptr,
                                      amount
                                  )
                                  revert(
                                      TokenTransferGenericFailure_error_sig_ptr,
                                      TokenTransferGenericFailure_error_length
                                  )
                              }
                              // Otherwise revert with a message about the token
                              // returning false or non-compliant return values.
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_sig_ptr,
                                  BadReturnValueFromERC20OnTransfer_error_signature
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_token_ptr,
                                  token
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_from_ptr,
                                  from
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_to_ptr,
                                  to
                              )
                              mstore(
                                  BadReturnValueFromERC20OnTransfer_error_amount_ptr,
                                  amount
                              )
                              revert(
                                  BadReturnValueFromERC20OnTransfer_error_sig_ptr,
                                  BadReturnValueFromERC20OnTransfer_error_length
                              )
                          }
                          // Otherwise, revert with error about token not having code:
                          mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                          mstore(NoContract_error_token_ptr, token)
                          revert(NoContract_error_sig_ptr, NoContract_error_length)
                      }
                      // Otherwise, the token just returned no data despite the call
                      // having succeeded; no need to optimize for this as it's not
                      // technically ERC20 compliant.
                  }
                  // Restore the original free memory pointer.
                  mstore(FreeMemoryPointerSlot, memPointer)
                  // Restore the zero slot to zero.
                  mstore(ZeroSlot, 0)
              }
          }
          /**
           * @dev Internal function to transfer an ERC721 token from a given
           *      originator to a given recipient. Sufficient approvals must be set on
           *      the contract performing the transfer. Note that this function does
           *      not check whether the receiver can accept the ERC721 token (i.e. it
           *      does not use `safeTransferFrom`).
           *
           * @param token      The ERC721 token to transfer.
           * @param from       The originator of the transfer.
           * @param to         The recipient of the transfer.
           * @param identifier The tokenId to transfer.
           */
          function _performERC721Transfer(
              address token,
              address from,
              address to,
              uint256 identifier
          ) internal {
              // Utilize assembly to perform an optimized ERC721 token transfer.
              assembly {
                  // If the token has no code, revert.
                  if iszero(extcodesize(token)) {
                      mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                      mstore(NoContract_error_token_ptr, token)
                      revert(NoContract_error_sig_ptr, NoContract_error_length)
                  }
                  // The free memory pointer memory slot will be used when populating
                  // call data for the transfer; read the value and restore it later.
                  let memPointer := mload(FreeMemoryPointerSlot)
                  // Write call data to memory starting with function selector.
                  mstore(ERC721_transferFrom_sig_ptr, ERC721_transferFrom_signature)
                  mstore(ERC721_transferFrom_from_ptr, from)
                  mstore(ERC721_transferFrom_to_ptr, to)
                  mstore(ERC721_transferFrom_id_ptr, identifier)
                  // Perform the call, ignoring return data.
                  let success := call(
                      gas(),
                      token,
                      0,
                      ERC721_transferFrom_sig_ptr,
                      ERC721_transferFrom_length,
                      0,
                      0
                  )
                  // If the transfer reverted:
                  if iszero(success) {
                      // If it returned a message, bubble it up as long as sufficient
                      // gas remains to do so:
                      if returndatasize() {
                          // Ensure that sufficient gas is available to copy
                          // returndata while expanding memory where necessary. Start
                          // by computing word size of returndata & allocated memory.
                          // Round up to the nearest full word.
                          let returnDataWords := div(
                              add(returndatasize(), AlmostOneWord),
                              OneWord
                          )
                          // Note: use the free memory pointer in place of msize() to
                          // work around a Yul warning that prevents accessing msize
                          // directly when the IR pipeline is activated.
                          let msizeWords := div(memPointer, OneWord)
                          // Next, compute the cost of the returndatacopy.
                          let cost := mul(CostPerWord, returnDataWords)
                          // Then, compute cost of new memory allocation.
                          if gt(returnDataWords, msizeWords) {
                              cost := add(
                                  cost,
                                  add(
                                      mul(
                                          sub(returnDataWords, msizeWords),
                                          CostPerWord
                                      ),
                                      div(
                                          sub(
                                              mul(returnDataWords, returnDataWords),
                                              mul(msizeWords, msizeWords)
                                          ),
                                          MemoryExpansionCoefficient
                                      )
                                  )
                              )
                          }
                          // Finally, add a small constant and compare to gas
                          // remaining; bubble up the revert data if enough gas is
                          // still available.
                          if lt(add(cost, ExtraGasBuffer), gas()) {
                              // Copy returndata to memory; overwrite existing memory.
                              returndatacopy(0, 0, returndatasize())
                              // Revert, giving memory region with copied returndata.
                              revert(0, returndatasize())
                          }
                      }
                      // Otherwise revert with a generic error message.
                      mstore(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_signature
                      )
                      mstore(TokenTransferGenericFailure_error_token_ptr, token)
                      mstore(TokenTransferGenericFailure_error_from_ptr, from)
                      mstore(TokenTransferGenericFailure_error_to_ptr, to)
                      mstore(TokenTransferGenericFailure_error_id_ptr, identifier)
                      mstore(TokenTransferGenericFailure_error_amount_ptr, 1)
                      revert(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_length
                      )
                  }
                  // Restore the original free memory pointer.
                  mstore(FreeMemoryPointerSlot, memPointer)
                  // Restore the zero slot to zero.
                  mstore(ZeroSlot, 0)
              }
          }
          /**
           * @dev Internal function to transfer ERC1155 tokens from a given
           *      originator to a given recipient. Sufficient approvals must be set on
           *      the contract performing the transfer and contract recipients must
           *      implement the ERC1155TokenReceiver interface to indicate that they
           *      are willing to accept the transfer.
           *
           * @param token      The ERC1155 token to transfer.
           * @param from       The originator of the transfer.
           * @param to         The recipient of the transfer.
           * @param identifier The id to transfer.
           * @param amount     The amount to transfer.
           */
          function _performERC1155Transfer(
              address token,
              address from,
              address to,
              uint256 identifier,
              uint256 amount
          ) internal {
              // Utilize assembly to perform an optimized ERC1155 token transfer.
              assembly {
                  // If the token has no code, revert.
                  if iszero(extcodesize(token)) {
                      mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                      mstore(NoContract_error_token_ptr, token)
                      revert(NoContract_error_sig_ptr, NoContract_error_length)
                  }
                  // The following memory slots will be used when populating call data
                  // for the transfer; read the values and restore them later.
                  let memPointer := mload(FreeMemoryPointerSlot)
                  let slot0x80 := mload(Slot0x80)
                  let slot0xA0 := mload(Slot0xA0)
                  let slot0xC0 := mload(Slot0xC0)
                  // Write call data into memory, beginning with function selector.
                  mstore(
                      ERC1155_safeTransferFrom_sig_ptr,
                      ERC1155_safeTransferFrom_signature
                  )
                  mstore(ERC1155_safeTransferFrom_from_ptr, from)
                  mstore(ERC1155_safeTransferFrom_to_ptr, to)
                  mstore(ERC1155_safeTransferFrom_id_ptr, identifier)
                  mstore(ERC1155_safeTransferFrom_amount_ptr, amount)
                  mstore(
                      ERC1155_safeTransferFrom_data_offset_ptr,
                      ERC1155_safeTransferFrom_data_length_offset
                  )
                  mstore(ERC1155_safeTransferFrom_data_length_ptr, 0)
                  // Perform the call, ignoring return data.
                  let success := call(
                      gas(),
                      token,
                      0,
                      ERC1155_safeTransferFrom_sig_ptr,
                      ERC1155_safeTransferFrom_length,
                      0,
                      0
                  )
                  // If the transfer reverted:
                  if iszero(success) {
                      // If it returned a message, bubble it up as long as sufficient
                      // gas remains to do so:
                      if returndatasize() {
                          // Ensure that sufficient gas is available to copy
                          // returndata while expanding memory where necessary. Start
                          // by computing word size of returndata & allocated memory.
                          // Round up to the nearest full word.
                          let returnDataWords := div(
                              add(returndatasize(), AlmostOneWord),
                              OneWord
                          )
                          // Note: use the free memory pointer in place of msize() to
                          // work around a Yul warning that prevents accessing msize
                          // directly when the IR pipeline is activated.
                          let msizeWords := div(memPointer, OneWord)
                          // Next, compute the cost of the returndatacopy.
                          let cost := mul(CostPerWord, returnDataWords)
                          // Then, compute cost of new memory allocation.
                          if gt(returnDataWords, msizeWords) {
                              cost := add(
                                  cost,
                                  add(
                                      mul(
                                          sub(returnDataWords, msizeWords),
                                          CostPerWord
                                      ),
                                      div(
                                          sub(
                                              mul(returnDataWords, returnDataWords),
                                              mul(msizeWords, msizeWords)
                                          ),
                                          MemoryExpansionCoefficient
                                      )
                                  )
                              )
                          }
                          // Finally, add a small constant and compare to gas
                          // remaining; bubble up the revert data if enough gas is
                          // still available.
                          if lt(add(cost, ExtraGasBuffer), gas()) {
                              // Copy returndata to memory; overwrite existing memory.
                              returndatacopy(0, 0, returndatasize())
                              // Revert, giving memory region with copied returndata.
                              revert(0, returndatasize())
                          }
                      }
                      // Otherwise revert with a generic error message.
                      mstore(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_signature
                      )
                      mstore(TokenTransferGenericFailure_error_token_ptr, token)
                      mstore(TokenTransferGenericFailure_error_from_ptr, from)
                      mstore(TokenTransferGenericFailure_error_to_ptr, to)
                      mstore(TokenTransferGenericFailure_error_id_ptr, identifier)
                      mstore(TokenTransferGenericFailure_error_amount_ptr, amount)
                      revert(
                          TokenTransferGenericFailure_error_sig_ptr,
                          TokenTransferGenericFailure_error_length
                      )
                  }
                  mstore(Slot0x80, slot0x80) // Restore slot 0x80.
                  mstore(Slot0xA0, slot0xA0) // Restore slot 0xA0.
                  mstore(Slot0xC0, slot0xC0) // Restore slot 0xC0.
                  // Restore the original free memory pointer.
                  mstore(FreeMemoryPointerSlot, memPointer)
                  // Restore the zero slot to zero.
                  mstore(ZeroSlot, 0)
              }
          }
          /**
           * @dev Internal function to transfer ERC1155 tokens from a given
           *      originator to a given recipient. Sufficient approvals must be set on
           *      the contract performing the transfer and contract recipients must
           *      implement the ERC1155TokenReceiver interface to indicate that they
           *      are willing to accept the transfer. NOTE: this function is not
           *      memory-safe; it will overwrite existing memory, restore the free
           *      memory pointer to the default value, and overwrite the zero slot.
           *      This function should only be called once memory is no longer
           *      required and when uninitialized arrays are not utilized, and memory
           *      should be considered fully corrupted (aside from the existence of a
           *      default-value free memory pointer) after calling this function.
           *
           * @param batchTransfers The group of 1155 batch transfers to perform.
           */
          function _performERC1155BatchTransfers(
              ConduitBatch1155Transfer[] calldata batchTransfers
          ) internal {
              // Utilize assembly to perform optimized batch 1155 transfers.
              assembly {
                  let len := batchTransfers.length
                  // Pointer to first head in the array, which is offset to the struct
                  // at each index. This gets incremented after each loop to avoid
                  // multiplying by 32 to get the offset for each element.
                  let nextElementHeadPtr := batchTransfers.offset
                  // Pointer to beginning of the head of the array. This is the
                  // reference position each offset references. It's held static to
                  // let each loop calculate the data position for an element.
                  let arrayHeadPtr := nextElementHeadPtr
                  // Write the function selector, which will be reused for each call:
                  // safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)
                  mstore(
                      ConduitBatch1155Transfer_from_offset,
                      ERC1155_safeBatchTransferFrom_signature
                  )
                  // Iterate over each batch transfer.
                  for {
                      let i := 0
                  } lt(i, len) {
                      i := add(i, 1)
                  } {
                      // Read the offset to the beginning of the element and add
                      // it to pointer to the beginning of the array head to get
                      // the absolute position of the element in calldata.
                      let elementPtr := add(
                          arrayHeadPtr,
                          calldataload(nextElementHeadPtr)
                      )
                      // Retrieve the token from calldata.
                      let token := calldataload(elementPtr)
                      // If the token has no code, revert.
                      if iszero(extcodesize(token)) {
                          mstore(NoContract_error_sig_ptr, NoContract_error_signature)
                          mstore(NoContract_error_token_ptr, token)
                          revert(NoContract_error_sig_ptr, NoContract_error_length)
                      }
                      // Get the total number of supplied ids.
                      let idsLength := calldataload(
                          add(elementPtr, ConduitBatch1155Transfer_ids_length_offset)
                      )
                      // Determine the expected offset for the amounts array.
                      let expectedAmountsOffset := add(
                          ConduitBatch1155Transfer_amounts_length_baseOffset,
                          mul(idsLength, OneWord)
                      )
                      // Validate struct encoding.
                      let invalidEncoding := iszero(
                          and(
                              // ids.length == amounts.length
                              eq(
                                  idsLength,
                                  calldataload(add(elementPtr, expectedAmountsOffset))
                              ),
                              and(
                                  // ids_offset == 0xa0
                                  eq(
                                      calldataload(
                                          add(
                                              elementPtr,
                                              ConduitBatch1155Transfer_ids_head_offset
                                          )
                                      ),
                                      ConduitBatch1155Transfer_ids_length_offset
                                  ),
                                  // amounts_offset == 0xc0 + ids.length*32
                                  eq(
                                      calldataload(
                                          add(
                                              elementPtr,
                                              ConduitBatchTransfer_amounts_head_offset
                                          )
                                      ),
                                      expectedAmountsOffset
                                  )
                              )
                          )
                      )
                      // Revert with an error if the encoding is not valid.
                      if invalidEncoding {
                          mstore(
                              Invalid1155BatchTransferEncoding_ptr,
                              Invalid1155BatchTransferEncoding_selector
                          )
                          revert(
                              Invalid1155BatchTransferEncoding_ptr,
                              Invalid1155BatchTransferEncoding_length
                          )
                      }
                      // Update the offset position for the next loop
                      nextElementHeadPtr := add(nextElementHeadPtr, OneWord)
                      // Copy the first section of calldata (before dynamic values).
                      calldatacopy(
                          BatchTransfer1155Params_ptr,
                          add(elementPtr, ConduitBatch1155Transfer_from_offset),
                          ConduitBatch1155Transfer_usable_head_size
                      )
                      // Determine size of calldata required for ids and amounts. Note
                      // that the size includes both lengths as well as the data.
                      let idsAndAmountsSize := add(TwoWords, mul(idsLength, TwoWords))
                      // Update the offset for the data array in memory.
                      mstore(
                          BatchTransfer1155Params_data_head_ptr,
                          add(
                              BatchTransfer1155Params_ids_length_offset,
                              idsAndAmountsSize
                          )
                      )
                      // Set the length of the data array in memory to zero.
                      mstore(
                          add(
                              BatchTransfer1155Params_data_length_basePtr,
                              idsAndAmountsSize
                          ),
                          0
                      )
                      // Determine the total calldata size for the call to transfer.
                      let transferDataSize := add(
                          BatchTransfer1155Params_calldata_baseSize,
                          idsAndAmountsSize
                      )
                      // Copy second section of calldata (including dynamic values).
                      calldatacopy(
                          BatchTransfer1155Params_ids_length_ptr,
                          add(elementPtr, ConduitBatch1155Transfer_ids_length_offset),
                          idsAndAmountsSize
                      )
                      // Perform the call to transfer 1155 tokens.
                      let success := call(
                          gas(),
                          token,
                          0,
                          ConduitBatch1155Transfer_from_offset, // Data portion start.
                          transferDataSize, // Location of the length of callData.
                          0,
                          0
                      )
                      // If the transfer reverted:
                      if iszero(success) {
                          // If it returned a message, bubble it up as long as
                          // sufficient gas remains to do so:
                          if returndatasize() {
                              // Ensure that sufficient gas is available to copy
                              // returndata while expanding memory where necessary.
                              // Start by computing word size of returndata and
                              // allocated memory. Round up to the nearest full word.
                              let returnDataWords := div(
                                  add(returndatasize(), AlmostOneWord),
                                  OneWord
                              )
                              // Note: use transferDataSize in place of msize() to
                              // work around a Yul warning that prevents accessing
                              // msize directly when the IR pipeline is activated.
                              // The free memory pointer is not used here because
                              // this function does almost all memory management
                              // manually and does not update it, and transferDataSize
                              // should be the largest memory value used (unless a
                              // previous batch was larger).
                              let msizeWords := div(transferDataSize, OneWord)
                              // Next, compute the cost of the returndatacopy.
                              let cost := mul(CostPerWord, returnDataWords)
                              // Then, compute cost of new memory allocation.
                              if gt(returnDataWords, msizeWords) {
                                  cost := add(
                                      cost,
                                      add(
                                          mul(
                                              sub(returnDataWords, msizeWords),
                                              CostPerWord
                                          ),
                                          div(
                                              sub(
                                                  mul(
                                                      returnDataWords,
                                                      returnDataWords
                                                  ),
                                                  mul(msizeWords, msizeWords)
                                              ),
                                              MemoryExpansionCoefficient
                                          )
                                      )
                                  )
                              }
                              // Finally, add a small constant and compare to gas
                              // remaining; bubble up the revert data if enough gas is
                              // still available.
                              if lt(add(cost, ExtraGasBuffer), gas()) {
                                  // Copy returndata to memory; overwrite existing.
                                  returndatacopy(0, 0, returndatasize())
                                  // Revert with memory region containing returndata.
                                  revert(0, returndatasize())
                              }
                          }
                          // Set the error signature.
                          mstore(
                              0,
                              ERC1155BatchTransferGenericFailure_error_signature
                          )
                          // Write the token.
                          mstore(ERC1155BatchTransferGenericFailure_token_ptr, token)
                          // Increase the offset to ids by 32.
                          mstore(
                              BatchTransfer1155Params_ids_head_ptr,
                              ERC1155BatchTransferGenericFailure_ids_offset
                          )
                          // Increase the offset to amounts by 32.
                          mstore(
                              BatchTransfer1155Params_amounts_head_ptr,
                              add(
                                  OneWord,
                                  mload(BatchTransfer1155Params_amounts_head_ptr)
                              )
                          )
                          // Return modified region. The total size stays the same as
                          // `token` uses the same number of bytes as `data.length`.
                          revert(0, transferDataSize)
                      }
                  }
                  // Reset the free memory pointer to the default value; memory must
                  // be assumed to be dirtied and not reused from this point forward.
                  // Also note that the zero slot is not reset to zero, meaning empty
                  // arrays cannot be safely created or utilized until it is restored.
                  mstore(FreeMemoryPointerSlot, DefaultFreeMemoryPointer)
              }
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      import { ConduitItemType } from "./ConduitEnums.sol";
      struct ConduitTransfer {
          ConduitItemType itemType;
          address token;
          address from;
          address to;
          uint256 identifier;
          uint256 amount;
      }
      struct ConduitBatch1155Transfer {
          address token;
          address from;
          address to;
          uint256[] ids;
          uint256[] amounts;
      }
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      // error ChannelClosed(address channel)
      uint256 constant ChannelClosed_error_signature = (
          0x93daadf200000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ChannelClosed_error_ptr = 0x00;
      uint256 constant ChannelClosed_channel_ptr = 0x4;
      uint256 constant ChannelClosed_error_length = 0x24;
      // For the mapping:
      // mapping(address => bool) channels
      // The position in storage for a particular account is:
      // keccak256(abi.encode(account, channels.slot))
      uint256 constant ChannelKey_channel_ptr = 0x00;
      uint256 constant ChannelKey_slot_ptr = 0x20;
      uint256 constant ChannelKey_length = 0x40;
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      /*
       * -------------------------- Disambiguation & Other Notes ---------------------
       *    - The term "head" is used as it is in the documentation for ABI encoding,
       *      but only in reference to dynamic types, i.e. it always refers to the
       *      offset or pointer to the body of a dynamic type. In calldata, the head
       *      is always an offset (relative to the parent object), while in memory,
       *      the head is always the pointer to the body. More information found here:
       *      https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#argument-encoding
       *        - Note that the length of an array is separate from and precedes the
       *          head of the array.
       *
       *    - The term "body" is used in place of the term "head" used in the ABI
       *      documentation. It refers to the start of the data for a dynamic type,
       *      e.g. the first word of a struct or the first word of the first element
       *      in an array.
       *
       *    - The term "pointer" is used to describe the absolute position of a value
       *      and never an offset relative to another value.
       *        - The suffix "_ptr" refers to a memory pointer.
       *        - The suffix "_cdPtr" refers to a calldata pointer.
       *
       *    - The term "offset" is used to describe the position of a value relative
       *      to some parent value. For example, OrderParameters_conduit_offset is the
       *      offset to the "conduit" value in the OrderParameters struct relative to
       *      the start of the body.
       *        - Note: Offsets are used to derive pointers.
       *
       *    - Some structs have pointers defined for all of their fields in this file.
       *      Lines which are commented out are fields that are not used in the
       *      codebase but have been left in for readability.
       */
      uint256 constant AlmostOneWord = 0x1f;
      uint256 constant OneWord = 0x20;
      uint256 constant TwoWords = 0x40;
      uint256 constant ThreeWords = 0x60;
      uint256 constant FreeMemoryPointerSlot = 0x40;
      uint256 constant ZeroSlot = 0x60;
      uint256 constant DefaultFreeMemoryPointer = 0x80;
      uint256 constant Slot0x80 = 0x80;
      uint256 constant Slot0xA0 = 0xa0;
      uint256 constant Slot0xC0 = 0xc0;
      // abi.encodeWithSignature("transferFrom(address,address,uint256)")
      uint256 constant ERC20_transferFrom_signature = (
          0x23b872dd00000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC20_transferFrom_sig_ptr = 0x0;
      uint256 constant ERC20_transferFrom_from_ptr = 0x04;
      uint256 constant ERC20_transferFrom_to_ptr = 0x24;
      uint256 constant ERC20_transferFrom_amount_ptr = 0x44;
      uint256 constant ERC20_transferFrom_length = 0x64; // 4 + 32 * 3 == 100
      // abi.encodeWithSignature(
      //     "safeTransferFrom(address,address,uint256,uint256,bytes)"
      // )
      uint256 constant ERC1155_safeTransferFrom_signature = (
          0xf242432a00000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC1155_safeTransferFrom_sig_ptr = 0x0;
      uint256 constant ERC1155_safeTransferFrom_from_ptr = 0x04;
      uint256 constant ERC1155_safeTransferFrom_to_ptr = 0x24;
      uint256 constant ERC1155_safeTransferFrom_id_ptr = 0x44;
      uint256 constant ERC1155_safeTransferFrom_amount_ptr = 0x64;
      uint256 constant ERC1155_safeTransferFrom_data_offset_ptr = 0x84;
      uint256 constant ERC1155_safeTransferFrom_data_length_ptr = 0xa4;
      uint256 constant ERC1155_safeTransferFrom_length = 0xc4; // 4 + 32 * 6 == 196
      uint256 constant ERC1155_safeTransferFrom_data_length_offset = 0xa0;
      // abi.encodeWithSignature(
      //     "safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)"
      // )
      uint256 constant ERC1155_safeBatchTransferFrom_signature = (
          0x2eb2c2d600000000000000000000000000000000000000000000000000000000
      );
      bytes4 constant ERC1155_safeBatchTransferFrom_selector = bytes4(
          bytes32(ERC1155_safeBatchTransferFrom_signature)
      );
      uint256 constant ERC721_transferFrom_signature = ERC20_transferFrom_signature;
      uint256 constant ERC721_transferFrom_sig_ptr = 0x0;
      uint256 constant ERC721_transferFrom_from_ptr = 0x04;
      uint256 constant ERC721_transferFrom_to_ptr = 0x24;
      uint256 constant ERC721_transferFrom_id_ptr = 0x44;
      uint256 constant ERC721_transferFrom_length = 0x64; // 4 + 32 * 3 == 100
      // abi.encodeWithSignature("NoContract(address)")
      uint256 constant NoContract_error_signature = (
          0x5f15d67200000000000000000000000000000000000000000000000000000000
      );
      uint256 constant NoContract_error_sig_ptr = 0x0;
      uint256 constant NoContract_error_token_ptr = 0x4;
      uint256 constant NoContract_error_length = 0x24; // 4 + 32 == 36
      // abi.encodeWithSignature(
      //     "TokenTransferGenericFailure(address,address,address,uint256,uint256)"
      // )
      uint256 constant TokenTransferGenericFailure_error_signature = (
          0xf486bc8700000000000000000000000000000000000000000000000000000000
      );
      uint256 constant TokenTransferGenericFailure_error_sig_ptr = 0x0;
      uint256 constant TokenTransferGenericFailure_error_token_ptr = 0x4;
      uint256 constant TokenTransferGenericFailure_error_from_ptr = 0x24;
      uint256 constant TokenTransferGenericFailure_error_to_ptr = 0x44;
      uint256 constant TokenTransferGenericFailure_error_id_ptr = 0x64;
      uint256 constant TokenTransferGenericFailure_error_amount_ptr = 0x84;
      // 4 + 32 * 5 == 164
      uint256 constant TokenTransferGenericFailure_error_length = 0xa4;
      // abi.encodeWithSignature(
      //     "BadReturnValueFromERC20OnTransfer(address,address,address,uint256)"
      // )
      uint256 constant BadReturnValueFromERC20OnTransfer_error_signature = (
          0x9889192300000000000000000000000000000000000000000000000000000000
      );
      uint256 constant BadReturnValueFromERC20OnTransfer_error_sig_ptr = 0x0;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_token_ptr = 0x4;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_from_ptr = 0x24;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_to_ptr = 0x44;
      uint256 constant BadReturnValueFromERC20OnTransfer_error_amount_ptr = 0x64;
      // 4 + 32 * 4 == 132
      uint256 constant BadReturnValueFromERC20OnTransfer_error_length = 0x84;
      uint256 constant ExtraGasBuffer = 0x20;
      uint256 constant CostPerWord = 3;
      uint256 constant MemoryExpansionCoefficient = 0x200;
      // Values are offset by 32 bytes in order to write the token to the beginning
      // in the event of a revert
      uint256 constant BatchTransfer1155Params_ptr = 0x24;
      uint256 constant BatchTransfer1155Params_ids_head_ptr = 0x64;
      uint256 constant BatchTransfer1155Params_amounts_head_ptr = 0x84;
      uint256 constant BatchTransfer1155Params_data_head_ptr = 0xa4;
      uint256 constant BatchTransfer1155Params_data_length_basePtr = 0xc4;
      uint256 constant BatchTransfer1155Params_calldata_baseSize = 0xc4;
      uint256 constant BatchTransfer1155Params_ids_length_ptr = 0xc4;
      uint256 constant BatchTransfer1155Params_ids_length_offset = 0xa0;
      uint256 constant BatchTransfer1155Params_amounts_length_baseOffset = 0xc0;
      uint256 constant BatchTransfer1155Params_data_length_baseOffset = 0xe0;
      uint256 constant ConduitBatch1155Transfer_usable_head_size = 0x80;
      uint256 constant ConduitBatch1155Transfer_from_offset = 0x20;
      uint256 constant ConduitBatch1155Transfer_ids_head_offset = 0x60;
      uint256 constant ConduitBatch1155Transfer_amounts_head_offset = 0x80;
      uint256 constant ConduitBatch1155Transfer_ids_length_offset = 0xa0;
      uint256 constant ConduitBatch1155Transfer_amounts_length_baseOffset = 0xc0;
      uint256 constant ConduitBatch1155Transfer_calldata_baseSize = 0xc0;
      // Note: abbreviated version of above constant to adhere to line length limit.
      uint256 constant ConduitBatchTransfer_amounts_head_offset = 0x80;
      uint256 constant Invalid1155BatchTransferEncoding_ptr = 0x00;
      uint256 constant Invalid1155BatchTransferEncoding_length = 0x04;
      uint256 constant Invalid1155BatchTransferEncoding_selector = (
          0xeba2084c00000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC1155BatchTransferGenericFailure_error_signature = (
          0xafc445e200000000000000000000000000000000000000000000000000000000
      );
      uint256 constant ERC1155BatchTransferGenericFailure_token_ptr = 0x04;
      uint256 constant ERC1155BatchTransferGenericFailure_ids_offset = 0xc0;
      // SPDX-License-Identifier: MIT
      pragma solidity >=0.8.7;
      /**
       * @title TokenTransferrerErrors
       */
      interface TokenTransferrerErrors {
          /**
           * @dev Revert with an error when an ERC721 transfer with amount other than
           *      one is attempted.
           */
          error InvalidERC721TransferAmount();
          /**
           * @dev Revert with an error when attempting to fulfill an order where an
           *      item has an amount of zero.
           */
          error MissingItemAmount();
          /**
           * @dev Revert with an error when attempting to fulfill an order where an
           *      item has unused parameters. This includes both the token and the
           *      identifier parameters for native transfers as well as the identifier
           *      parameter for ERC20 transfers. Note that the conduit does not
           *      perform this check, leaving it up to the calling channel to enforce
           *      when desired.
           */
          error UnusedItemParameters();
          /**
           * @dev Revert with an error when an ERC20, ERC721, or ERC1155 token
           *      transfer reverts.
           *
           * @param token      The token for which the transfer was attempted.
           * @param from       The source of the attempted transfer.
           * @param to         The recipient of the attempted transfer.
           * @param identifier The identifier for the attempted transfer.
           * @param amount     The amount for the attempted transfer.
           */
          error TokenTransferGenericFailure(
              address token,
              address from,
              address to,
              uint256 identifier,
              uint256 amount
          );
          /**
           * @dev Revert with an error when a batch ERC1155 token transfer reverts.
           *
           * @param token       The token for which the transfer was attempted.
           * @param from        The source of the attempted transfer.
           * @param to          The recipient of the attempted transfer.
           * @param identifiers The identifiers for the attempted transfer.
           * @param amounts     The amounts for the attempted transfer.
           */
          error ERC1155BatchTransferGenericFailure(
              address token,
              address from,
              address to,
              uint256[] identifiers,
              uint256[] amounts
          );
          /**
           * @dev Revert with an error when an ERC20 token transfer returns a falsey
           *      value.
           *
           * @param token      The token for which the ERC20 transfer was attempted.
           * @param from       The source of the attempted ERC20 transfer.
           * @param to         The recipient of the attempted ERC20 transfer.
           * @param amount     The amount for the attempted ERC20 transfer.
           */
          error BadReturnValueFromERC20OnTransfer(
              address token,
              address from,
              address to,
              uint256 amount
          );
          /**
           * @dev Revert with an error when an account being called as an assumed
           *      contract does not have code and returns no data.
           *
           * @param account The account that should contain code.
           */
          error NoContract(address account);
          /**
           * @dev Revert with an error when attempting to execute an 1155 batch
           *      transfer using calldata not produced by default ABI encoding or with
           *      different lengths for ids and amounts arrays.
           */
          error Invalid1155BatchTransferEncoding();
      }