ETH Price: $2,115.85 (-2.99%)

Transaction Decoder

Block:
19644532 at Apr-13-2024 05:20:35 AM +UTC
Transaction Fee:
0.00200534673565512 ETH $4.24
Gas Used:
182,039 Gas / 11.01602808 Gwei

Emitted Events:

579 PaymentProcessor.NonceInvalidated( nonce=69005277841611552456666767078621072521642912468796321438269508217196416860271, account=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, wasCancellation=False )
580 ProbablyNothing.Approval( owner=[Sender] 0x138df8ceb2fe8b68ad3936d7921a5421651a12f8, approved=0x00000000...000000000, tokenId=6859 )
581 ProbablyNothing.Transfer( from=[Sender] 0x138df8ceb2fe8b68ad3936d7921a5421651a12f8, to=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, tokenId=6859 )
582 WETH9.Transfer( src=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, dst=0xCA9337244B5F04cB946391bC8B8A980e988f9A6A, wad=55500000000000 )
583 WETH9.Transfer( src=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, dst=[Sender] 0x138df8ceb2fe8b68ad3936d7921a5421651a12f8, wad=11044500000000000 )
584 PaymentProcessor.AcceptOfferERC721( seller=[Sender] 0x138df8ceb2fe8b68ad3936d7921a5421651a12f8, buyer=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, tokenAddress=ProbablyNothing, beneficiary=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, paymentCoin=WETH9, tokenId=6859, salePrice=11100000000000000 )

Account State Difference:

  Address   Before After State Difference Code
0x138Df8ce...1651A12f8
0.007228229598360724 Eth
Nonce: 98
0.005222882862705604 Eth
Nonce: 99
0.00200534673565512
0x9A1D00bE...22Aac6834
(Limit Break: Payment Processor (V2))
0xB9aEcB63...e0DaBa78A
0xC02aaA39...83C756Cc2
(MEV Builder: 0xf156...8e1)
6.503388181761426243 Eth6.503388199965326243 Eth0.0000000182039

Execution Trace

TrustedForwarder.forwardCall( target=0x9A1D00bEd7CD04BCDA516d721A596eb22Aac6834, message=0x08FDD68E00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000420366C197F70B07438A884ACC9C6424F7A2B935BA6EC54C8064A2527B1338A5A95000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000BA15CF033DC6EA4C2AB410D9719C8D4F61604C90000000000000000000000000BA15CF033DC6EA4C2AB410D9719C8D4F61604C9000000000000000000000000CA9337244B5F04CB946391BC8B8A980E988F9A6A000000000000000000000000EC45E904B11C764D1A842B16F874A5474914DA71000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000B9AECB63908C13B6167AD2EAB9BACD7E0DABA78A0000000000000000000000000000000000000000000000000000000000001ACB000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000276F642501C000988F9A6A0000000000000000000000000000000000000000000000000000006F00000000000000000000000000000000000000000000000000000000661FE9900000000000000000000000000000000000000000000000000000000000000032000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001C3D2C34EA085BDAD67FD4F1D536E8F20E8566539C9072462AE84D4095EE8B1C265D0A8792199DD7C71EA1A0701AA137EF44478A51A36DDEA9031B1C1321A9864E00000000000000000000000000000000000000000000000000000000000003C000000000000000000000000032DA57E736E05F75AA4FAE2E9BE60FD904492726000000000000000000000000138DF8CEB2FE8B68AD3936D7921A5421651A12F800000000000000000000000000000000000000000000000000000000661A1628000000000000000000000000000000000000000000000000000000000000001C9B088B0E31499519FD79C10536A83B780F6144A0CB9A1BC8655FF4489AE3DC485726E8A462A6CEB20B9292CFF83D3D928AD0A585D06FB100E89C6A0BE73EFF6A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000 ) => ( returnData=0x )
  • TrustedForwarder.forwardCall( target=0x9A1D00bEd7CD04BCDA516d721A596eb22Aac6834, message=0x08FDD68E00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000420366C197F70B07438A884ACC9C6424F7A2B935BA6EC54C8064A2527B1338A5A95000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000BA15CF033DC6EA4C2AB410D9719C8D4F61604C90000000000000000000000000BA15CF033DC6EA4C2AB410D9719C8D4F61604C9000000000000000000000000CA9337244B5F04CB946391BC8B8A980E988F9A6A000000000000000000000000EC45E904B11C764D1A842B16F874A5474914DA71000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000B9AECB63908C13B6167AD2EAB9BACD7E0DABA78A0000000000000000000000000000000000000000000000000000000000001ACB000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000276F642501C000988F9A6A0000000000000000000000000000000000000000000000000000006F00000000000000000000000000000000000000000000000000000000661FE9900000000000000000000000000000000000000000000000000000000000000032000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001C3D2C34EA085BDAD67FD4F1D536E8F20E8566539C9072462AE84D4095EE8B1C265D0A8792199DD7C71EA1A0701AA137EF44478A51A36DDEA9031B1C1321A9864E00000000000000000000000000000000000000000000000000000000000003C000000000000000000000000032DA57E736E05F75AA4FAE2E9BE60FD904492726000000000000000000000000138DF8CEB2FE8B68AD3936D7921A5421651A12F800000000000000000000000000000000000000000000000000000000661A1628000000000000000000000000000000000000000000000000000000000000001C9B088B0E31499519FD79C10536A83B780F6144A0CB9A1BC8655FF4489AE3DC485726E8A462A6CEB20B9292CFF83D3D928AD0A585D06FB100E89C6A0BE73EFF6A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000 ) => ( returnData=0x )
    • PaymentProcessor.acceptOffer( data=0x366C197F70B07438A884ACC9C6424F7A2B935BA6EC54C8064A2527B1338A5A95000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000BA15CF033DC6EA4C2AB410D9719C8D4F61604C90000000000000000000000000BA15CF033DC6EA4C2AB410D9719C8D4F61604C9000000000000000000000000CA9337244B5F04CB946391BC8B8A980E988F9A6A000000000000000000000000EC45E904B11C764D1A842B16F874A5474914DA71000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000B9AECB63908C13B6167AD2EAB9BACD7E0DABA78A0000000000000000000000000000000000000000000000000000000000001ACB000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000276F642501C000988F9A6A0000000000000000000000000000000000000000000000000000006F00000000000000000000000000000000000000000000000000000000661FE9900000000000000000000000000000000000000000000000000000000000000032000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001C3D2C34EA085BDAD67FD4F1D536E8F20E8566539C9072462AE84D4095EE8B1C265D0A8792199DD7C71EA1A0701AA137EF44478A51A36DDEA9031B1C1321A9864E00000000000000000000000000000000000000000000000000000000000003C000000000000000000000000032DA57E736E05F75AA4FAE2E9BE60FD904492726000000000000000000000000138DF8CEB2FE8B68AD3936D7921A5421651A12F800000000000000000000000000000000000000000000000000000000661A1628000000000000000000000000000000000000000000000000000000000000001C9B088B0E31499519FD79C10536A83B780F6144A0CB9A1BC8655FF4489AE3DC485726E8A462A6CEB20B9292CFF83D3D928AD0A585D06FB100E89C6A0BE73EFF6A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000 )
      • ModuleTrades.acceptOffer( )
        • TrustedForwarderFactory.isTrustedForwarder( sender=0x5ebc127fae83ed5bdd91fc6a5f5767E259dF5642 ) => ( True )
        • Null: 0x000...001.f733a7cd( )
        • Null: 0x000...001.c0f066de( )
        • ProbablyNothing.transferFrom( from=0x138Df8ceB2Fe8b68Ad3936D7921A5421651A12f8, to=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, tokenId=6859 )
        • ProbablyNothing.2a55205a( )
        • WETH9.transferFrom( src=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, dst=0xCA9337244B5F04cB946391bC8B8A980e988f9A6A, wad=55500000000000 ) => ( True )
        • WETH9.transferFrom( src=0x0ba15cf033DC6EA4C2aB410D9719C8D4F61604C9, dst=0x138Df8ceB2Fe8b68Ad3936D7921A5421651A12f8, wad=11044500000000000 ) => ( True )
          File 1 of 7: TrustedForwarder
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.4;
          import "@openzeppelin/contracts/access/Ownable.sol";
          import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
          import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
          import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
          /**
           * @title  TrustedForwarder
           * @author Limit Break, Inc.
           * @notice TrustedForwarder is a generic message forwarder, which allows you to relay transactions to any contract and preserve the original sender.
           *         The processor acts as a trusted proxy, which can be a way to limit interactions with your contract, or enforce certain conditions.
           */
          contract TrustedForwarder is EIP712, Initializable, Ownable {
              error TrustedForwarder__CannotSetAppSignerToZeroAddress();
              error TrustedForwarder__CannotSetOwnerToZeroAddress();
              error TrustedForwarder__CannotUseWithoutSignature();
              error TrustedForwarder__InvalidSignature();
              error TrustedForwarder__SignerNotAuthorized();
              struct SignatureECDSA {
                  uint8 v;
                  bytes32 r;
                  bytes32 s;
              }
              // keccak256("AppSigner(bytes32 messageHash,address target,address sender)")
              bytes32 public constant APP_SIGNER_TYPEHASH = 0xc83d02443cc9e12c5d2faae8a9a36bf0112f5b4a8cce23c9277a0c68bf638762;
              address public signer;
              constructor() EIP712("TrustedForwarder", "1") {}
              /**
               * @notice Initializes the TrustedForwarder contract.
               *
               * @dev    This should be called atomically with the clone of the contract to prevent bad actors from calling it.
               * @dev    - Throws if the contract is already initialized
               *
               * @param owner           The address to assign the owner role to.
               * @param appSigner       The address to assign the app signer role to.
               */
              function __TrustedForwarder_init(address owner, address appSigner) external initializer {
                  if (owner == address(0)) {
                      revert TrustedForwarder__CannotSetOwnerToZeroAddress();
                  }
                  if (appSigner != address(0)) {
                      signer = appSigner;
                  }
                  _transferOwnership(owner);
              }
              /**
               * @notice Forwards a message to a target contract, preserving the original sender.
               * @notice In the case the forwarder does not require a signature, this function should be used to save gas.
               *
               * @dev    - Throws if the target contract reverts.
               * @dev    - Throws if the target address has no code.
               * @dev    - Throws if `signer` is not address(0).
               *
               * @param target    The address of the contract to forward the message to.
               * @param message   The calldata to forward.
               *
               * @return returnData The return data of the call to the target contract.
               */
              function forwardCall(address target, bytes calldata message)
                  external
                  payable
                  returns (bytes memory returnData)
              {
                  address signerCache = signer;
                  if (signerCache != address(0)) {
                      revert TrustedForwarder__CannotUseWithoutSignature();
                  }
                  bytes memory encodedData = _encodeERC2771Context(message, _msgSender());
                  assembly {
                      let success := call(gas(), target, callvalue(), add(encodedData, 0x20), mload(encodedData), 0, 0)
                      let size := returndatasize()
                      returnData := mload(0x40)
                      mstore(returnData, size)
                      mstore(0x40, add(add(returnData, 0x20), size)) // Adjust memory pointer
                      returndatacopy(add(returnData, 0x20), 0, size) // Copy returndata to memory
                      if iszero(success) {
                          revert(add(returnData, 0x20), size) // Revert with return data on failure
                      }
                      // If the call was successful, but the return data is empty, check if the target address has code
                      if iszero(size) {
                          if iszero(extcodesize(target)) {
                              mstore(0x00, 0x39bf07c1) // Store function selector `TrustedForwarder__TargetAddressHasNoCode()` and revert
                              revert(0x1c, 0x04) // Revert with the custom function selector
                          }
                      }
                  }
              }
              /**
               * @notice Forwards a message to a target contract, preserving the original sender.
               * @notice This should only be used if the forwarder requires a signature.
               * @notice In the case the app signer is not set, use the overloaded `forwardCall` function without a signature variable.
               *
               * @dev    - Throws if the target contract reverts.
               * @dev    - Throws if the target address has no code.
               * @dev    - Throws if `signer` is not address(0) and the signature does not match the signer.
               *
               * @param target    The address of the contract to forward the message to.
               * @param message   The calldata to forward.
               * @param signature The signature of the message.
               *
               * @return returnData The return data of the call to the target contract.
               */
              function forwardCall(address target, bytes calldata message, SignatureECDSA calldata signature)
                  external
                  payable
                  returns (bytes memory returnData)
              {
                  address signerCache = signer;
                  if (signerCache != address(0)) {
                      if (
                              signerCache != _ecdsaRecover(
                                  _hashTypedDataV4(
                                      keccak256(abi.encode(APP_SIGNER_TYPEHASH, keccak256(message), target, _msgSender()))
                                  ),
                                  signature.v,
                                  signature.r,
                                  signature.s
                              )
                      ) {
                          revert TrustedForwarder__SignerNotAuthorized();
                      }
                  }
                  bytes memory encodedData = _encodeERC2771Context(message, _msgSender());
                  assembly {
                      let success := call(gas(), target, callvalue(), add(encodedData, 0x20), mload(encodedData), 0, 0)
                      let size := returndatasize()
                      returnData := mload(0x40)
                      mstore(returnData, size)
                      mstore(0x40, add(add(returnData, 0x20), size)) // Adjust memory pointer
                      returndatacopy(add(returnData, 0x20), 0, size) // Copy returndata to memory
                      if iszero(success) {
                          revert(add(returnData, 0x20), size) // Revert with return data on failure
                      }
                      // If the call was successful, but the return data is empty, check if the target address has code
                      if iszero(size) {
                          if iszero(extcodesize(target)) {
                              mstore(0x00, 0x39bf07c1) // Store function selector `TrustedForwarder__TargetAddressHasNoCode()` and revert
                              revert(0x1c, 0x04) // Revert with the custom function selector
                          }
                      }
                  }
              }
              /**
               * @notice Updates the app signer address. To disable app signing, set signer to address(0).
               *
               * @dev    - Throws if the sender is not the owner.
               *
               * @param signer_ The address to assign the app signer role to.
               */
              function updateSigner(address signer_) external onlyOwner {
                  if (signer_ == address(0)) {
                      revert TrustedForwarder__CannotSetAppSignerToZeroAddress();
                  }
                  signer = signer_;
              }
              /**
               * @notice Resets the app signer address to address(0).
               *
               * @dev    - Throws if the sender is not the owner.
               */
               function deactivateSigner() external onlyOwner {
                  signer = address(0);
              }
              /**
               * @notice Returns the domain separator used in the permit signature
               *
               * @return The domain separator
               */
              function domainSeparatorV4() external view returns (bytes32) {
                  return _domainSeparatorV4();
              }
              /// @dev appends the msg.sender to the end of the calldata
              function _encodeERC2771Context(bytes calldata _data, address _msgSender) internal pure returns (bytes memory encodedData) {
                  assembly  {
                      // Calculate total length: data.length + 20 bytes for the address
                      let totalLength := add(_data.length, 20)
                      // Allocate memory for the combined data
                      encodedData := mload(0x40)
                      mstore(0x40, add(encodedData, add(totalLength, 0x20)))
                      // Set the length of the `encodedData`
                      mstore(encodedData, totalLength)
                      // Copy the `bytes calldata` data
                      calldatacopy(add(encodedData, 0x20), _data.offset, _data.length)
                      // Append the `address`. Addresses are 20 bytes, stored in the last 20 bytes of a 32-byte word
                      mstore(add(add(encodedData, 0x20), _data.length), shl(96, _msgSender))
                  }
              }
              /**
               * @notice Recovers an ECDSA signature
               *
               * @dev    This function is copied from OpenZeppelin's ECDSA library
               *
               * @param digest The digest to recover
               * @param v      The v component of the signature
               * @param r      The r component of the signature
               * @param s      The s component of the signature
               *
               * @return recoveredSigner The signer of the digest
               */
              function _ecdsaRecover(bytes32 digest, uint8 v, bytes32 r, bytes32 s) internal pure returns (address recoveredSigner) {
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      revert TrustedForwarder__InvalidSignature();
                  }
                  recoveredSigner = ecrecover(digest, v, r, s);
                  if (recoveredSigner == address(0)) {
                      revert TrustedForwarder__InvalidSignature();
                  }
              }
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
          pragma solidity ^0.8.0;
          import "../utils/Context.sol";
          /**
           * @dev Contract module which provides a basic access control mechanism, where
           * there is an account (an owner) that can be granted exclusive access to
           * specific functions.
           *
           * By default, the owner account will be the one that deploys the contract. This
           * can later be changed with {transferOwnership}.
           *
           * This module is used through inheritance. It will make available the modifier
           * `onlyOwner`, which can be applied to your functions to restrict their use to
           * the owner.
           */
          abstract contract Ownable is Context {
              address private _owner;
              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
              /**
               * @dev Initializes the contract setting the deployer as the initial owner.
               */
              constructor() {
                  _transferOwnership(_msgSender());
              }
              /**
               * @dev Throws if called by any account other than the owner.
               */
              modifier onlyOwner() {
                  _checkOwner();
                  _;
              }
              /**
               * @dev Returns the address of the current owner.
               */
              function owner() public view virtual returns (address) {
                  return _owner;
              }
              /**
               * @dev Throws if the sender is not the owner.
               */
              function _checkOwner() internal view virtual {
                  require(owner() == _msgSender(), "Ownable: caller is not the owner");
              }
              /**
               * @dev Leaves the contract without owner. It will not be possible to call
               * `onlyOwner` functions. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby disabling any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                  _transferOwnership(newOwner);
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Internal function without access restriction.
               */
              function _transferOwnership(address newOwner) internal virtual {
                  address oldOwner = _owner;
                  _owner = newOwner;
                  emit OwnershipTransferred(oldOwner, newOwner);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
          pragma solidity ^0.8.2;
          import "../../utils/Address.sol";
          /**
           * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
           * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
           * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
           * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
           *
           * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
           * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
           * case an upgrade adds a module that needs to be initialized.
           *
           * For example:
           *
           * [.hljs-theme-light.nopadding]
           * ```solidity
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           *
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
               * constructor.
               *
               * Emits an {Initialized} event.
               */
              modifier initializer() {
                  bool isTopLevelCall = !_initializing;
                  require(
                      (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
                      "Initializable: contract is already initialized"
                  );
                  _initialized = 1;
                  if (isTopLevelCall) {
                      _initializing = true;
                  }
                  _;
                  if (isTopLevelCall) {
                      _initializing = false;
                      emit Initialized(1);
                  }
              }
              /**
               * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
               * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
               * used to initialize parent contracts.
               *
               * A reinitializer may be used after the original initialization step. This is essential to configure modules that
               * are added through upgrades and that require initialization.
               *
               * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
               * cannot be nested. If one is invoked in the context of another, execution will revert.
               *
               * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
               * a contract, executing them in the right order is up to the developer or operator.
               *
               * WARNING: setting the version to 255 will prevent any future reinitialization.
               *
               * Emits an {Initialized} event.
               */
              modifier reinitializer(uint8 version) {
                  require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                  _initialized = version;
                  _initializing = true;
                  _;
                  _initializing = false;
                  emit Initialized(version);
              }
              /**
               * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
               * {initializer} and {reinitializer} modifiers, directly or indirectly.
               */
              modifier onlyInitializing() {
                  require(_initializing, "Initializable: contract is not initializing");
                  _;
              }
              /**
               * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
               * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
               * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
               * through proxies.
               *
               * Emits an {Initialized} event the first time it is successfully executed.
               */
              function _disableInitializers() internal virtual {
                  require(!_initializing, "Initializable: contract is initializing");
                  if (_initialized != type(uint8).max) {
                      _initialized = type(uint8).max;
                      emit Initialized(type(uint8).max);
                  }
              }
              /**
               * @dev Returns the highest version that has been initialized. See {reinitializer}.
               */
              function _getInitializedVersion() internal view returns (uint8) {
                  return _initialized;
              }
              /**
               * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
               */
              function _isInitializing() internal view returns (bool) {
                  return _initializing;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
          pragma solidity ^0.8.8;
          import "./ECDSA.sol";
          import "../ShortStrings.sol";
          import "../../interfaces/IERC5267.sol";
          /**
           * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
           *
           * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
           * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
           * they need in their contracts using a combination of `abi.encode` and `keccak256`.
           *
           * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
           * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
           * ({_hashTypedDataV4}).
           *
           * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
           * the chain id to protect against replay attacks on an eventual fork of the chain.
           *
           * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
           * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
           *
           * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
           * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
           * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
           *
           * _Available since v3.4._
           *
           * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
           */
          abstract contract EIP712 is IERC5267 {
              using ShortStrings for *;
              bytes32 private constant _TYPE_HASH =
                  keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
              // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
              // invalidate the cached domain separator if the chain id changes.
              bytes32 private immutable _cachedDomainSeparator;
              uint256 private immutable _cachedChainId;
              address private immutable _cachedThis;
              bytes32 private immutable _hashedName;
              bytes32 private immutable _hashedVersion;
              ShortString private immutable _name;
              ShortString private immutable _version;
              string private _nameFallback;
              string private _versionFallback;
              /**
               * @dev Initializes the domain separator and parameter caches.
               *
               * The meaning of `name` and `version` is specified in
               * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
               *
               * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
               * - `version`: the current major version of the signing domain.
               *
               * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
               * contract upgrade].
               */
              constructor(string memory name, string memory version) {
                  _name = name.toShortStringWithFallback(_nameFallback);
                  _version = version.toShortStringWithFallback(_versionFallback);
                  _hashedName = keccak256(bytes(name));
                  _hashedVersion = keccak256(bytes(version));
                  _cachedChainId = block.chainid;
                  _cachedDomainSeparator = _buildDomainSeparator();
                  _cachedThis = address(this);
              }
              /**
               * @dev Returns the domain separator for the current chain.
               */
              function _domainSeparatorV4() internal view returns (bytes32) {
                  if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
                      return _cachedDomainSeparator;
                  } else {
                      return _buildDomainSeparator();
                  }
              }
              function _buildDomainSeparator() private view returns (bytes32) {
                  return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
              }
              /**
               * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
               * function returns the hash of the fully encoded EIP712 message for this domain.
               *
               * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
               *
               * ```solidity
               * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
               *     keccak256("Mail(address to,string contents)"),
               *     mailTo,
               *     keccak256(bytes(mailContents))
               * )));
               * address signer = ECDSA.recover(digest, signature);
               * ```
               */
              function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                  return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
              }
              /**
               * @dev See {EIP-5267}.
               *
               * _Available since v4.9._
               */
              function eip712Domain()
                  public
                  view
                  virtual
                  override
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  )
              {
                  return (
                      hex"0f", // 01111
                      _name.toStringWithFallback(_nameFallback),
                      _version.toStringWithFallback(_versionFallback),
                      block.chainid,
                      address(this),
                      bytes32(0),
                      new uint256[](0)
                  );
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
          pragma solidity ^0.8.0;
          import "../Strings.sol";
          /**
           * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
           *
           * These functions can be used to verify that a message was signed by the holder
           * of the private keys of a given address.
           */
          library ECDSA {
              enum RecoverError {
                  NoError,
                  InvalidSignature,
                  InvalidSignatureLength,
                  InvalidSignatureS,
                  InvalidSignatureV // Deprecated in v4.8
              }
              function _throwError(RecoverError error) private pure {
                  if (error == RecoverError.NoError) {
                      return; // no error: do nothing
                  } else if (error == RecoverError.InvalidSignature) {
                      revert("ECDSA: invalid signature");
                  } else if (error == RecoverError.InvalidSignatureLength) {
                      revert("ECDSA: invalid signature length");
                  } else if (error == RecoverError.InvalidSignatureS) {
                      revert("ECDSA: invalid signature 's' value");
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature` or error string. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               *
               * Documentation for signature generation:
               * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
               * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
                  if (signature.length == 65) {
                      bytes32 r;
                      bytes32 s;
                      uint8 v;
                      // ecrecover takes the signature parameters, and the only way to get them
                      // currently is to use assembly.
                      /// @solidity memory-safe-assembly
                      assembly {
                          r := mload(add(signature, 0x20))
                          s := mload(add(signature, 0x40))
                          v := byte(0, mload(add(signature, 0x60)))
                      }
                      return tryRecover(hash, v, r, s);
                  } else {
                      return (address(0), RecoverError.InvalidSignatureLength);
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature`. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               */
              function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, signature);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
               *
               * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
                  bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                  uint8 v = uint8((uint256(vs) >> 255) + 27);
                  return tryRecover(hash, v, r, s);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
               *
               * _Available since v4.2._
               */
              function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, r, vs);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
               * `r` and `s` signature fields separately.
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
                  // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                  // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                  // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                  // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                  //
                  // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                  // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                  // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                  // these malleable signatures as well.
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      return (address(0), RecoverError.InvalidSignatureS);
                  }
                  // If the signature is valid (and not malleable), return the signer address
                  address signer = ecrecover(hash, v, r, s);
                  if (signer == address(0)) {
                      return (address(0), RecoverError.InvalidSignature);
                  }
                  return (signer, RecoverError.NoError);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `v`,
               * `r` and `s` signature fields separately.
               */
              function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from a `hash`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
                  // 32 is the length in bytes of hash,
                  // enforced by the type signature above
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(0x00, "\\x19Ethereum Signed Message:\
          32")
                      mstore(0x1c, hash)
                      message := keccak256(0x00, 0x3c)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from `s`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
          ", Strings.toString(s.length), s));
              }
              /**
               * @dev Returns an Ethereum Signed Typed Data, created from a
               * `domainSeparator` and a `structHash`. This produces hash corresponding
               * to the one signed with the
               * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
               * JSON-RPC method as part of EIP-712.
               *
               * See {recover}.
               */
              function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      let ptr := mload(0x40)
                      mstore(ptr, "\\x19\\x01")
                      mstore(add(ptr, 0x02), domainSeparator)
                      mstore(add(ptr, 0x22), structHash)
                      data := keccak256(ptr, 0x42)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Data with intended validator, created from a
               * `validator` and `data` according to the version 0 of EIP-191.
               *
               * See {recover}.
               */
              function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
              }
          }
          // 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.9.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
          pragma solidity ^0.8.8;
          import "./StorageSlot.sol";
          // | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
          // | length  | 0x                                                              BB |
          type ShortString is bytes32;
          /**
           * @dev This library provides functions to convert short memory strings
           * into a `ShortString` type that can be used as an immutable variable.
           *
           * Strings of arbitrary length can be optimized using this library if
           * they are short enough (up to 31 bytes) by packing them with their
           * length (1 byte) in a single EVM word (32 bytes). Additionally, a
           * fallback mechanism can be used for every other case.
           *
           * Usage example:
           *
           * ```solidity
           * contract Named {
           *     using ShortStrings for *;
           *
           *     ShortString private immutable _name;
           *     string private _nameFallback;
           *
           *     constructor(string memory contractName) {
           *         _name = contractName.toShortStringWithFallback(_nameFallback);
           *     }
           *
           *     function name() external view returns (string memory) {
           *         return _name.toStringWithFallback(_nameFallback);
           *     }
           * }
           * ```
           */
          library ShortStrings {
              // Used as an identifier for strings longer than 31 bytes.
              bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
              error StringTooLong(string str);
              error InvalidShortString();
              /**
               * @dev Encode a string of at most 31 chars into a `ShortString`.
               *
               * This will trigger a `StringTooLong` error is the input string is too long.
               */
              function toShortString(string memory str) internal pure returns (ShortString) {
                  bytes memory bstr = bytes(str);
                  if (bstr.length > 31) {
                      revert StringTooLong(str);
                  }
                  return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
              }
              /**
               * @dev Decode a `ShortString` back to a "normal" string.
               */
              function toString(ShortString sstr) internal pure returns (string memory) {
                  uint256 len = byteLength(sstr);
                  // using `new string(len)` would work locally but is not memory safe.
                  string memory str = new string(32);
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(str, len)
                      mstore(add(str, 0x20), sstr)
                  }
                  return str;
              }
              /**
               * @dev Return the length of a `ShortString`.
               */
              function byteLength(ShortString sstr) internal pure returns (uint256) {
                  uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
                  if (result > 31) {
                      revert InvalidShortString();
                  }
                  return result;
              }
              /**
               * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
               */
              function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
                  if (bytes(value).length < 32) {
                      return toShortString(value);
                  } else {
                      StorageSlot.getStringSlot(store).value = value;
                      return ShortString.wrap(_FALLBACK_SENTINEL);
                  }
              }
              /**
               * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               */
              function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return toString(value);
                  } else {
                      return store;
                  }
              }
              /**
               * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               *
               * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
               * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
               */
              function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return byteLength(value);
                  } else {
                      return bytes(store).length;
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
          pragma solidity ^0.8.0;
          interface IERC5267 {
              /**
               * @dev MAY be emitted to signal that the domain could have changed.
               */
              event EIP712DomainChanged();
              /**
               * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
               * signature.
               */
              function eip712Domain()
                  external
                  view
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  );
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
          pragma solidity ^0.8.0;
          import "./math/Math.sol";
          import "./math/SignedMath.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 `int256` to its ASCII `string` decimal representation.
               */
              function toString(int256 value) internal pure returns (string memory) {
                  return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  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);
              }
              /**
               * @dev Returns true if the two strings are equal.
               */
              function equal(string memory a, string memory b) internal pure returns (bool) {
                  return keccak256(bytes(a)) == keccak256(bytes(b));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
          // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for reading and writing primitive types to specific storage slots.
           *
           * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
           * This library helps with reading and writing to such slots without the need for inline assembly.
           *
           * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
           *
           * Example usage to set ERC1967 implementation slot:
           * ```solidity
           * contract ERC1967 {
           *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
           *
           *     function _getImplementation() internal view returns (address) {
           *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
           *     }
           *
           *     function _setImplementation(address newImplementation) internal {
           *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
           *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
           *     }
           * }
           * ```
           *
           * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
           * _Available since v4.9 for `string`, `bytes`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
              struct BooleanSlot {
                  bool value;
              }
              struct Bytes32Slot {
                  bytes32 value;
              }
              struct Uint256Slot {
                  uint256 value;
              }
              struct StringSlot {
                  string value;
              }
              struct BytesSlot {
                  bytes value;
              }
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
               */
              function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
               */
              function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
               */
              function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` with member `value` located at `slot`.
               */
              function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
               */
              function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` with member `value` located at `slot`.
               */
              function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
               */
              function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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) {
                          // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                          // The surrounding unchecked block does not change this fact.
                          // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1, "Math: mulDiv overflow");
                      ///////////////////////////////////////////////
                      // 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 256, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard signed math utilities missing in the Solidity language.
           */
          library SignedMath {
              /**
               * @dev Returns the largest of two signed numbers.
               */
              function max(int256 a, int256 b) internal pure returns (int256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two signed numbers.
               */
              function min(int256 a, int256 b) internal pure returns (int256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two signed numbers without overflow.
               * The result is rounded towards zero.
               */
              function average(int256 a, int256 b) internal pure returns (int256) {
                  // Formula from the book "Hacker's Delight"
                  int256 x = (a & b) + ((a ^ b) >> 1);
                  return x + (int256(uint256(x) >> 255) & (a ^ b));
              }
              /**
               * @dev Returns the absolute unsigned value of a signed value.
               */
              function abs(int256 n) internal pure returns (uint256) {
                  unchecked {
                      // must be unchecked in order to support `n = type(int256).min`
                      return uint256(n >= 0 ? n : -n);
                  }
              }
          }
          

          File 2 of 7: PaymentProcessor
          // SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "./Constants.sol";
          import "./Errors.sol";
          import "./interfaces/IPaymentProcessorConfiguration.sol";
          import "./interfaces/IPaymentProcessorEvents.sol";
          import "./interfaces/IModuleDefaultPaymentMethods.sol";
          import "./storage/PaymentProcessorStorageAccess.sol";
          import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
          /*
                                                               @@@@@@@@@@@@@@             
                                                              @@@@@@@@@@@@@@@@@@(         
                                                             @@@@@@@@@@@@@@@@@@@@@        
                                                            @@@@@@@@@@@@@@@@@@@@@@@@      
                                                                     #@@@@@@@@@@@@@@      
                                                                         @@@@@@@@@@@@     
                                      @@@@@@@@@@@@@@*                    @@@@@@@@@@@@     
                                     @@@@@@@@@@@@@@@     @               @@@@@@@@@@@@     
                                    @@@@@@@@@@@@@@@     @                @@@@@@@@@@@      
                                   @@@@@@@@@@@@@@@     @@               @@@@@@@@@@@@      
                                  @@@@@@@@@@@@@@@     #@@             @@@@@@@@@@@@/       
                                  @@@@@@@@@@@@@@.     @@@@@@@@@@@@@@@@@@@@@@@@@@@         
                                 @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@            
                                @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@             
                               @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@           
                              @@@@@@@@@@@@@@@     @@@@@&%%%%%%%%&&@@@@@@@@@@@@@@          
                              @@@@@@@@@@@@@@      @@@@@               @@@@@@@@@@@         
                             @@@@@@@@@@@@@@@     @@@@@                 @@@@@@@@@@@        
                            @@@@@@@@@@@@@@@     @@@@@@                 @@@@@@@@@@@        
                           @@@@@@@@@@@@@@@     @@@@@@@                 @@@@@@@@@@@        
                          @@@@@@@@@@@@@@@     @@@@@@@                 @@@@@@@@@@@&        
                          @@@@@@@@@@@@@@     *@@@@@@@               (@@@@@@@@@@@@         
                         @@@@@@@@@@@@@@@     @@@@@@@@             @@@@@@@@@@@@@@          
                        @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@           
                       @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@            
                      @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@              
                     .@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                 
                     @@@@@@@@@@@@@@%     @@@@@@@@@@@@@@@@@@@@@@@@(                        
                    @@@@@@@@@@@@@@@                                                       
                   @@@@@@@@@@@@@@@                                                        
                  @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                         
                 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                          
                 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&                                          
                @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                           
           
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          contract PaymentProcessor is EIP712, PaymentProcessorStorageAccess, IPaymentProcessorEvents {
              using EnumerableSet for EnumerableSet.AddressSet;
              /// @dev The Payment Settings module implements of all payment configuration-related functionality.
              address private immutable _modulePaymentSettings;
              /// @dev The On-Chain Cancellation module implements of all on-chain cancellation-related functionality.
              address private immutable _moduleOnChainCancellation;
              /// @dev The Trades module implements all trade-related functionality.
              address private immutable _moduleTrades;
              /// @dev The Trades module implements all advanced trade-related functionality.
              address private immutable _moduleTradesAdvanced;
              constructor(address configurationContract) EIP712("PaymentProcessor", "2") {
                  (
                      address defaultContractOwner_,
                      PaymentProcessorModules memory paymentProcessorModules
                  ) = IPaymentProcessorConfiguration(configurationContract).getPaymentProcessorDeploymentParams();
                  
                  
                  if (defaultContractOwner_ == address(0) ||
                      paymentProcessorModules.modulePaymentSettings == address(0) ||
                      paymentProcessorModules.moduleOnChainCancellation == address(0) ||
                      paymentProcessorModules.moduleTrades == address(0) ||
                      paymentProcessorModules.moduleTradesAdvanced == address(0)) {
                      revert PaymentProcessor__InvalidConstructorArguments();
                  }
                  _modulePaymentSettings = paymentProcessorModules.modulePaymentSettings;
                  _moduleOnChainCancellation = paymentProcessorModules.moduleOnChainCancellation;
                  _moduleTrades = paymentProcessorModules.moduleTrades;
                  _moduleTradesAdvanced = paymentProcessorModules.moduleTradesAdvanced;
                  unchecked {
                      uint32 paymentMethodWhitelistId = appStorage().lastPaymentMethodWhitelistId++;
                      appStorage().paymentMethodWhitelistOwners[paymentMethodWhitelistId] = defaultContractOwner_;
                      emit CreatedPaymentMethodWhitelist(paymentMethodWhitelistId, defaultContractOwner_, "Default Payment Methods");
                  }
              }
              /**************************************************************/
              /*                         MODIFIERS                          */
              /**************************************************************/
              /**
               * @dev Function modifier that generates a delegatecall to `module` with `selector` as the calldata
               * @dev This delegatecall is for functions that do not have parameters. The only calldata added is
               * @dev the extra calldata from a trusted forwarder, when present.
               * 
               * @param module The contract address being called in the delegatecall.
               * @param selector The 4 byte function selector for the function to call in `module`.
               */
              modifier delegateCallNoData(address module, bytes4 selector) {
                  assembly {
                      // This protocol is designed to work both via direct calls and calls from a trusted forwarder that
                      // preserves the original msg.sender by appending an extra 20 bytes to the calldata.  
                      // The following code supports both cases.  The magic number of 68 is:
                      // 4 bytes for the selector
                      let ptr := mload(0x40)
                      mstore(ptr, selector)
                      mstore(0x40, add(ptr, calldatasize()))
                      calldatacopy(add(ptr, 0x04), 0x04, sub(calldatasize(), 0x04))
                      let result := delegatecall(gas(), module, ptr, add(sub(calldatasize(), 4), 4), 0, 0)
                      if iszero(result) {
                          // Call has failed, retrieve the error message and revert
                          let size := returndatasize()
                          returndatacopy(0, 0, size)
                          revert(0, size)
                      }
                  }
                  _;
              }
              /**
               * @dev Function modifier that generates a delegatecall to `module` with `selector` and `data` as the 
               * @dev calldata. This delegatecall is for functions that have parameters but **DO NOT** take domain
               * @dev separator as a parameter. Additional calldata from a trusted forwarder is appended to the end, when present.
               * 
               * @param module The contract address being called in the delegatecall.
               * @param selector The 4 byte function selector for the function to call in `module`.
               * @param data The calldata to send to the `module`.
               */
              modifier delegateCall(address module, bytes4 selector, bytes calldata data) {
                  assembly {
                      // This protocol is designed to work both via direct calls and calls from a trusted forwarder that
                      // preserves the original msg.sender by appending an extra 20 bytes to the calldata.  
                      // The following code supports both cases.  The magic number of 68 is:
                      // 4 bytes for the selector
                      // 32 bytes calldata offset to the data parameter
                      // 32 bytes for the length of the data parameter
                      let lengthWithAppendedCalldata := sub(calldatasize(), 68)
                      let ptr := mload(0x40)
                      mstore(ptr, selector)
                      calldatacopy(add(ptr,0x04), data.offset, lengthWithAppendedCalldata)
                      mstore(0x40, add(ptr,add(0x04, lengthWithAppendedCalldata)))
                      let result := delegatecall(gas(), module, ptr, add(lengthWithAppendedCalldata, 4), 0, 0)
                      if iszero(result) {
                          // Call has failed, retrieve the error message and revert
                          let size := returndatasize()
                          returndatacopy(0, 0, size)
                          revert(0, size)
                      }
                  }        
                  _;
              }
              /**
               * @dev Function modifier that generates a delegatecall to `module` with `selector` and `data` as the 
               * @dev calldata. This delegatecall is for functions that have parameters **AND** take domain
               * @dev separator as the first parameter. Any domain separator that has been included in `data`
               * @dev will be replaced with the Payment Processor domain separator.  Additional calldata from a 
               * @dev trusted forwarder is appended to the end, when present.
               * 
               * @param module The contract address being called in the delegatecall.
               * @param selector The 4 byte function selector for the function to call in `module`.
               * @param data The calldata to send to the `module`.
               */
              modifier delegateCallReplaceDomainSeparator(address module, bytes4 selector, bytes calldata data) {
                  bytes32 domainSeparator = _domainSeparatorV4();
                  assembly {
                      // This protocol is designed to work both via direct calls and calls from a trusted forwarder that
                      // preserves the original msg.sender by appending an extra 20 bytes to the calldata.  
                      // The following code supports both cases.  The magic number of 68 is:
                      // 4 bytes for the selector
                      // 32 bytes calldata offset to the data parameter
                      // 32 bytes for the length of the data parameter
                      let lengthWithAppendedCalldata := sub(calldatasize(), 68)
                      let ptr := mload(0x40)
                      mstore(ptr, selector)
                      calldatacopy(add(ptr,0x04), data.offset, lengthWithAppendedCalldata)
                      mstore(0x40, add(ptr,add(0x04, lengthWithAppendedCalldata)))
                      mstore(add(ptr, 0x04), domainSeparator)
                  
                      let result := delegatecall(gas(), module, ptr, add(lengthWithAppendedCalldata, 4), 0, 0)
                      if iszero(result) {
                          // Call has failed, retrieve the error message and revert
                          let size := returndatasize()
                          returndatacopy(0, 0, size)
                          revert(0, size)
                      }
                  }
                  _;
              }
              /**************************************************************/
              /*                    READ ONLY ACCESSORS                     */
              /**************************************************************/
              /**
               * @notice Returns the EIP-712 domain separator for this contract.
               */
              function getDomainSeparator() public view returns (bytes32) {
                  return _domainSeparatorV4();
              }
              /**
               * @notice Returns the user-specific master nonce that allows order makers to efficiently cancel all listings or offers
               *         they made previously. The master nonce for a user only changes when they explicitly request to revoke all
               *         existing listings and offers.
               *
               * @dev    When prompting makers to sign a listing or offer, marketplaces must query the current master nonce of
               *         the user and include it in the listing/offer signature data.
               */
              function masterNonces(address account) public view returns (uint256) {
                  return appStorage().masterNonces[account];
              }
              /**
               * @notice Returns true if the nonce for the given account has been used or cancelled. In comparison to a master nonce for
               *         a user, this nonce value is specific to a single order and may only be used or cancelled a single time.
               *
               * @dev    When prompting makers to sign a listing or offer, marketplaces must generate a unique nonce value that
               *         has not been previously used for filled, unfilled or cancelled orders. User nonces are unique to each
               *         user but common to that user across all marketplaces that utilize Payment Processor and do not reset
               *         when the master nonce is incremented. Nonces are stored in a BitMap for gas efficiency so it is recommended
               *         to utilize sequential numbers that do not overlap with other marketplaces.
               */
              function isNonceUsed(address account, uint256 nonce) public view returns (bool isUsed) {
                  // The following code is equivalent to, but saves gas:
                  //
                  // uint256 slot = nonce / 256;
                  // uint256 offset = nonce % 256;
                  // uint256 slotValue = appStorage().invalidatedSignatures[account][slot];
                  // isUsed = ((slotValue >> offset) & ONE) == ONE;
                  isUsed = ((appStorage().invalidatedSignatures[account][uint248(nonce >> 8)] >> uint8(nonce)) & ONE) == ONE;
              }
              /**
               * @notice Returns the state and remaining fillable quantity of an order digest given the maker address.
               */
              function remainingFillableQuantity(
                  address account, 
                  bytes32 orderDigest
              ) external view returns (PartiallyFillableOrderStatus memory) {
                  return appStorage().partiallyFillableOrderStatuses[account][orderDigest];
              }
              /**
               * @notice Returns the payment settings for a given collection.
               *
               * @notice paymentSettings: The payment setting type for a given collection 
               *         (DefaultPaymentMethodWhitelist|AllowAnyPaymentMethod|CustomPaymentMethodWhitelist|PricingConstraints)
               * @notice paymentMethodWhitelistId: The payment method whitelist id for a given collection.  
               *         Applicable only when paymentSettings is CustomPaymentMethodWhitelist
               * @notice constrainedPricingPaymentMethod: The payment method that min/max priced collections are priced in.
               *         Applicable only when paymentSettings is PricingConstraints.
               * @notice royaltyBackfillNumerator: The royalty backfill percentage for a given collection.  Used only as a
               *         fallback when a collection does not implement EIP-2981.
               * @notice royaltyBountyNumerator: The royalty bounty percentage for a given collection.  When set, this percentage
               *         is applied to the creator's royalty amount and paid to the maker marketplace as a bounty.
               * @notice isRoyaltyBountyExclusive: When true, only the designated marketplace is eligible for royalty bounty.
               * @notice blockTradesFromUntrustedChannels: When true, only transactions from channels that the collection 
               *         authorizes will be allowed to execute.
               */
              function collectionPaymentSettings(address tokenAddress) external view returns (CollectionPaymentSettings memory) {
                  return appStorage().collectionPaymentSettings[tokenAddress];
              }
              /**
               * @notice Returns the optional creator-defined royalty bounty settings for a given collection.
               * 
               * @return royaltyBountyNumerator  The royalty bounty percentage for a given collection.  When set, this percentage
               *         is applied to the creator's royalty amount and paid to the maker marketplace as a bounty.
               * @return exclusiveBountyReceiver When non-zero, only the designated marketplace is eligible for royalty bounty.
               */
              function collectionBountySettings(
                  address tokenAddress
              ) external view returns (uint16 royaltyBountyNumerator, address exclusiveBountyReceiver) {
                  CollectionPaymentSettings memory collectionPaymentSettings = 
                      appStorage().collectionPaymentSettings[tokenAddress];
                  return (
                      collectionPaymentSettings.royaltyBountyNumerator, 
                      collectionPaymentSettings.isRoyaltyBountyExclusive ? 
                          appStorage().collectionExclusiveBountyReceivers[tokenAddress] : 
                          address(0));
              }
              /**
               * @notice Returns the optional creator-defined royalty backfill settings for a given collection.
               *         This is useful for legacy collection lacking EIP-2981 support, as the collection owner can instruct
               *         PaymentProcessor to backfill missing on-chain royalties.
               * 
               * @return royaltyBackfillNumerator  The creator royalty percentage for a given collection.  
               *         When set, this percentage is applied to the item sale price and paid to the creator if the attempt
               *         to query EIP-2981 royalties fails.
               * @return royaltyBackfillReceiver When non-zero, this is the destination address for backfilled creator royalties.
               */
              function collectionRoyaltyBackfillSettings(
                  address tokenAddress
              ) external view returns (uint16 royaltyBackfillNumerator, address royaltyBackfillReceiver) {
                  CollectionPaymentSettings memory collectionPaymentSettings = 
                      appStorage().collectionPaymentSettings[tokenAddress];
                  return (
                      collectionPaymentSettings.royaltyBackfillNumerator, 
                      collectionPaymentSettings.royaltyBackfillNumerator > 0 ?
                          appStorage().collectionRoyaltyBackfillReceivers[tokenAddress] : 
                          address(0));
              }
              /**
               * @notice Returns the address of the account that owns the specified payment method whitelist id.
               */
              function paymentMethodWhitelistOwners(uint32 paymentMethodWhitelistId) external view returns (address) {
                  return appStorage().paymentMethodWhitelistOwners[paymentMethodWhitelistId];
              }
              /**
               * @notice Returns true if the specified payment method is whitelisted for the specified payment method whitelist.
               */
              function isPaymentMethodWhitelisted(uint32 paymentMethodWhitelistId, address paymentMethod) external view returns (bool) {
                  return appStorage().collectionPaymentMethodWhitelists[paymentMethodWhitelistId].contains(paymentMethod);
              }
              /**
               * @notice Returns the pricing bounds floor price for a given collection and token id, when applicable.
               *
               * @dev    The pricing bounds floor price is only enforced when the collection payment settings are set to
               *         the PricingContraints type.
               */
              function getFloorPrice(address tokenAddress, uint256 tokenId) external view returns (uint256) {
                  PricingBounds memory tokenLevelPricingBounds = appStorage().tokenPricingBounds[tokenAddress][tokenId];
                  if (tokenLevelPricingBounds.isSet) {
                      return tokenLevelPricingBounds.floorPrice;
                  } else {
                      PricingBounds memory collectionLevelPricingBounds = appStorage().collectionPricingBounds[tokenAddress];
                      if (collectionLevelPricingBounds.isSet) {
                          return collectionLevelPricingBounds.floorPrice;
                      }
                  }
                  return 0;
              }
              /**
               * @notice Returns the pricing bounds ceiling price for a given collection and token id, when applicable.
               *
               * @dev    The pricing bounds ceiling price is only enforced when the collection payment settings are set to
               *         the PricingConstraints type.
               */
              function getCeilingPrice(address tokenAddress, uint256 tokenId) external view returns (uint256) {
                  PricingBounds memory tokenLevelPricingBounds = appStorage().tokenPricingBounds[tokenAddress][tokenId];
                  if (tokenLevelPricingBounds.isSet) {
                      return tokenLevelPricingBounds.ceilingPrice;
                  } else {
                      PricingBounds memory collectionLevelPricingBounds = appStorage().collectionPricingBounds[tokenAddress];
                      if (collectionLevelPricingBounds.isSet) {
                          return collectionLevelPricingBounds.ceilingPrice;
                      }
                  }
                  return type(uint256).max;
              }
              /**
               * @notice Returns the last created payment method whitelist id.
               */
              function lastPaymentMethodWhitelistId() external view returns (uint32) {
                  return appStorage().lastPaymentMethodWhitelistId;
              }
              /**
               * @notice Returns the set of payment methods for a given payment method whitelist.
               */
              function getWhitelistedPaymentMethods(uint32 paymentMethodWhitelistId) external view returns (address[] memory) {
                  return appStorage().collectionPaymentMethodWhitelists[paymentMethodWhitelistId].values();
              }
              /**
               * @notice Returns the set of trusted channels for a given collection.
               */
              function getTrustedChannels(address tokenAddress) external view returns (address[] memory) {
                  return appStorage().collectionTrustedChannels[tokenAddress].values();
              }
              /**
               * @notice Returns the set of banned accounts for a given collection.
               */
              function getBannedAccounts(address tokenAddress) external view returns (address[] memory) {
                  return appStorage().collectionBannedAccounts[tokenAddress].values();
              }
              /**************************************************************/
              /*           PAYMENT SETTINGS MANAGEMENT OPERATIONS           */
              /**************************************************************/
              /**
               * @notice Returns true if the specified payment method is on the deploy-time default payment method whitelist
               *         or post-deploy default payment method whitelist (id 0).
               */
              function isDefaultPaymentMethod(address paymentMethod) external view returns (bool) {
                  address[] memory defaultPaymentMethods = 
                      IModuleDefaultPaymentMethods(_modulePaymentSettings).getDefaultPaymentMethods();
                  for (uint256 i = 0; i < defaultPaymentMethods.length;) {
                      if (paymentMethod == defaultPaymentMethods[i]) {
                          return true;
                      }
                      unchecked {
                          ++i;
                      }
                  }
                  return appStorage().collectionPaymentMethodWhitelists[DEFAULT_PAYMENT_METHOD_WHITELIST_ID].contains(paymentMethod);
              }
              /**
               * @notice Returns an array of the immutable default payment methods specified at deploy time.  
               *         However, if any post-deployment default payment methods have been added, they are
               *         not returned here because using an enumerable payment method whitelist would make trades
               *         less gas efficient.  For post-deployment default payment methods, exchanges should index
               *         the `PaymentMethodAddedToWhitelist` and `PaymentMethodRemovedFromWhitelist` events.
               */
              function getDefaultPaymentMethods() external view returns (address[] memory) {
                  return IModuleDefaultPaymentMethods(_modulePaymentSettings).getDefaultPaymentMethods();
              }
              /**
               * @notice Allows any user to create a new custom payment method whitelist.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The payment method whitelist id tracker has been incremented by `1`.
               * @dev    2. The caller has been assigned as the owner of the payment method whitelist.
               * @dev    3. A `CreatedPaymentMethodWhitelist` event has been emitted.
               *
               * @param  data  Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *               `createPaymentMethodWhitelist(string calldata whitelistName)`
               * @return paymentMethodWhitelistId  The id of the newly created payment method whitelist.
               */
              function createPaymentMethodWhitelist(bytes calldata data) external returns (uint32 paymentMethodWhitelistId) {
                  address module = _modulePaymentSettings;
                  assembly {
                      // This protocol is designed to work both via direct calls and calls from a trusted forwarder that
                      // preserves the original msg.sender by appending an extra 20 bytes to the calldata.  
                      // The following code supports both cases.  The magic number of 68 is:
                      // 4 bytes for the selector
                      // 32 bytes calldata offset to the data parameter
                      // 32 bytes for the length of the data parameter
                      let lengthWithAppendedCalldata := sub(calldatasize(), 68)
                      let ptr := mload(0x40)
                      mstore(ptr, hex"f83116c9")
                      calldatacopy(add(ptr, 0x04), data.offset, lengthWithAppendedCalldata)
                      mstore(0x40, add(ptr, add(0x04, lengthWithAppendedCalldata)))
                      let result := delegatecall(gas(), module, ptr, add(lengthWithAppendedCalldata, 4), 0x00, 0x20)
                      switch result case 0 {
                          let size := returndatasize()
                          returndatacopy(0, 0, size)
                          revert(0, size)
                      } default {
                          return (0x00, 0x20)
                      }
                  }
              }
              /**
               * @notice Transfer ownership of a payment method whitelist list to a new owner.
               *
               * @dev Throws when the new owner is the zero address.
               * @dev Throws when the caller does not own the specified list.
               *
               * @dev <h4>Postconditions:</h4>
               *      1. The payment method whitelist list ownership is transferred to the new owner.
               *      2. A `ReassignedPaymentMethodWhitelistOwnership` event is emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `reassignOwnershipOfPaymentMethodWhitelist(uint32 id, address newOwner)`
               */
              function reassignOwnershipOfPaymentMethodWhitelist(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_REASSIGN_OWNERSHIP_OF_PAYMENT_METHOD_WHITELIST, data) {}
              /**
               * @notice Renounce the ownership of a payment method whitelist, rendering the list immutable.
               *
               * @dev Throws when the caller does not own the specified list.
               *
               * @dev <h4>Postconditions:</h4>
               *      1. The ownership of the specified payment method whitelist is renounced.
               *      2. A `ReassignedPaymentMethodWhitelistOwnership` event is emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `renounceOwnershipOfPaymentMethodWhitelist(uint32 id)`
               */
              function renounceOwnershipOfPaymentMethodWhitelist(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_RENOUNCE_OWNERSHIP_OF_PAYMENT_METHOD_WHITELIST, data) {}
              /**
               * @notice Allows custom payment method whitelist owners to approve a new coin for use as a payment currency.
               *
               * @dev    Throws when caller is not the owner of the specified payment method whitelist.
               * @dev    Throws when the specified coin is already whitelisted under the specified whitelist id.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. `paymentMethod` has been approved in `paymentMethodWhitelist` mapping.
               * @dev    2. A `PaymentMethodAddedToWhitelist` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `whitelistPaymentMethod(uint32 paymentMethodWhitelistId, address paymentMethod)`
               */
              function whitelistPaymentMethod(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_WHITELIST_PAYMENT_METHOD, data) {}
              /**
               * @notice Allows custom payment method whitelist owners to remove a coin from the list of approved payment currencies.
               *
               * @dev    Throws when caller is not the owner of the specified payment method whitelist.
               * @dev    Throws when the specified coin is not currently whitelisted under the specified whitelist id.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. `paymentMethod` has been removed from the `paymentMethodWhitelist` mapping.
               * @dev    2. A `PaymentMethodRemovedFromWhitelist` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `unwhitelistPaymentMethod(uint32 paymentMethodWhitelistId, address paymentMethod)`
               */
              function unwhitelistPaymentMethod(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_UNWHITELIST_PAYMENT_METHOD, data) {}
              /**
               * @notice Allows the smart contract, the contract owner, or the contract admin of any NFT collection to 
               *         specify the payment settings for their collections.
               *
               * @dev    Throws when the specified tokenAddress is address(0).
               * @dev    Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.
               * @dev    Throws when the royalty backfill numerator is greater than 10,000.
               * @dev    Throws when the royalty bounty numerator is greater than 10,000.
               * @dev    Throws when the specified payment method whitelist id does not exist.
               * 
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The `PaymentSettings` type for the collection has been set.
               * @dev    2. The `paymentMethodWhitelistId` for the collection has been set, if applicable.
               * @dev    3. The `constrainedPricingPaymentMethod` for the collection has been set, if applicable.
               * @dev    4. The `royaltyBackfillNumerator` for the collection has been set.
               * @dev    5. The `royaltyBackfillReceiver` for the collection has been set.
               * @dev    6. The `royaltyBountyNumerator` for the collection has been set.
               * @dev    7. The `exclusiveBountyReceiver` for the collection has been set.
               * @dev    8. The `blockTradesFromUntrustedChannels` for the collection has been set.
               * @dev    9. An `UpdatedCollectionPaymentSettings` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `setCollectionPaymentSettings(
                                  address tokenAddress, 
                                  PaymentSettings paymentSettings,
                                  uint32 paymentMethodWhitelistId,
                                  address constrainedPricingPaymentMethod,
                                  uint16 royaltyBackfillNumerator,
                                  address royaltyBackfillReceiver,
                                  uint16 royaltyBountyNumerator,
                                  address exclusiveBountyReceiver,
                                  bool blockTradesFromUntrustedChannels)`
               */
              function setCollectionPaymentSettings(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_SET_COLLECTION_PAYMENT_SETTINGS, data) {}
              /**
               * @notice Allows the smart contract, the contract owner, or the contract admin of any NFT collection to 
               *         specify their own bounded price at the collection level.
               *
               * @dev    Throws when the specified tokenAddress is address(0).
               * @dev    Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.
               * @dev    Throws when the specified floor price is greater than the ceiling price.
               * 
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The collection-level pricing bounds for the specified tokenAddress has been set.
               * @dev    2. An `UpdatedCollectionLevelPricingBoundaries` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `setCollectionPricingBounds(address tokenAddress, PricingBounds calldata pricingBounds)`
               */
              function setCollectionPricingBounds(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_SET_COLLECTION_PRICING_BOUNDS, data) {}
              /**
               * @notice Allows the smart contract, the contract owner, or the contract admin of any NFT collection to 
               *         specify their own bounded price at the individual token level.
               *
               * @dev    Throws when the specified tokenAddress is address(0).
               * @dev    Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.
               * @dev    Throws when the lengths of the tokenIds and pricingBounds array don't match.
               * @dev    Throws when the tokenIds or pricingBounds array length is zero. 
               * @dev    Throws when the any of the specified floor prices is greater than the ceiling price for that token id.
               * 
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The token-level pricing bounds for the specified tokenAddress and token ids has been set.
               * @dev    2. An `UpdatedTokenLevelPricingBoundaries` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `setTokenPricingBounds(
                                  address tokenAddress, 
                                  uint256[] calldata tokenIds, 
                                  PricingBounds[] calldata pricingBounds)`
               */
              function setTokenPricingBounds(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_SET_TOKEN_PRICING_BOUNDS, data) {}
              /**
               * @notice Allows trusted channels to be added to a collection.
               *
               * @dev    Throws when the specified tokenAddress is address(0).
               * @dev    Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.
               * @dev    Throws when the specified address is not a trusted forwarder.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. `channel` has been approved for trusted forwarding of trades on a collection.
               * @dev    2. A `TrustedChannelAddedForCollection` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `addTrustedChannelForCollection(
               *                  address tokenAddress, 
               *                  address channel)`
               */
              function addTrustedChannelForCollection(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_ADD_TRUSTED_CHANNEL_FOR_COLLECTION, data) {}
              /**
               * @notice Allows trusted channels to be removed from a collection.
               *
               * @dev    Throws when the specified tokenAddress is address(0).
               * @dev    Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. `channel` has been dis-approved for trusted forwarding of trades on a collection.
               * @dev    2. A `TrustedChannelRemovedForCollection` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `removeTrustedChannelForCollection(
               *                  address tokenAddress, 
               *                  address channel)`
               */
              function removeTrustedChannelForCollection(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_REMOVE_TRUSTED_CHANNEL_FOR_COLLECTION, data) {}
              /**
               * @notice Allows creator to ban accounts from a collection.
               *
               * @dev    Throws when the specified tokenAddress is address(0).
               * @dev    Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. `account` has been banned from trading on a collection.
               * @dev    2. A `BannedAccountAddedForCollection` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `addBannedAccountForCollection(
               *                  address tokenAddress, 
               *                  address account)`
               */
              function addBannedAccountForCollection(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_ADD_BANNED_ACCOUNT_FOR_COLLECTION, data) {}
              /**
               * @notice Allows creator to un-ban accounts from a collection.
               *
               * @dev    Throws when the specified tokenAddress is address(0).
               * @dev    Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. `account` ban has been lifted for trades on a collection.
               * @dev    2. A `BannedAccountRemovedForCollection` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `removeBannedAccountForCollection(
               *                  address tokenAddress, 
               *                  address account)`
               */
              function removeBannedAccountForCollection(bytes calldata data) external 
              delegateCall(_modulePaymentSettings, SELECTOR_REMOVE_BANNED_ACCOUNT_FOR_COLLECTION, data) {}
              /**************************************************************/
              /*              ON-CHAIN CANCELLATION OPERATIONS              */
              /**************************************************************/
              /**
               * @notice Allows a cosigner to destroy itself, never to be used again.  This is a fail-safe in case of a failure
               *         to secure the co-signer private key in a Web2 co-signing service.  In case of suspected cosigner key
               *         compromise, or when a co-signer key is rotated, the cosigner MUST destroy itself to prevent past listings 
               *         that were cancelled off-chain from being used by a malicious actor.
               *
               * @dev    Throws when the cosigner did not sign an authorization to self-destruct.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The cosigner can never be used to co-sign orders again.
               * @dev    2. A `DestroyedCosigner` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `destroyCosigner(address cosigner, SignatureECDSA signature)`
               */
              function destroyCosigner(bytes calldata data) external
              delegateCall(_moduleOnChainCancellation, SELECTOR_DESTROY_COSIGNER, data) {}
              /**
               * @notice Allows a maker to revoke/cancel all prior signatures of their listings and offers.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The maker's master nonce has been incremented by `1` in contract storage, rendering all signed
               *            approvals using the prior nonce unusable.
               * @dev    2. A `MasterNonceInvalidated` event has been emitted.
               */
              function revokeMasterNonce() external 
              delegateCallNoData(_moduleOnChainCancellation, SELECTOR_REVOKE_MASTER_NONCE) {}
              /**
               * @notice Allows a maker to revoke/cancel a single, previously signed listing or offer by specifying the
               *         nonce of the listing or offer.
               *
               * @dev    Throws when the maker has already revoked the nonce.
               * @dev    Throws when the nonce was already used by the maker to successfully buy or sell an NFT.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The specified `nonce` for the `_msgSender()` has been revoked and can
               *            no longer be used to execute a sale or purchase.
               * @dev    2. A `NonceInvalidated` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `revokeSingleNonce(uint256 nonce)`
               */
              function revokeSingleNonce(bytes calldata data) external 
              delegateCall(_moduleOnChainCancellation, SELECTOR_REVOKE_SINGLE_NONCE, data) {}
              /**
               * @notice Allows a maker to revoke/cancel a partially fillable order by specifying the order digest hash.
               *
               * @dev    Throws when the maker has already revoked the order digest.
               * @dev    Throws when the order digest was already used by the maker and has been fully filled.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. The specified `orderDigest` for the `_msgSender()` has been revoked and can
               *            no longer be used to execute a sale or purchase.
               * @dev    2. An `OrderDigestInvalidated` event has been emitted.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `revokeOrderDigest(bytes32 orderDigest)`
               */
              function revokeOrderDigest(bytes calldata data) external 
              delegateCall(_moduleOnChainCancellation, SELECTOR_REVOKE_ORDER_DIGEST, data) {}
              /**************************************************************/
              /*                      TAKER OPERATIONS                      */
              /**************************************************************/
              /**
               * @notice Executes a buy listing transaction for a single order item.
               *
               * @dev    Throws when the maker's nonce has already been used or has been cancelled.
               * @dev    Throws when the order has expired.
               * @dev    Throws when the combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when the taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when the maker's master nonce does not match the order details.
               * @dev    Throws when the order does not comply with the collection payment settings.
               * @dev    Throws when the maker's signature is invalid.
               * @dev    Throws when the order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when the maker or taker is a banned account for the collection.
               * @dev    Throws when the taker does not have or did not send sufficient funds to complete the purchase.
               * @dev    Throws when the token transfer fails for any reason such as lack of approvals or token no longer owned by maker.
               * @dev    Throws when the maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               * @dev    Any unused native token payment will be returned to the taker as wrapped native token.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Maker's nonce is marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Maker's partially fillable order state is updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. An `BuyListingERC721` event has been emitted for a ERC721 purchase.
               * @dev    6. An `BuyListingERC1155` event has been emitted for a ERC1155 purchase.
               * @dev    7. A `NonceInvalidated` event has been emitted for a ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for a ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `function buyListing(
               *                  bytes32 domainSeparator, 
               *                  Order memory saleDetails, 
               *                  SignatureECDSA memory sellerSignature,
               *                  Cosignature memory cosignature,
               *                  FeeOnTop memory feeOnTop)`
               */
              function buyListing(bytes calldata data) external payable 
              delegateCallReplaceDomainSeparator(_moduleTrades, SELECTOR_BUY_LISTING, data) {}
              /**
               * @notice Executes an offer accept transaction for a single order item.
               *
               * @dev    Throws when the maker's nonce has already been used or has been cancelled.
               * @dev    Throws when the order has expired.
               * @dev    Throws when the combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when the taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when the maker's master nonce does not match the order details.
               * @dev    Throws when the order does not comply with the collection payment settings.
               * @dev    Throws when the maker's signature is invalid.
               * @dev    Throws when the order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when the maker or taker is a banned account for the collection.
               * @dev    Throws when the maker does not have sufficient funds to complete the purchase.
               * @dev    Throws when the token transfer fails for any reason such as lack of approvals or token not owned by the taker.
               * @dev    Throws when the token the offer is being accepted for does not match the conditions set by the maker.
               * @dev    Throws when the maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Maker's nonce is marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Maker's partially fillable order state is updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. An `AcceptOfferERC721` event has been emitted for a ERC721 sale.
               * @dev    6. An `AcceptOfferERC1155` event has been emitted for a ERC1155 sale.
               * @dev    7. A `NonceInvalidated` event has been emitted for a ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for a ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `function acceptOffer(
               *                  bytes32 domainSeparator, 
               *                  bool isCollectionLevelOffer, 
               *                  Order memory saleDetails, 
               *                  SignatureECDSA memory buyerSignature,
               *                  TokenSetProof memory tokenSetProof,
               *                  Cosignature memory cosignature,
               *                  FeeOnTop memory feeOnTop)`
               */
              function acceptOffer(bytes calldata data) external payable 
              delegateCallReplaceDomainSeparator(_moduleTrades, SELECTOR_ACCEPT_OFFER, data) {}
              /**
               * @notice Executes a buy listing transaction for multiple order items.
               *
               * @dev    Throws when a maker's nonce has already been used or has been cancelled.
               * @dev    Throws when any order has expired.
               * @dev    Throws when any combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when any taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when a maker's master nonce does not match the order details.
               * @dev    Throws when an order does not comply with the collection payment settings.
               * @dev    Throws when a maker's signature is invalid.
               * @dev    Throws when an order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when any maker or taker is a banned account for the collection.
               * @dev    Throws when the taker does not have or did not send sufficient funds to complete the purchase.
               * @dev    Throws when a maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               * @dev    Will NOT throw when a token fails to transfer but also will not disperse payments for failed items.
               * @dev    Any unused native token payment will be returned to the taker as wrapped native token.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Makers nonces are marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Makers partially fillable order states are updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. `BuyListingERC721` events have been emitted for each ERC721 purchase.
               * @dev    6. `BuyListingERC1155` events have been emitted for each ERC1155 purchase.
               * @dev    7. A `NonceInvalidated` event has been emitted for each ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for each ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `function bulkBuyListings(
               *                  bytes32 domainSeparator, 
               *                  Order[] calldata saleDetailsArray,
               *                  SignatureECDSA[] calldata sellerSignatures,
               *                  Cosignature[] calldata cosignatures,
               *                  FeeOnTop[] calldata feesOnTop)`
               */
              function bulkBuyListings(bytes calldata data) external payable 
              delegateCallReplaceDomainSeparator(_moduleTrades, SELECTOR_BULK_BUY_LISTINGS, data) {}
              /**
               * @notice Executes an accept offer transaction for multiple order items.
               *
               * @dev    Throws when a maker's nonce has already been used or has been cancelled.
               * @dev    Throws when any order has expired.
               * @dev    Throws when any combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when any taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when a maker's master nonce does not match the order details.
               * @dev    Throws when an order does not comply with the collection payment settings.
               * @dev    Throws when a maker's signature is invalid.
               * @dev    Throws when an order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when any maker or taker is a banned account for the collection.
               * @dev    Throws when a maker does not have sufficient funds to complete the purchase.
               * @dev    Throws when the token an offer is being accepted for does not match the conditions set by the maker.
               * @dev    Throws when a maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               * @dev    Will NOT throw when a token fails to transfer but also will not disperse payments for failed items.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Makers nonces are marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Makers partially fillable order states are updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. `AcceptOfferERC721` events have been emitted for each ERC721 sale.
               * @dev    6. `AcceptOfferERC1155` events have been emitted for each ERC1155 sale.
               * @dev    7. A `NonceInvalidated` event has been emitted for each ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for each ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `function bulkAcceptOffers(
               *                  bytes32 domainSeparator, 
               *                  BulkAcceptOffersParams memory params)`
               */
              function bulkAcceptOffers(bytes calldata data) external payable 
              delegateCallReplaceDomainSeparator(_moduleTrades, SELECTOR_BULK_ACCEPT_OFFERS, data) {}
              /**
               * @notice Executes a sweep transaction for buying multiple items from the same collection.
               *
               * @dev    Throws when the sweep order protocol is ERC1155_PARTIAL_FILL (unsupported).
               * @dev    Throws when a maker's nonce has already been used or has been cancelled.
               * @dev    Throws when any order has expired.
               * @dev    Throws when any combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when the taker fee on top exceeds 100% of the combined item sale prices.
               * @dev    Throws when a maker's master nonce does not match the order details.
               * @dev    Throws when an order does not comply with the collection payment settings.
               * @dev    Throws when a maker's signature is invalid.
               * @dev    Throws when an order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when any maker or taker is a banned account for the collection.
               * @dev    Throws when the taker does not have or did not send sufficient funds to complete the purchase.
               * @dev    Will NOT throw when a token fails to transfer but also will not disperse payments for failed items.
               * @dev    Any unused native token payment will be returned to the taker as wrapped native token.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Makers nonces are marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Makers partially fillable order states are updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. `BuyListingERC721` events have been emitted for each ERC721 purchase.
               * @dev    6. `BuyListingERC1155` events have been emitted for each ERC1155 purchase.
               * @dev    7. A `NonceInvalidated` event has been emitted for each ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               *
               * @param  data Calldata encoded with PaymentProcessorEncoder.  Matches calldata for:
               *              `function sweepCollection(
               *                  bytes32 domainSeparator, 
               *                  FeeOnTop memory feeOnTop,
               *                  SweepOrder memory sweepOrder,
               *                  SweepItem[] calldata items,
               *                  SignatureECDSA[] calldata signedSellOrders,
               *                  Cosignature[] memory cosignatures)`
               */
              function sweepCollection(bytes calldata data) external payable 
              delegateCallReplaceDomainSeparator(_moduleTradesAdvanced, SELECTOR_SWEEP_COLLECTION, data) {}
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          // keccack256("Cosignature(uint8 v,bytes32 r,bytes32 s,uint256 expiration,address taker)")
          bytes32 constant COSIGNATURE_HASH = 0x347b7818601b168f6faadc037723496e9130b057c1ffef2ec4128311e19142f2;
          // keccack256("CollectionOfferApproval(uint8 protocol,address cosigner,address buyer,address beneficiary,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 nonce,uint256 masterNonce)")
          bytes32 constant COLLECTION_OFFER_APPROVAL_HASH = 0x8fe9498e93fe26b30ebf76fac07bd4705201c8609227362697082288e3b4af9c;
          // keccack256("ItemOfferApproval(uint8 protocol,address cosigner,address buyer,address beneficiary,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 tokenId,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 nonce,uint256 masterNonce)")
          bytes32 constant ITEM_OFFER_APPROVAL_HASH = 0xce2e9706d63e89ddf7ee16ce0508a1c3c9bd1904c582db2e647e6f4690a0bf6b;
          //   keccack256("TokenSetOfferApproval(uint8 protocol,address cosigner,address buyer,address beneficiary,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 nonce,uint256 masterNonce,bytes32 tokenSetMerkleRoot)")
          bytes32 constant TOKEN_SET_OFFER_APPROVAL_HASH = 0x244905ade6b0e455d12fb539a4b17d7f675db14797d514168d09814a09c70e70;
          // keccack256("SaleApproval(uint8 protocol,address cosigner,address seller,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 tokenId,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 maxRoyaltyFeeNumerator,uint256 nonce,uint256 masterNonce)")
          bytes32 constant SALE_APPROVAL_HASH = 0x938786a8256d04dc45d6d5b997005aa07c0c9e3e4925d0d6c33128d240096ebc;
          // The denominator used when calculating the marketplace fee.
          // 0.5% fee numerator is 50, 1% fee numerator is 100, 10% fee numerator is 1,000 and so on.
          uint256 constant FEE_DENOMINATOR = 100_00;
          // Default Payment Method Whitelist Id
          uint32 constant DEFAULT_PAYMENT_METHOD_WHITELIST_ID = 0;
          // Convenience to avoid magic number in bitmask get/set logic.
          uint256 constant ZERO = uint256(0);
          uint256 constant ONE = uint256(1);
          // The default admin role for NFT collections using Access Control.
          bytes32 constant DEFAULT_ACCESS_CONTROL_ADMIN_ROLE = 0x00;
          /// @dev The plain text message to sign for cosigner self-destruct signature verification
          string constant COSIGNER_SELF_DESTRUCT_MESSAGE_TO_SIGN = "COSIGNER_SELF_DESTRUCT";
          /**************************************************************/
          /*                   PRECOMPUTED SELECTORS                    */
          /**************************************************************/
          bytes4 constant SELECTOR_REASSIGN_OWNERSHIP_OF_PAYMENT_METHOD_WHITELIST= hex"a1e6917e";
          bytes4 constant SELECTOR_RENOUNCE_OWNERSHIP_OF_PAYMENT_METHOD_WHITELIST= hex"0886702e";
          bytes4 constant SELECTOR_WHITELIST_PAYMENT_METHOD = hex"bb39ce91";
          bytes4 constant SELECTOR_UNWHITELIST_PAYMENT_METHOD = hex"e9d4c14e";
          bytes4 constant SELECTOR_SET_COLLECTION_PAYMENT_SETTINGS = hex"fc5d8393";
          bytes4 constant SELECTOR_SET_COLLECTION_PRICING_BOUNDS = hex"7141ae10";
          bytes4 constant SELECTOR_SET_TOKEN_PRICING_BOUNDS = hex"22146d70";
          bytes4 constant SELECTOR_ADD_TRUSTED_CHANNEL_FOR_COLLECTION = hex"ab559c14";
          bytes4 constant SELECTOR_REMOVE_TRUSTED_CHANNEL_FOR_COLLECTION = hex"282e89f8";
          bytes4 constant SELECTOR_ADD_BANNED_ACCOUNT_FOR_COLLECTION = hex"e21dde50";
          bytes4 constant SELECTOR_REMOVE_BANNED_ACCOUNT_FOR_COLLECTION = hex"adf14a76";
          bytes4 constant SELECTOR_DESTROY_COSIGNER = hex"2aebdefe";
          bytes4 constant SELECTOR_REVOKE_MASTER_NONCE = hex"226d4adb";
          bytes4 constant SELECTOR_REVOKE_SINGLE_NONCE = hex"b6d7dc33";
          bytes4 constant SELECTOR_REVOKE_ORDER_DIGEST = hex"96ae0380";
          bytes4 constant SELECTOR_BUY_LISTING = hex"a9272951";
          bytes4 constant SELECTOR_ACCEPT_OFFER = hex"e35bb9b7";
          bytes4 constant SELECTOR_BULK_BUY_LISTINGS = hex"27add047";
          bytes4 constant SELECTOR_BULK_ACCEPT_OFFERS = hex"b3cdebdb";
          bytes4 constant SELECTOR_SWEEP_COLLECTION = hex"206576f6";
          /**************************************************************/
          /*                   EXPECTED BASE msg.data LENGTHS           */
          /**************************************************************/
          uint256 constant PROOF_ELEMENT_SIZE = 32;
          // | 4        | 32              | 512         | 96              | 192         | 64       | = 900 bytes
          // | selector | domainSeparator | saleDetails | sellerSignature | cosignature | feeOnTop |
          uint256 constant BASE_MSG_LENGTH_BUY_LISTING = 900;
          // | 4        | 32              | 32                     | 512         |  96             | 32 + (96 + (32 * proof.length)) | 192         | 64       | = 1060 bytes + (32 * proof.length)
          // | selector | domainSeparator | isCollectionLevelOffer | saleDetails |  buyerSignature | tokenSetProof                   | cosignature | feeOnTop |
          uint256 constant BASE_MSG_LENGTH_ACCEPT_OFFER = 1060;
          // | 4        | 32              | 64              | 512 * length      | 64              | 96 * length      | 64              | 192 * length | 64              | 64 * length | = 292 bytes + (864 * saleDetailsArray.length)
          // | selector | domainSeparator | length + offset | saleDetailsArray  | length + offset | sellerSignatures | length + offset | cosignatures | length + offset | feesOnTop   |
          uint256 constant BASE_MSG_LENGTH_BULK_BUY_LISTINGS = 292;
          uint256 constant BASE_MSG_LENGTH_BULK_BUY_LISTINGS_PER_ITEM = 864;
          // | 4        | 32              | 32           | 64              | 32 * length                 | 64              | 512 * length      | 64              | 96 * length          | 64              | 32 + (96 + (32 * proof.length)) | 64              | 192 * length | 64              | 64 * length | = 452 bytes + (1024 * saleDetailsArray.length) + (32 * proof.length [for each element])
          // | selector | domainSeparator | struct info? | length + offset | isCollectionLevelOfferArray | length + offset | saleDetailsArray  | length + offset | buyerSignaturesArray | length + offset | tokenSetProof                   | length + offset | cosignatures | length + offset | feesOnTop   |
          uint256 constant BASE_MSG_LENGTH_BULK_ACCEPT_OFFERS = 452;
          uint256 constant BASE_MSG_LENGTH_BULK_ACCEPT_OFFERS_PER_ITEM = 1024;
          // | 4        | 32              | 64       | 128        | 64              | 320 * length | 64              | 96 * length      | 64              | 192 * length | = 420 bytes + (608 * items.length)
          // | selector | domainSeparator | feeOnTop | sweepOrder | length + offset | items        | length + offset | signedSellOrders | length + offset | cosignatures |
          uint256 constant BASE_MSG_LENGTH_SWEEP_COLLECTION = 420;
          uint256 constant BASE_MSG_LENGTH_SWEEP_COLLECTION_PER_ITEM = 608;// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          /// @dev Thrown when an order is an ERC721 order and the amount is not one.
          error PaymentProcessor__AmountForERC721SalesMustEqualOne();
          /// @dev Thrown when an order is an ERC1155 order and the amount is zero.
          error PaymentProcessor__AmountForERC1155SalesGreaterThanZero();
          /// @dev Thrown when an offer is being accepted and the payment method is the chain native token.
          error PaymentProcessor__BadPaymentMethod();
          /// @dev Thrown when adding or removing a payment method from a whitelist that the caller does not own.
          error PaymentProcessor__CallerDoesNotOwnPaymentMethodWhitelist();
          /**
           * @dev Thrown when modifying collection payment settings, pricing bounds, or trusted channels on a collection
           * @dev that the caller is not the owner of or a member of the default admin role for.
           */
          error PaymentProcessor__CallerMustHaveElevatedPermissionsForSpecifiedNFT();
          /// @dev Thrown when setting a collection or token pricing constraint with a floor price greater than ceiling price.
          error PaymentProcessor__CeilingPriceMustBeGreaterThanFloorPrice();
          /// @dev Thrown when adding a trusted channel that is not a trusted forwarder deployed by the trusted forwarder factory.
          error PaymentProcessor__ChannelIsNotTrustedForwarder();
          /// @dev Thrown when removing a payment method from a whitelist when that payment method is not on the whitelist.
          error PaymentProcessor__CoinIsNotApproved();
          /// @dev Thrown when the current block time is greater than the expiration time for the cosignature.
          error PaymentProcessor__CosignatureHasExpired();
          /// @dev Thrown when the cosigner has self destructed.
          error PaymentProcessor__CosignerHasSelfDestructed();
          /// @dev Thrown when a token failed to transfer to the beneficiary and partial fills are disabled.
          error PaymentProcessor__DispensingTokenWasUnsuccessful();
          /// @dev Thrown when a maker is a contract and the contract does not return the correct EIP1271 response to validate the signature.
          error PaymentProcessor__EIP1271SignatureInvalid();
          /// @dev Thrown when a native token transfer call fails to transfer the tokens.
          error PaymentProcessor__FailedToTransferProceeds();
          /// @dev Thrown when the additional fee on top exceeds the item price.
          error PaymentProcessor__FeeOnTopCannotBeGreaterThanItemPrice();
          /// @dev Thrown when the supplied root hash, token and proof do not match.
          error PaymentProcessor__IncorrectTokenSetMerkleProof();
          /// @dev Thrown when an input array has zero items in a location where it must have items.
          error PaymentProcessor__InputArrayLengthCannotBeZero();
          /// @dev Thrown when multiple input arrays have different lengths but are required to be the same length.
          error PaymentProcessor__InputArrayLengthMismatch();
          /// @dev Thrown when Payment Processor or a module is being deployed with invalid constructor arguments.
          error PaymentProcessor__InvalidConstructorArguments();
          /// @dev Thrown when the maker or taker is a banned account on the collection being traded.
          error PaymentProcessor__MakerOrTakerIsBannedAccount();
          /// @dev Thrown when the combined marketplace and royalty fees will exceed the item price.
          error PaymentProcessor__MarketplaceAndRoyaltyFeesWillExceedSalePrice();
          /// @dev Thrown when the recovered address from a cosignature does not match the order cosigner.
          error PaymentProcessor__NotAuthorizedByCosigner();
          /// @dev Thrown when the ERC2981 or backfilled royalties exceed the maximum fee specified by the order maker.
          error PaymentProcessor__OnchainRoyaltiesExceedMaximumApprovedRoyaltyFee();
          /// @dev Thrown when the current block timestamp is greater than the order expiration time.
          error PaymentProcessor__OrderHasExpired();
          /// @dev Thrown when attempting to fill a partially fillable order that has already been filled or cancelled.
          error PaymentProcessor__OrderIsEitherCancelledOrFilled();
          /// @dev Thrown when attempting to execute a sweep order for partially fillable orders.
          error PaymentProcessor__OrderProtocolERC1155FillPartialUnsupportedInSweeps();
          /// @dev Thrown when attempting to partially fill an order where the item price is not equally divisible by the amount of tokens.
          error PaymentProcessor__PartialFillsNotSupportedForNonDivisibleItems();
          /// @dev Thrown when attempting to execute an order with a payment method that is not allowed by the collection payment settings.
          error PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
          /// @dev Thrown when adding a payment method to a whitelist when that payment method is already on the list.
          error PaymentProcessor__PaymentMethodIsAlreadyApproved();
          /// @dev Thrown when setting collection payment settings with a whitelist id that does not exist.
          error PaymentProcessor__PaymentMethodWhitelistDoesNotExist();
          /// @dev Thrown when attempting to transfer ownership of a payment method whitelist to the zero address.
          error PaymentProcessor__PaymentMethodWhitelistOwnershipCannotBeTransferredToZeroAddress();
          /// @dev Thrown when distributing payments and fees in native token and the amount remaining is less than the amount to distribute.
          error PaymentProcessor__RanOutOfNativeFunds();
          /// @dev Thrown when attempting to set a royalty backfill numerator that would result in royalties greater than 100%.
          error PaymentProcessor__RoyaltyBackfillNumeratorCannotExceedFeeDenominator();
          /// @dev Thrown when attempting to set a royalty bounty numerator that would result in royalty bounties greater than 100%.
          error PaymentProcessor__RoyaltyBountyNumeratorCannotExceedFeeDenominator();
          /// @dev Thrown when a collection is set to pricing constraints and the item price exceeds the defined maximum price.
          error PaymentProcessor__SalePriceAboveMaximumCeiling();
          /// @dev Thrown when a collection is set to pricing constraints and the item price is below the defined minimum price.
          error PaymentProcessor__SalePriceBelowMinimumFloor();
          /// @dev Thrown when a maker's nonce has already been used for an executed order or cancelled by the maker.
          error PaymentProcessor__SignatureAlreadyUsedOrRevoked();
          /**
           * @dev Thrown when a collection is set to block untrusted channels and the order execution originates from a channel 
           * @dev that is not in the collection's trusted channel list.
           */ 
          error PaymentProcessor__TradeOriginatedFromUntrustedChannel();
          /// @dev Thrown when a trading of a specific collection has been paused by the collection owner or admin.
          error PaymentProcessor__TradingIsPausedForCollection();
          /**
           * @dev Thrown when attempting to fill a partially fillable order and the amount available to fill 
           * @dev is less than the specified minimum to fill.
           */
          error PaymentProcessor__UnableToFillMinimumRequestedQuantity();
          /// @dev Thrown when the recovered signer for an order does not match the order maker.
          error PaymentProcessor__UnauthorizedOrder();
          /// @dev Thrown when the taker on a cosigned order does not match the taker on the cosignature.
          error PaymentProcessor__UnauthorizedTaker();
          /// @dev Thrown when the Payment Processor or a module is being deployed with uninitialized configuration values.
          error PaymentProcessor__UninitializedConfiguration();// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "../DataTypes.sol";
          /** 
          * @title PaymentProcessor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          interface IPaymentProcessorConfiguration {
              /**
               * @notice Returns the ERC2771 context setup params for payment processor modules.
               */
              function getPaymentProcessorModuleERC2771ContextParams() 
                  external 
                  view 
                  returns (
                      address /*trustedForwarderFactory*/
                  );
              /**
               * @notice Returns the setup params for payment processor modules.
               */
              function getPaymentProcessorModuleDeploymentParams() 
                  external 
                  view 
                  returns (
                      uint32, /*defaultPushPaymentGasLimit*/
                      address, /*wrappedNativeCoin*/
                      DefaultPaymentMethods memory /*defaultPaymentMethods*/
                  );
              /**
               * @notice Returns the setup params for payment processor.
               */
              function getPaymentProcessorDeploymentParams()
                  external
                  view
                  returns (
                      address, /*defaultContractOwner*/
                      PaymentProcessorModules memory /*paymentProcessorModules*/
                  );
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "../DataTypes.sol";
          /** 
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          interface IPaymentProcessorEvents {
              /// @notice Emitted when an account is banned from trading a collection
              event BannedAccountAddedForCollection(
                  address indexed tokenAddress, 
                  address indexed account);
              /// @notice Emitted when an account ban has been lifted on a collection
              event BannedAccountRemovedForCollection(
                  address indexed tokenAddress, 
                  address indexed account);
              /// @notice Emitted when an ERC721 listing is purchased.
              event BuyListingERC721(
                  address indexed buyer,
                  address indexed seller,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 salePrice);
              /// @notice Emitted when an ERC1155 listing is purchased.
              event BuyListingERC1155(
                  address indexed buyer,
                  address indexed seller,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 amount,
                  uint256 salePrice);
              /// @notice Emitted when an ERC721 offer is accepted.
              event AcceptOfferERC721(
                  address indexed seller,
                  address indexed buyer,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 salePrice);
              /// @notice Emitted when an ERC1155 offer is accepted.
              event AcceptOfferERC1155(
                  address indexed seller,
                  address indexed buyer,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 amount,
                  uint256 salePrice);
              /// @notice Emitted when a new payment method whitelist is created.
              event CreatedPaymentMethodWhitelist(
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed whitelistOwner,
                  string whitelistName);
              /// @notice Emitted when a cosigner destroys itself.
              event DestroyedCosigner(address indexed cosigner);
              /// @notice Emitted when a user revokes all of their existing listings or offers that share the master nonce.
              event MasterNonceInvalidated(address indexed account, uint256 nonce);
              /// @notice Emitted when a user revokes a single listing or offer nonce for a specific marketplace.
              event NonceInvalidated(
                  uint256 indexed nonce, 
                  address indexed account, 
                  bool wasCancellation);
              /// @notice Emitted when a user revokes a single listing or offer nonce for a specific marketplace.
              event OrderDigestInvalidated(
                  bytes32 indexed orderDigest, 
                  address indexed account, 
                  bool wasCancellation);
              /// @notice Emitted when a coin is added to the approved coins mapping for a security policy
              event PaymentMethodAddedToWhitelist(
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed paymentMethod);
              /// @notice Emitted when a coin is removed from the approved coins mapping for a security policy
              event PaymentMethodRemovedFromWhitelist(
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed paymentMethod);
              /// @notice Emitted when a payment method whitelist is reassigned to a new owner
              event ReassignedPaymentMethodWhitelistOwnership(uint32 indexed id, address indexed newOwner);
              /// @notice Emitted when a trusted channel is added for a collection
              event TrustedChannelAddedForCollection(
                  address indexed tokenAddress, 
                  address indexed channel);
              /// @notice Emitted when a trusted channel is removed for a collection
              event TrustedChannelRemovedForCollection(
                  address indexed tokenAddress, 
                  address indexed channel);
              /// @notice Emitted whenever pricing bounds change at a collection level for price-constrained collections.
              event UpdatedCollectionLevelPricingBoundaries(
                  address indexed tokenAddress, 
                  uint256 floorPrice, 
                  uint256 ceilingPrice);
              /// @notice Emitted whenever the supported ERC-20 payment is set for price-constrained collections.
              event UpdatedCollectionPaymentSettings(
                  address indexed tokenAddress, 
                  PaymentSettings paymentSettings, 
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed constrainedPricingPaymentMethod,
                  uint16 royaltyBackfillNumerator,
                  address royaltyBackfillReceiver,
                  uint16 royaltyBountyNumerator,
                  address exclusiveBountyReceiver,
                  bool blockTradesFromUntrustedChannels,
                  bool blockBannedAccounts);
              /// @notice Emitted whenever pricing bounds change at a token level for price-constrained collections.
              event UpdatedTokenLevelPricingBoundaries(
                  address indexed tokenAddress, 
                  uint256 indexed tokenId, 
                  uint256 floorPrice, 
                  uint256 ceilingPrice);
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          /** 
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          interface IModuleDefaultPaymentMethods {
              /**
               * @notice Returns the list of default payment methods that Payment Processor supports.
               */
              function getDefaultPaymentMethods() external view returns (address[] memory);
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "../DataTypes.sol";
          /** 
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          contract PaymentProcessorStorageAccess {
              /// @dev The base storage slot for Payment Processor contract storage items.
              bytes32 constant DIAMOND_STORAGE_PAYMENT_PROCESSOR = 
                  keccak256("diamond.storage.payment.processor");
              /**
               * @dev Returns a storage object that follows the Diamond standard storage pattern for
               * @dev contract storage across multiple module contracts.
               */
              function appStorage() internal pure returns (PaymentProcessorStorage storage diamondStorage) {
                  bytes32 slot = DIAMOND_STORAGE_PAYMENT_PROCESSOR;
                  assembly {
                      diamondStorage.slot := slot
                  }
              }
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/draft-EIP712.sol)
          pragma solidity ^0.8.0;
          // EIP-712 is Final as of 2022-08-11. This file is deprecated.
          import "./EIP712.sol";
          // SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
          /**
           * @dev Used internally to indicate which side of the order the taker is on.
           */
          enum Sides { 
              // 0: Taker is on buy side of order.
              Buy, 
              // 1: Taker is on sell side of order.
              Sell 
          }
          /**
           * @dev Defines condition to apply to order execution.
           */
          enum OrderProtocols { 
              // 0: ERC721 order that must execute in full or not at all.
              ERC721_FILL_OR_KILL,
              // 1: ERC1155 order that must execute in full or not at all.
              ERC1155_FILL_OR_KILL,
              // 2: ERC1155 order that may be partially executed.
              ERC1155_FILL_PARTIAL
          }
          /**
           * @dev Defines the rules applied to a collection for payments.
           */
          enum PaymentSettings { 
              // 0: Utilize Payment Processor default whitelist.
              DefaultPaymentMethodWhitelist,
              // 1: Allow any payment method.
              AllowAnyPaymentMethod,
              // 2: Use a custom payment method whitelist.
              CustomPaymentMethodWhitelist,
              // 3: Single payment method with floor and ceiling limits.
              PricingConstraints,
              // 4: Pauses trading for the collection.
              Paused
          }
          /**
           * @dev This struct is used internally for the deployment of the Payment Processor contract and 
           * @dev module deployments to define the default payment method whitelist.
           */
          struct DefaultPaymentMethods {
              address defaultPaymentMethod1;
              address defaultPaymentMethod2;
              address defaultPaymentMethod3;
              address defaultPaymentMethod4;
          }
          /**
           * @dev This struct is used internally for the deployment of the Payment Processor contract to define the
           * @dev module addresses to be used for the contract.
           */
          struct PaymentProcessorModules {
              address modulePaymentSettings;
              address moduleOnChainCancellation;
              address moduleTrades;
              address moduleTradesAdvanced;
          }
          /**
           * @dev This struct defines the payment settings parameters for a collection.
           *
           * @dev **paymentSettings**: The general rule definition for payment methods allowed.
           * @dev **paymentMethodWhitelistId**: The list id to be used when paymentSettings is set to CustomPaymentMethodWhitelist.
           * @dev **constraintedPricingPaymentMethod**: The payment method to be used when paymentSettings is set to PricingConstraints.
           * @dev **royaltyBackfillNumerator**: The royalty fee to apply to the collection when ERC2981 is not supported.
           * @dev **royaltyBountyNumerator**: The percentage of royalties the creator will grant to a marketplace for order fulfillment.
           * @dev **isRoyaltyBountyExclusive**: If true, royalty bounties will only be paid if the order marketplace is the set exclusive marketplace.
           * @dev **blockTradesFromUntrustedChannels**: If true, trades that originate from untrusted channels will not be executed.
           * @dev **blockBannedAccounts**: If true, banned accounts can be neither maker or taker for trades on a per-collection basis.
           */
          struct CollectionPaymentSettings {
              PaymentSettings paymentSettings;
              uint32 paymentMethodWhitelistId;
              address constrainedPricingPaymentMethod;
              uint16 royaltyBackfillNumerator;
              uint16 royaltyBountyNumerator;
              bool isRoyaltyBountyExclusive;
              bool blockTradesFromUntrustedChannels;
              bool blockBannedAccounts;
          }
          /**
           * @dev The `v`, `r`, and `s` components of an ECDSA signature.  For more information
           *      [refer to this article](https://medium.com/mycrypto/the-magic-of-digital-signatures-on-ethereum-98fe184dc9c7).
           */
          struct SignatureECDSA {
              uint8 v;
              bytes32 r;
              bytes32 s;
          }
          /**
           * @dev This struct defines order execution parameters.
           * 
           * @dev **protocol**: The order protocol to apply to the order.
           * @dev **maker**: The user that created and signed the order to be executed by a taker.
           * @dev **beneficiary**: The account that will receive the tokens.
           * @dev **marketplace**: The fee receiver of the marketplace that the order was created on.
           * @dev **fallbackRoyaltyRecipient**: The address that will receive royalties if ERC2981 
           * @dev is not supported by the collection and the creator has not defined backfilled royalties with Payment Processor.
           * @dev **paymentMethod**: The payment method for the order.
           * @dev **tokenAddress**: The address of the token collection the order is for.
           * @dev **tokenId**: The token id that the order is for.
           * @dev **amount**: The quantity of token the order is for.
           * @dev **itemPrice**: The price for the order in base units for the payment method.
           * @dev **nonce**: The maker's nonce for the order.
           * @dev **expiration**: The time, in seconds since the Unix epoch, that the order will expire.
           * @dev **marketplaceFeeNumerator**: The percentage fee that will be sent to the marketplace.
           * @dev **maxRoyaltyFeeNumerator**: The maximum royalty the maker is willing to accept. This will be used
           * @dev as the royalty amount when ERC2981 is not supported by the collection.
           * @dev **requestedFillAmount**: The amount of tokens for an ERC1155 partial fill order that the taker wants to fill.
           * @dev **minimumFillAmount**: The minimum amount of tokens for an ERC1155 partial fill order that the taker will accept.
           */
          struct Order {
              OrderProtocols protocol;
              address maker;
              address beneficiary;
              address marketplace;
              address fallbackRoyaltyRecipient;
              address paymentMethod;
              address tokenAddress;
              uint256 tokenId;
              uint248 amount;
              uint256 itemPrice;
              uint256 nonce;
              uint256 expiration;
              uint256 marketplaceFeeNumerator;
              uint256 maxRoyaltyFeeNumerator;
              uint248 requestedFillAmount;
              uint248 minimumFillAmount;
          }
          /**
           * @dev This struct defines the cosignature for verifying an order that is a cosigned order.
           *
           * @dev **signer**: The address that signed the cosigned order. This must match the cosigner that is part of the order signature.
           * @dev **taker**: The address of the order taker.
           * @dev **expiration**: The time, in seconds since the Unix epoch, that the cosignature will expire.
           * @dev The `v`, `r`, and `s` components of an ECDSA signature.  For more information
           *      [refer to this article](https://medium.com/mycrypto/the-magic-of-digital-signatures-on-ethereum-98fe184dc9c7).
           */
          struct Cosignature {
              address signer;
              address taker;
              uint256 expiration;
              uint8 v;
              bytes32 r;
              bytes32 s;
          }
          /**
           * @dev This struct defines an additional fee on top of an order, paid by taker.
           *
           * @dev **recipient**: The recipient of the additional fee.
           * @dev **amount**: The amount of the additional fee, in base units of the payment token.
           */
          struct FeeOnTop {
              address recipient;
              uint256 amount;
          }
          /**
           * @dev This struct defines the root hash and proof data for accepting an offer that is for a subset
           * @dev of items in a collection. The root hash must match the root hash specified as part of the 
           * @dev maker's order signature.
           * 
           * @dev **rootHash**: The merkletree root hash for the items that may be used to fulfill the offer order.
           * @dev **proof**: The merkle proofs for the item being supplied to fulfill the offer order.
           */
          struct TokenSetProof {
              bytes32 rootHash;
              bytes32[] proof;
          }
          /**
           * @dev Current state of a partially fillable order.
           */
          enum PartiallyFillableOrderState { 
              // 0: Order is open and may continue to be filled.
              Open, 
              // 1: Order has been completely filled.
              Filled, 
              // 2: Order has been cancelled.
              Cancelled
          }
          /**
           * @dev This struct defines the current status of a partially fillable order.
           * 
           * @dev **state**: The current state of the order as defined by the PartiallyFillableOrderState enum.
           * @dev **remainingFillableQuantity**: The remaining quantity that may be filled for the order.
           */
          struct PartiallyFillableOrderStatus {
              PartiallyFillableOrderState state;
              uint248 remainingFillableQuantity;
          }
          /**
           * @dev This struct defines the royalty backfill and bounty information. Its data for an
           * @dev order execution is constructed internally based on the collection settings and
           * @dev order execution details.
           * 
           * @dev **backfillNumerator**: The percentage of the order amount to pay as royalties
           * @dev for a collection that does not support ERC2981.
           * @dev **backfillReceiver**: The recipient of backfill royalties.
           * @dev **bountyNumerator**: The percentage of royalties to share with the marketplace for order fulfillment.
           * @dev **exclusiveMarketplace**: If non-zero, the address of the exclusive marketplace for royalty bounties.
           */
          struct RoyaltyBackfillAndBounty {
              uint16 backfillNumerator;
              address backfillReceiver;
              uint16 bountyNumerator;
              address exclusiveMarketplace;
          }
          /**
           * @dev This struct defines order information that is common to all items in a sweep order.
           * 
           * @dev **protocol**: The order protocol to apply to the order.
           * @dev **tokenAddress**: The address of the token collection the order is for.
           * @dev **paymentMethod**: The payment method for the order.
           * @dev **beneficiary**: The account that will receive the tokens.
           */
          struct SweepOrder {
              OrderProtocols protocol;
              address tokenAddress;
              address paymentMethod;
              address beneficiary;
          }
          /**
           * @dev This struct defines order information that is unique to each item of a sweep order.
           * @dev Combined with the SweepOrder header information to make an Order to execute.
           * 
           * @dev **maker**: The user that created and signed the order to be executed by a taker.
           * @dev **marketplace**: The marketplace that the order was created on.
           * @dev **fallbackRoyaltyRecipient**: The address that will receive royalties if ERC2981 
           * @dev is not supported by the collection and the creator has not defined royalties with Payment Processor.
           * @dev **tokenId**: The token id that the order is for.
           * @dev **amount**: The quantity of token the order is for.
           * @dev **itemPrice**: The price for the order in base units for the payment method.
           * @dev **nonce**: The maker's nonce for the order.
           * @dev **expiration**: The time, in seconds since the Unix epoch, that the order will expire.
           * @dev **marketplaceFeeNumerator**: The percentage fee that will be sent to the marketplace.
           * @dev **maxRoyaltyFeeNumerator**: The maximum royalty the maker is willing to accept. This will be used
           * @dev as the royalty amount when ERC2981 is not supported by the collection.
           */
          struct SweepItem {
              address maker;
              address marketplace;
              address fallbackRoyaltyRecipient;
              uint256 tokenId;
              uint248 amount;
              uint256 itemPrice;
              uint256 nonce;
              uint256 expiration;
              uint256 marketplaceFeeNumerator;
              uint256 maxRoyaltyFeeNumerator;
          }
          /**
           * @dev This struct is used to define pricing constraints for a collection or individual token.
           *
           * @dev **isSet**: When true, this indicates that pricing constraints are set for the collection or token.
           * @dev **floorPrice**: The minimum price for a token or collection.  This is only enforced when 
           * @dev `enforcePricingConstraints` is `true`.
           * @dev **ceilingPrice**: The maximum price for a token or collection.  This is only enforced when
           * @dev `enforcePricingConstraints` is `true`.
           */
          struct PricingBounds {
              bool isSet;
              uint120 floorPrice;
              uint120 ceilingPrice;
          }
          /**
           * @dev This struct defines the parameters for a bulk offer acceptance transaction.
           * 
           * 
           * @dev **isCollectionLevelOfferArray**: An array of flags to indicate if an offer is for any token in the collection.
           * @dev **saleDetailsArray**: An array of order execution details.
           * @dev **buyerSignaturesArray**: An array of maker signatures authorizing the order executions.
           * @dev **tokenSetProofsArray**: An array of root hashes and merkle proofs for offers that are a subset of tokens in a collection.
           * @dev **cosignaturesArray**: An array of additional cosignatures for cosigned orders, as applicable.
           * @dev **feesOnTopArray**: An array of additional fees to add on top of the orders, paid by taker.
           */
          struct BulkAcceptOffersParams {
              bool[] isCollectionLevelOfferArray;
              Order[] saleDetailsArray;
              SignatureECDSA[] buyerSignaturesArray;
              TokenSetProof[] tokenSetProofsArray;
              Cosignature[] cosignaturesArray;
              FeeOnTop[] feesOnTopArray;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
          struct SplitProceeds {
              address royaltyRecipient;
              uint256 royaltyProceeds;
              uint256 marketplaceProceeds;
              uint256 sellerProceeds;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
          struct PayoutsAccumulator {
              address lastSeller;
              address lastMarketplace;
              address lastRoyaltyRecipient;
              uint256 accumulatedSellerProceeds;
              uint256 accumulatedMarketplaceProceeds;
              uint256 accumulatedRoyaltyProceeds;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
          struct SweepCollectionComputeAndDistributeProceedsParams {
              IERC20 paymentCoin;
              FulfillOrderFunctionPointers fnPointers;
              FeeOnTop feeOnTop;
              RoyaltyBackfillAndBounty royaltyBackfillAndBounty;
              Order[] saleDetailsBatch;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
           struct FulfillOrderFunctionPointers {
              function(address,address,IERC20,uint256,uint256) funcPayout;
              function(address,address,address,uint256,uint256) returns (bool) funcDispenseToken;
              function(TradeContext memory, Order memory) funcEmitOrderExecutionEvent;
           }
           /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
           struct TradeContext {
              bytes32 domainSeparator;
              address channel;
              address taker;
              bool disablePartialFill;
           }
          /**
           * @dev This struct defines contract-level storage to be used across all Payment Processor modules.
           * @dev Follows the Diamond storage pattern.
           */
          struct PaymentProcessorStorage {
              /// @dev Tracks the most recently created payment method whitelist id
              uint32 lastPaymentMethodWhitelistId;
              /**
               * @notice User-specific master nonce that allows buyers and sellers to efficiently cancel all listings or offers
               *         they made previously. The master nonce for a user only changes when they explicitly request to revoke all
               *         existing listings and offers.
               *
               * @dev    When prompting sellers to sign a listing or offer, marketplaces must query the current master nonce of
               *         the user and include it in the listing/offer signature data.
               */
              mapping(address => uint256) masterNonces;
              /**
               * @dev The mapping key is the keccak256 hash of marketplace address and user address.
               *
               * @dev ```keccak256(abi.encodePacked(marketplace, user))```
               *
               * @dev The mapping value is another nested mapping of "slot" (key) to a bitmap (value) containing boolean flags
               *      indicating whether or not a nonce has been used or invalidated.
               *
               * @dev Marketplaces MUST track their own nonce by user, incrementing it for every signed listing or offer the user
               *      creates.  Listings and purchases may be executed out of order, and they may never be executed if orders
               *      are not matched prior to expriation.
               *
               * @dev The slot and the bit offset within the mapped value are computed as:
               *
               * @dev ```slot = nonce / 256;```
               * @dev ```offset = nonce % 256;```
               */
              mapping(address => mapping(uint256 => uint256)) invalidatedSignatures;
              
              /// @dev Mapping of token contract addresses to the collection payment settings.
              mapping (address => CollectionPaymentSettings) collectionPaymentSettings;
              /// @dev Mapping of payment method whitelist id to the owner address for the list.
              mapping (uint32 => address) paymentMethodWhitelistOwners;
              /// @dev Mapping of payment method whitelist id to a defined list of allowed payment methods.
              mapping (uint32 => EnumerableSet.AddressSet) collectionPaymentMethodWhitelists;
              /// @dev Mapping of token contract addresses to the collection-level pricing boundaries (floor and ceiling price).
              mapping (address => PricingBounds) collectionPricingBounds;
              /// @dev Mapping of token contract addresses to the token-level pricing boundaries (floor and ceiling price).
              mapping (address => mapping (uint256 => PricingBounds)) tokenPricingBounds;
              /// @dev Mapping of token contract addresses to the defined royalty backfill receiver addresses.
              mapping (address => address) collectionRoyaltyBackfillReceivers;
              /// @dev Mapping of token contract addresses to the defined exclusive bounty receivers.
              mapping (address => address) collectionExclusiveBountyReceivers;
              /// @dev Mapping of maker addresses to a mapping of order digests to the status of the partially fillable order for that digest.
              mapping (address => mapping(bytes32 => PartiallyFillableOrderStatus)) partiallyFillableOrderStatuses;
              /// @dev Mapping of token contract addresses to the defined list of trusted channels for the token contract.
              mapping (address => EnumerableSet.AddressSet) collectionTrustedChannels;
              /// @dev Mapping of token contract addresses to the defined list of banned accounts for the token contract.
              mapping (address => EnumerableSet.AddressSet) collectionBannedAccounts;
              /// @dev A mapping of all co-signers that have self-destructed and can never be used as cosigners again.
              mapping (address => bool) destroyedCosigners;
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
          pragma solidity ^0.8.8;
          import "./ECDSA.sol";
          import "../ShortStrings.sol";
          import "../../interfaces/IERC5267.sol";
          /**
           * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
           *
           * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
           * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
           * they need in their contracts using a combination of `abi.encode` and `keccak256`.
           *
           * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
           * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
           * ({_hashTypedDataV4}).
           *
           * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
           * the chain id to protect against replay attacks on an eventual fork of the chain.
           *
           * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
           * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
           *
           * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
           * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
           * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
           *
           * _Available since v3.4._
           *
           * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
           */
          abstract contract EIP712 is IERC5267 {
              using ShortStrings for *;
              bytes32 private constant _TYPE_HASH =
                  keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
              // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
              // invalidate the cached domain separator if the chain id changes.
              bytes32 private immutable _cachedDomainSeparator;
              uint256 private immutable _cachedChainId;
              address private immutable _cachedThis;
              bytes32 private immutable _hashedName;
              bytes32 private immutable _hashedVersion;
              ShortString private immutable _name;
              ShortString private immutable _version;
              string private _nameFallback;
              string private _versionFallback;
              /**
               * @dev Initializes the domain separator and parameter caches.
               *
               * The meaning of `name` and `version` is specified in
               * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
               *
               * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
               * - `version`: the current major version of the signing domain.
               *
               * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
               * contract upgrade].
               */
              constructor(string memory name, string memory version) {
                  _name = name.toShortStringWithFallback(_nameFallback);
                  _version = version.toShortStringWithFallback(_versionFallback);
                  _hashedName = keccak256(bytes(name));
                  _hashedVersion = keccak256(bytes(version));
                  _cachedChainId = block.chainid;
                  _cachedDomainSeparator = _buildDomainSeparator();
                  _cachedThis = address(this);
              }
              /**
               * @dev Returns the domain separator for the current chain.
               */
              function _domainSeparatorV4() internal view returns (bytes32) {
                  if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
                      return _cachedDomainSeparator;
                  } else {
                      return _buildDomainSeparator();
                  }
              }
              function _buildDomainSeparator() private view returns (bytes32) {
                  return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
              }
              /**
               * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
               * function returns the hash of the fully encoded EIP712 message for this domain.
               *
               * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
               *
               * ```solidity
               * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
               *     keccak256("Mail(address to,string contents)"),
               *     mailTo,
               *     keccak256(bytes(mailContents))
               * )));
               * address signer = ECDSA.recover(digest, signature);
               * ```
               */
              function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                  return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
              }
              /**
               * @dev See {EIP-5267}.
               *
               * _Available since v4.9._
               */
              function eip712Domain()
                  public
                  view
                  virtual
                  override
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  )
              {
                  return (
                      hex"0f", // 01111
                      _name.toStringWithFallback(_nameFallback),
                      _version.toStringWithFallback(_versionFallback),
                      block.chainid,
                      address(this),
                      bytes32(0),
                      new uint256[](0)
                  );
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20 {
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
              /**
               * @dev Moves `amount` tokens from the caller's account to `to`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address to, uint256 amount) external returns (bool);
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
              /**
               * @dev Moves `amount` tokens from `from` to `to` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(address from, address to, uint256 amount) external returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
          // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```solidity
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           *
           * [WARNING]
           * ====
           * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
           * unusable.
           * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
           *
           * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
           * array of EnumerableSet.
           * ====
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastValue = set._values[lastIndex];
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastValue;
                          // Update the index for the moved value
                          set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                      }
                      // Delete the slot where the moved value was stored
                      set._values.pop();
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
              // Bytes32Set
              struct Bytes32Set {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  bytes32[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // AddressSet
              struct AddressSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // UintSet
              struct UintSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
          pragma solidity ^0.8.0;
          import "../Strings.sol";
          /**
           * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
           *
           * These functions can be used to verify that a message was signed by the holder
           * of the private keys of a given address.
           */
          library ECDSA {
              enum RecoverError {
                  NoError,
                  InvalidSignature,
                  InvalidSignatureLength,
                  InvalidSignatureS,
                  InvalidSignatureV // Deprecated in v4.8
              }
              function _throwError(RecoverError error) private pure {
                  if (error == RecoverError.NoError) {
                      return; // no error: do nothing
                  } else if (error == RecoverError.InvalidSignature) {
                      revert("ECDSA: invalid signature");
                  } else if (error == RecoverError.InvalidSignatureLength) {
                      revert("ECDSA: invalid signature length");
                  } else if (error == RecoverError.InvalidSignatureS) {
                      revert("ECDSA: invalid signature 's' value");
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature` or error string. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               *
               * Documentation for signature generation:
               * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
               * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
                  if (signature.length == 65) {
                      bytes32 r;
                      bytes32 s;
                      uint8 v;
                      // ecrecover takes the signature parameters, and the only way to get them
                      // currently is to use assembly.
                      /// @solidity memory-safe-assembly
                      assembly {
                          r := mload(add(signature, 0x20))
                          s := mload(add(signature, 0x40))
                          v := byte(0, mload(add(signature, 0x60)))
                      }
                      return tryRecover(hash, v, r, s);
                  } else {
                      return (address(0), RecoverError.InvalidSignatureLength);
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature`. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               */
              function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, signature);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
               *
               * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
                  bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                  uint8 v = uint8((uint256(vs) >> 255) + 27);
                  return tryRecover(hash, v, r, s);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
               *
               * _Available since v4.2._
               */
              function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, r, vs);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
               * `r` and `s` signature fields separately.
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
                  // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                  // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                  // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                  // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                  //
                  // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                  // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                  // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                  // these malleable signatures as well.
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      return (address(0), RecoverError.InvalidSignatureS);
                  }
                  // If the signature is valid (and not malleable), return the signer address
                  address signer = ecrecover(hash, v, r, s);
                  if (signer == address(0)) {
                      return (address(0), RecoverError.InvalidSignature);
                  }
                  return (signer, RecoverError.NoError);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `v`,
               * `r` and `s` signature fields separately.
               */
              function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from a `hash`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
                  // 32 is the length in bytes of hash,
                  // enforced by the type signature above
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(0x00, "\\x19Ethereum Signed Message:\
          32")
                      mstore(0x1c, hash)
                      message := keccak256(0x00, 0x3c)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from `s`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
          ", Strings.toString(s.length), s));
              }
              /**
               * @dev Returns an Ethereum Signed Typed Data, created from a
               * `domainSeparator` and a `structHash`. This produces hash corresponding
               * to the one signed with the
               * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
               * JSON-RPC method as part of EIP-712.
               *
               * See {recover}.
               */
              function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      let ptr := mload(0x40)
                      mstore(ptr, "\\x19\\x01")
                      mstore(add(ptr, 0x02), domainSeparator)
                      mstore(add(ptr, 0x22), structHash)
                      data := keccak256(ptr, 0x42)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Data with intended validator, created from a
               * `validator` and `data` according to the version 0 of EIP-191.
               *
               * See {recover}.
               */
              function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
          pragma solidity ^0.8.8;
          import "./StorageSlot.sol";
          // | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
          // | length  | 0x                                                              BB |
          type ShortString is bytes32;
          /**
           * @dev This library provides functions to convert short memory strings
           * into a `ShortString` type that can be used as an immutable variable.
           *
           * Strings of arbitrary length can be optimized using this library if
           * they are short enough (up to 31 bytes) by packing them with their
           * length (1 byte) in a single EVM word (32 bytes). Additionally, a
           * fallback mechanism can be used for every other case.
           *
           * Usage example:
           *
           * ```solidity
           * contract Named {
           *     using ShortStrings for *;
           *
           *     ShortString private immutable _name;
           *     string private _nameFallback;
           *
           *     constructor(string memory contractName) {
           *         _name = contractName.toShortStringWithFallback(_nameFallback);
           *     }
           *
           *     function name() external view returns (string memory) {
           *         return _name.toStringWithFallback(_nameFallback);
           *     }
           * }
           * ```
           */
          library ShortStrings {
              // Used as an identifier for strings longer than 31 bytes.
              bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
              error StringTooLong(string str);
              error InvalidShortString();
              /**
               * @dev Encode a string of at most 31 chars into a `ShortString`.
               *
               * This will trigger a `StringTooLong` error is the input string is too long.
               */
              function toShortString(string memory str) internal pure returns (ShortString) {
                  bytes memory bstr = bytes(str);
                  if (bstr.length > 31) {
                      revert StringTooLong(str);
                  }
                  return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
              }
              /**
               * @dev Decode a `ShortString` back to a "normal" string.
               */
              function toString(ShortString sstr) internal pure returns (string memory) {
                  uint256 len = byteLength(sstr);
                  // using `new string(len)` would work locally but is not memory safe.
                  string memory str = new string(32);
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(str, len)
                      mstore(add(str, 0x20), sstr)
                  }
                  return str;
              }
              /**
               * @dev Return the length of a `ShortString`.
               */
              function byteLength(ShortString sstr) internal pure returns (uint256) {
                  uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
                  if (result > 31) {
                      revert InvalidShortString();
                  }
                  return result;
              }
              /**
               * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
               */
              function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
                  if (bytes(value).length < 32) {
                      return toShortString(value);
                  } else {
                      StorageSlot.getStringSlot(store).value = value;
                      return ShortString.wrap(_FALLBACK_SENTINEL);
                  }
              }
              /**
               * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               */
              function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return toString(value);
                  } else {
                      return store;
                  }
              }
              /**
               * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               *
               * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
               * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
               */
              function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return byteLength(value);
                  } else {
                      return bytes(store).length;
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
          pragma solidity ^0.8.0;
          interface IERC5267 {
              /**
               * @dev MAY be emitted to signal that the domain could have changed.
               */
              event EIP712DomainChanged();
              /**
               * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
               * signature.
               */
              function eip712Domain()
                  external
                  view
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  );
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
          pragma solidity ^0.8.0;
          import "./math/Math.sol";
          import "./math/SignedMath.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 `int256` to its ASCII `string` decimal representation.
               */
              function toString(int256 value) internal pure returns (string memory) {
                  return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  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);
              }
              /**
               * @dev Returns true if the two strings are equal.
               */
              function equal(string memory a, string memory b) internal pure returns (bool) {
                  return keccak256(bytes(a)) == keccak256(bytes(b));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
          // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for reading and writing primitive types to specific storage slots.
           *
           * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
           * This library helps with reading and writing to such slots without the need for inline assembly.
           *
           * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
           *
           * Example usage to set ERC1967 implementation slot:
           * ```solidity
           * contract ERC1967 {
           *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
           *
           *     function _getImplementation() internal view returns (address) {
           *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
           *     }
           *
           *     function _setImplementation(address newImplementation) internal {
           *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
           *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
           *     }
           * }
           * ```
           *
           * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
           * _Available since v4.9 for `string`, `bytes`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
              struct BooleanSlot {
                  bool value;
              }
              struct Bytes32Slot {
                  bytes32 value;
              }
              struct Uint256Slot {
                  uint256 value;
              }
              struct StringSlot {
                  string value;
              }
              struct BytesSlot {
                  bytes value;
              }
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
               */
              function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
               */
              function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
               */
              function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` with member `value` located at `slot`.
               */
              function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
               */
              function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` with member `value` located at `slot`.
               */
              function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
               */
              function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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) {
                          // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                          // The surrounding unchecked block does not change this fact.
                          // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1, "Math: mulDiv overflow");
                      ///////////////////////////////////////////////
                      // 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 256, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard signed math utilities missing in the Solidity language.
           */
          library SignedMath {
              /**
               * @dev Returns the largest of two signed numbers.
               */
              function max(int256 a, int256 b) internal pure returns (int256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two signed numbers.
               */
              function min(int256 a, int256 b) internal pure returns (int256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two signed numbers without overflow.
               * The result is rounded towards zero.
               */
              function average(int256 a, int256 b) internal pure returns (int256) {
                  // Formula from the book "Hacker's Delight"
                  int256 x = (a & b) + ((a ^ b) >> 1);
                  return x + (int256(uint256(x) >> 255) & (a ^ b));
              }
              /**
               * @dev Returns the absolute unsigned value of a signed value.
               */
              function abs(int256 n) internal pure returns (uint256) {
                  unchecked {
                      // must be unchecked in order to support `n = type(int256).min`
                      return uint256(n >= 0 ? n : -n);
                  }
              }
          }
          

          File 3 of 7: ProbablyNothing
          {"Address.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size \u003e 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity\u0027s `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance \u003e= amount, \"Address: insufficient balance\");\n\n        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n        (bool success, ) = recipient.call{ value: amount }(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain`call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n      return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n        require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.call{ value: value }(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length \u003e 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\n \nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n        return msg.data;\n    }\n}\n"},"ERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}"},"ERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./IERC721Metadata.sol\";\nimport \"./Address.sol\";\nimport \"./Context.sol\";\nimport \"./Strings.sol\";\nimport \"./ERC165.sol\";\nimport \"./Ownable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n    using Address for address;\n    using Strings for uint256;\n\n    // Token name\n    string private _name;\n\n    // Token symbol\n    string private _symbol;\n\n    // Mapping from token ID to owner address\n    mapping(uint256 =\u003e address) private _owners;\n\n    // Mapping owner address to token count\n    mapping(address =\u003e uint256) private _balances;\n\n    // Mapping from token ID to approved address\n    mapping(uint256 =\u003e address) private _tokenApprovals;\n\n    // Mapping from owner to operator approvals\n    mapping(address =\u003e mapping(address =\u003e bool)) private _operatorApprovals;\n\n    /**\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC721).interfaceId ||\n            interfaceId == type(IERC721Metadata).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721-balanceOf}.\n     */\n    function balanceOf(address owner) public view virtual override returns (uint256) {\n        require(owner != address(0), \"ERC721: balance query for the zero address\");\n        return _balances[owner];\n    }\n\n    /**\n     * @dev See {IERC721-ownerOf}.\n     */\n    function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n        address owner = _owners[tokenId];\n        require(owner != address(0), \"ERC721: owner query for nonexistent token\");\n        return owner;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-name}.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-symbol}.\n     */\n    function symbol() public view virtual override returns (string memory) {\n        return _symbol;\n    }\n\n\n\n    /**\n     * @dev See {IERC721Metadata-tokenURI}.\n     */\n    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n        require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length \u003e 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n    }\n\n    /**\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n     * by default, can be overriden in child contracts.\n     */\n    string URI;\n    function _baseURI() internal view virtual returns (string memory) {\n        return URI;\n    }\n\n    /**\n     * @dev See {IERC721-approve}.\n     */\n    function approve(address to, uint256 tokenId) public virtual override {\n        address owner = ERC721.ownerOf(tokenId);\n        require(to != owner, \"ERC721: approval to current owner\");\n\n        require(\n            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n            \"ERC721: approve caller is not owner nor approved for all\"\n        );\n\n        _approve(to, tokenId);\n    }\n\n    /**\n     * @dev See {IERC721-getApproved}.\n     */\n    function getApproved(uint256 tokenId) public view virtual override returns (address) {\n        require(_exists(tokenId), \"ERC721: approved query for nonexistent token\");\n\n        return _tokenApprovals[tokenId];\n    }\n\n    /**\n     * @dev See {IERC721-setApprovalForAll}.\n     */\n    function setApprovalForAll(address operator, bool approved) public virtual override {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /**\n     * @dev See {IERC721-isApprovedForAll}.\n     */\n    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n        return _operatorApprovals[owner][operator];\n    }\n\n    /**\n     * @dev See {IERC721-transferFrom}.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) public virtual override {\n        //solhint-disable-next-line max-line-length\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\n\n        _transfer(from, to, tokenId);\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) public virtual override {\n        safeTransferFrom(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory _data\n    ) public virtual override {\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\n        _safeTransfer(from, to, tokenId, _data);\n    }\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * `_data` is additional data, it has no specified format and it is sent in call to `to`.\n     *\n     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeTransfer(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory _data\n    ) internal virtual {\n        _transfer(from, to, tokenId);\n        require(_checkOnERC721Received(from, to, tokenId, _data), \"ERC721: transfer to non ERC721Receiver implementer\");\n    }\n\n    /**\n     * @dev Returns whether `tokenId` exists.\n     *\n     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n     *\n     * Tokens start existing when they are minted (`_mint`),\n     * and stop existing when they are burned (`_burn`).\n     */\n    function _exists(uint256 tokenId) internal view virtual returns (bool) {\n        return _owners[tokenId] != address(0);\n    }\n\n    /**\n     * @dev Returns whether `spender` is allowed to manage `tokenId`.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n        require(_exists(tokenId), \"ERC721: operator query for nonexistent token\");\n        address owner = ERC721.ownerOf(tokenId);\n        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));\n    }\n\n    /**\n     * @dev Safely mints `tokenId` and transfers it to `to`.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeMint(address to, uint256 tokenId) internal virtual {\n        _safeMint(to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeMint(\n        address to,\n        uint256 tokenId,\n        bytes memory _data\n    ) internal virtual {\n        _mint(to, tokenId);\n        require(\n            _checkOnERC721Received(address(0), to, tokenId, _data),\n            \"ERC721: transfer to non ERC721Receiver implementer\"\n        );\n    }\n\n    /**\n     * @dev Mints `tokenId` and transfers it to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - `to` cannot be the zero address.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _mint(address to, uint256 tokenId) internal virtual {\n        require(to != address(0), \"ERC721: mint to the zero address\");\n        require(!_exists(tokenId), \"ERC721: token already minted\");\n\n        _beforeTokenTransfer(address(0), to, tokenId);\n\n        _balances[to] += 1;\n        _owners[tokenId] = to;\n\n        emit Transfer(address(0), to, tokenId);\n    }\n\n    /**\n     * @dev Destroys `tokenId`.\n     * The approval is cleared when the token is burned.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _burn(uint256 tokenId) internal virtual {\n        address owner = ERC721.ownerOf(tokenId);\n\n        _beforeTokenTransfer(owner, address(0), tokenId);\n\n        // Clear approvals\n        _approve(address(0), tokenId);\n\n        _balances[owner] -= 1;\n        delete _owners[tokenId];\n\n        emit Transfer(owner, address(0), tokenId);\n    }\n\n    /**\n     * @dev Transfers `tokenId` from `from` to `to`.\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _transfer(\n        address from,\n        address to,\n        uint256 tokenId\n    ) internal virtual {\n        require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer of token that is not own\");\n        require(to != address(0), \"ERC721: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, tokenId);\n\n        // Clear approvals from the previous owner\n        _approve(address(0), tokenId);\n\n        _balances[from] -= 1;\n        _balances[to] += 1;\n        _owners[tokenId] = to;\n\n        emit Transfer(from, to, tokenId);\n    }\n\n    /**\n     * @dev Approve `to` to operate on `tokenId`\n     *\n     * Emits a {Approval} event.\n     */\n    function _approve(address to, uint256 tokenId) internal virtual {\n        _tokenApprovals[tokenId] = to;\n        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Emits a {ApprovalForAll} event.\n     */\n    function _setApprovalForAll(\n        address owner,\n        address operator,\n        bool approved\n    ) internal virtual {\n        require(owner != operator, \"ERC721: approve to caller\");\n        _operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n     * The call is not executed if the target address is not a contract.\n     *\n     * @param from address representing the previous owner of the given token ID\n     * @param to target address that will receive the tokens\n     * @param tokenId uint256 ID of the token to be transferred\n     * @param _data bytes optional data to send along with the call\n     * @return bool whether the call correctly returned the expected magic value\n     */\n    function _checkOnERC721Received(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory _data\n    ) private returns (bool) {\n        if (to.isContract()) {\n            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {\n                return retval == IERC721Receiver.onERC721Received.selector;\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n                } else {\n                    assembly {\n                        revert(add(32, reason), mload(reason))\n                    }\n                }\n            }\n        } else {\n            return true;\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any token transfer. This includes minting\n     * and burning.\n     *\n     * Calling conditions:\n     *\n     * - When `from` and `to` are both non-zero, ``from``\u0027s `tokenId` will be\n     * transferred to `to`.\n     * - When `from` is zero, `tokenId` will be minted for `to`.\n     * - When `to` is zero, ``from``\u0027s `tokenId` will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 tokenId\n    ) internal virtual {}\n}"},"ERC721A.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./IERC721Metadata.sol\";\nimport \"./IERC721Enumerable.sol\";\nimport \"./Address.sol\";\n//import \"@openzeppelin/contracts/utils/Context.sol\";\nimport \"./Strings.sol\";\nimport \"./ERC165.sol\";\nimport \"./Ownable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.\n *\n * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).\n *\n * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.\n *\n * Does not support burning tokens to address(0).\n */\ncontract ERC721A is\n  Context,\n  ERC165,\n  IERC721,\n  IERC721Metadata,\n  IERC721Enumerable\n{\n  using Address for address;\n  using Strings for uint256;\n\n  struct TokenOwnership {\n    address addr;\n    uint64 startTimestamp;\n  }\n\n  struct AddressData {\n    uint128 balance;\n    uint128 numberMinted;\n  }\n\n  uint256 private currentIndex = 0;\n\n  uint256 internal immutable collectionSize;\n  uint256 internal immutable maxBatchSize;\n\n  // Token name\n  string private _name;\n\n  // Token symbol\n  string private _symbol;\n\n  // Mapping from token ID to ownership details\n  // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.\n  mapping(uint256 =\u003e TokenOwnership) private _ownerships;\n\n  // Mapping owner address to address data\n  mapping(address =\u003e AddressData) private _addressData;\n\n  // Mapping from token ID to approved address\n  mapping(uint256 =\u003e address) private _tokenApprovals;\n\n  // Mapping from owner to operator approvals\n  mapping(address =\u003e mapping(address =\u003e bool)) private _operatorApprovals;\n\n  /**\n   * @dev\n   * `maxBatchSize` refers to how much a minter can mint at a time.\n   * `collectionSize_` refers to how many tokens are in the collection.\n   */\n  constructor(\n    string memory name_,\n    string memory symbol_,\n    uint256 maxBatchSize_,\n    uint256 collectionSize_\n  ) {\n    require(\n      collectionSize_ \u003e 0,\n      \"ERC721A: collection must have a nonzero supply\"\n    );\n    require(maxBatchSize_ \u003e 0, \"ERC721A: max batch size must be nonzero\");\n    _name = name_;\n    _symbol = symbol_;\n    maxBatchSize = maxBatchSize_;\n    collectionSize = collectionSize_;\n  }\n\n  /**\n   * @dev See {IERC721Enumerable-totalSupply}.\n   */\n  function totalSupply() public view override returns (uint256) {\n    return currentIndex;\n  }\n\n  /**\n   * @dev See {IERC721Enumerable-tokenByIndex}.\n   */\n  function tokenByIndex(uint256 index) public view override returns (uint256) {\n    require(index \u003c totalSupply(), \"ERC721A: global index out of bounds\");\n    return index;\n  }\n\n  /**\n   * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n   * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.\n   * It may also degrade with extremely large collection sizes (e.g \u003e\u003e 10000), test for your use case.\n   */\n  function tokenOfOwnerByIndex(address owner, uint256 index)\n    public\n    view\n    override\n    returns (uint256)\n  {\n    require(index \u003c balanceOf(owner), \"ERC721A: owner index out of bounds\");\n    uint256 numMintedSoFar = totalSupply();\n    uint256 tokenIdsIdx = 0;\n    address currOwnershipAddr = address(0);\n    for (uint256 i = 0; i \u003c numMintedSoFar; i++) {\n      TokenOwnership memory ownership = _ownerships[i];\n      if (ownership.addr != address(0)) {\n        currOwnershipAddr = ownership.addr;\n      }\n      if (currOwnershipAddr == owner) {\n        if (tokenIdsIdx == index) {\n          return i;\n        }\n        tokenIdsIdx++;\n      }\n    }\n    revert(\"ERC721A: unable to get token of owner by index\");\n  }\n\n  /**\n   * @dev See {IERC165-supportsInterface}.\n   */\n  function supportsInterface(bytes4 interfaceId)\n    public\n    view\n    virtual\n    override(ERC165, IERC165)\n    returns (bool)\n  {\n    return\n      interfaceId == type(IERC721).interfaceId ||\n      interfaceId == type(IERC721Metadata).interfaceId ||\n      interfaceId == type(IERC721Enumerable).interfaceId ||\n      super.supportsInterface(interfaceId);\n  }\n\n  /**\n   * @dev See {IERC721-balanceOf}.\n   */\n  function balanceOf(address owner) public view override returns (uint256) {\n    require(owner != address(0), \"ERC721A: balance query for the zero address\");\n    return uint256(_addressData[owner].balance);\n  }\n\n  function _numberMinted(address owner) internal view returns (uint256) {\n    require(\n      owner != address(0),\n      \"ERC721A: number minted query for the zero address\"\n    );\n    return uint256(_addressData[owner].numberMinted);\n  }\n\n  function ownershipOf(uint256 tokenId)\n    internal\n    view\n    returns (TokenOwnership memory)\n  {\n    require(_exists(tokenId), \"ERC721A: owner query for nonexistent token\");\n\n    uint256 lowestTokenToCheck;\n    if (tokenId \u003e= maxBatchSize) {\n      lowestTokenToCheck = tokenId - maxBatchSize + 1;\n    }\n\n    for (uint256 curr = tokenId; curr \u003e= lowestTokenToCheck; curr--) {\n      TokenOwnership memory ownership = _ownerships[curr];\n      if (ownership.addr != address(0)) {\n        return ownership;\n      }\n    }\n\n    revert(\"ERC721A: unable to determine the owner of token\");\n  }\n\n  /**\n   * @dev See {IERC721-ownerOf}.\n   */\n  function ownerOf(uint256 tokenId) public view override returns (address) {\n    return ownershipOf(tokenId).addr;\n  }\n\n  /**\n   * @dev See {IERC721Metadata-name}.\n   */\n  function name() public view virtual override returns (string memory) {\n    return _name;\n  }\n\n  /**\n   * @dev See {IERC721Metadata-symbol}.\n   */\n  function symbol() public view virtual override returns (string memory) {\n    return _symbol;\n  }\n\n  /**\n   * @dev See {IERC721Metadata-tokenURI}.\n   */\n  function tokenURI(uint256 tokenId)\n    public\n    view\n    virtual\n    override\n    returns (string memory)\n  {\n    require(\n      _exists(tokenId),\n      \"ERC721Metadata: URI query for nonexistent token\"\n    );\n\n    string memory baseURI = _baseURI();\n    return\n      bytes(baseURI).length \u003e 0\n        ? string(abi.encodePacked(baseURI, tokenId.toString()))\n        : \"\";\n  }\n\n  /**\n   * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n   * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n   * by default, can be overriden in child contracts.\n   */\n  string URI;\n  function _baseURI() internal view virtual returns (string memory) {\n    return URI;\n  }\n\n  /**\n   * @dev See {IERC721-approve}.\n   */\n  function approve(address to, uint256 tokenId) public override {\n    address owner = ERC721A.ownerOf(tokenId);\n    require(to != owner, \"ERC721A: approval to current owner\");\n\n    require(\n      _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n      \"ERC721A: approve caller is not owner nor approved for all\"\n    );\n\n    _approve(to, tokenId, owner);\n  }\n\n  /**\n   * @dev See {IERC721-getApproved}.\n   */\n  function getApproved(uint256 tokenId) public view override returns (address) {\n    require(_exists(tokenId), \"ERC721A: approved query for nonexistent token\");\n\n    return _tokenApprovals[tokenId];\n  }\n\n  /**\n   * @dev See {IERC721-setApprovalForAll}.\n   */\n  function setApprovalForAll(address operator, bool approved) public override {\n    require(operator != _msgSender(), \"ERC721A: approve to caller\");\n\n    _operatorApprovals[_msgSender()][operator] = approved;\n    emit ApprovalForAll(_msgSender(), operator, approved);\n  }\n\n  /**\n   * @dev See {IERC721-isApprovedForAll}.\n   */\n  function isApprovedForAll(address owner, address operator)\n    public\n    view\n    virtual\n    override\n    returns (bool)\n  {\n    return _operatorApprovals[owner][operator];\n  }\n\n  /**\n   * @dev See {IERC721-transferFrom}.\n   */\n  function transferFrom(\n    address from,\n    address to,\n    uint256 tokenId\n  ) public override {\n    _transfer(from, to, tokenId);\n  }\n\n  /**\n   * @dev See {IERC721-safeTransferFrom}.\n   */\n  function safeTransferFrom(\n    address from,\n    address to,\n    uint256 tokenId\n  ) public override {\n    safeTransferFrom(from, to, tokenId, \"\");\n  }\n\n  /**\n   * @dev See {IERC721-safeTransferFrom}.\n   */\n  function safeTransferFrom(\n    address from,\n    address to,\n    uint256 tokenId,\n    bytes memory _data\n  ) public override {\n    _transfer(from, to, tokenId);\n    require(\n      _checkOnERC721Received(from, to, tokenId, _data),\n      \"ERC721A: transfer to non ERC721Receiver implementer\"\n    );\n  }\n\n  /**\n   * @dev Returns whether `tokenId` exists.\n   *\n   * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n   *\n   * Tokens start existing when they are minted (`_mint`),\n   */\n  function _exists(uint256 tokenId) internal view returns (bool) {\n    return tokenId \u003c currentIndex;\n  }\n\n  function _safeMint(address to, uint256 quantity) internal {\n    _safeMint(to, quantity, \"\");\n  }\n\n  /**\n   * @dev Mints `quantity` tokens and transfers them to `to`.\n   *\n   * Requirements:\n   *\n   * - there must be `quantity` tokens remaining unminted in the total collection.\n   * - `to` cannot be the zero address.\n   * - `quantity` cannot be larger than the max batch size.\n   *\n   * Emits a {Transfer} event.\n   */\n  function _safeMint(\n    address to,\n    uint256 quantity,\n    bytes memory _data\n  ) internal {\n    uint256 startTokenId = currentIndex;\n    require(to != address(0), \"ERC721A: mint to the zero address\");\n    // We know if the first token in the batch doesn\u0027t exist, the other ones don\u0027t as well, because of serial ordering.\n    require(!_exists(startTokenId), \"ERC721A: token already minted\");\n    require(quantity \u003c= maxBatchSize, \"ERC721A: quantity to mint too high\");\n\n    _beforeTokenTransfers(address(0), to, startTokenId, quantity);\n\n    AddressData memory addressData = _addressData[to];\n    _addressData[to] = AddressData(\n      addressData.balance + uint128(quantity),\n      addressData.numberMinted + uint128(quantity)\n    );\n    _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));\n\n    uint256 updatedIndex = startTokenId;\n\n    for (uint256 i = 0; i \u003c quantity; i++) {\n      emit Transfer(address(0), to, updatedIndex);\n      require(\n        _checkOnERC721Received(address(0), to, updatedIndex, _data),\n        \"ERC721A: transfer to non ERC721Receiver implementer\"\n      );\n      updatedIndex++;\n    }\n\n    currentIndex = updatedIndex;\n    _afterTokenTransfers(address(0), to, startTokenId, quantity);\n  }\n\n  /**\n   * @dev Transfers `tokenId` from `from` to `to`.\n   *\n   * Requirements:\n   *\n   * - `to` cannot be the zero address.\n   * - `tokenId` token must be owned by `from`.\n   *\n   * Emits a {Transfer} event.\n   */\n  function _transfer(\n    address from,\n    address to,\n    uint256 tokenId\n  ) private {\n    TokenOwnership memory prevOwnership = ownershipOf(tokenId);\n\n    bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||\n      getApproved(tokenId) == _msgSender() ||\n      isApprovedForAll(prevOwnership.addr, _msgSender()));\n\n    require(\n      isApprovedOrOwner,\n      \"ERC721A: transfer caller is not owner nor approved\"\n    );\n\n    require(\n      prevOwnership.addr == from,\n      \"ERC721A: transfer from incorrect owner\"\n    );\n    //require(to != address(0), \"ERC721A: transfer to the zero address\");\n\n    _beforeTokenTransfers(from, to, tokenId, 1);\n\n    // Clear approvals from the previous owner\n    _approve(address(0), tokenId, prevOwnership.addr);\n\n    _addressData[from].balance -= 1;\n    _addressData[to].balance += 1;\n    _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));\n\n    // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.\n    // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.\n    uint256 nextTokenId = tokenId + 1;\n    if (_ownerships[nextTokenId].addr == address(0)) {\n      if (_exists(nextTokenId)) {\n        _ownerships[nextTokenId] = TokenOwnership(\n          prevOwnership.addr,\n          prevOwnership.startTimestamp\n        );\n      }\n    }\n\n    emit Transfer(from, to, tokenId);\n    _afterTokenTransfers(from, to, tokenId, 1);\n  }\n\n  /**\n   * @dev Approve `to` to operate on `tokenId`\n   *\n   * Emits a {Approval} event.\n   */\n  function _approve(\n    address to,\n    uint256 tokenId,\n    address owner\n  ) private {\n    _tokenApprovals[tokenId] = to;\n    emit Approval(owner, to, tokenId);\n  }\n\n  uint256 public nextOwnerToExplicitlySet = 0;\n\n  /**\n   * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().\n   */\n  function _setOwnersExplicit(uint256 quantity) internal {\n    uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;\n    require(quantity \u003e 0, \"quantity must be nonzero\");\n    uint256 endIndex = oldNextOwnerToSet + quantity - 1;\n    if (endIndex \u003e collectionSize - 1) {\n      endIndex = collectionSize - 1;\n    }\n    // We know if the last one in the group exists, all in the group exist, due to serial ordering.\n    require(_exists(endIndex), \"not enough minted yet for this cleanup\");\n    for (uint256 i = oldNextOwnerToSet; i \u003c= endIndex; i++) {\n      if (_ownerships[i].addr == address(0)) {\n        TokenOwnership memory ownership = ownershipOf(i);\n        _ownerships[i] = TokenOwnership(\n          ownership.addr,\n          ownership.startTimestamp\n        );\n      }\n    }\n    nextOwnerToExplicitlySet = endIndex + 1;\n  }\n\n  /**\n   * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n   * The call is not executed if the target address is not a contract.\n   *\n   * @param from address representing the previous owner of the given token ID\n   * @param to target address that will receive the tokens\n   * @param tokenId uint256 ID of the token to be transferred\n   * @param _data bytes optional data to send along with the call\n   * @return bool whether the call correctly returned the expected magic value\n   */\n  function _checkOnERC721Received(\n    address from,\n    address to,\n    uint256 tokenId,\n    bytes memory _data\n  ) private returns (bool) {\n    if (to.isContract()) {\n      try\n        IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)\n      returns (bytes4 retval) {\n        return retval == IERC721Receiver(to).onERC721Received.selector;\n      } catch (bytes memory reason) {\n        if (reason.length == 0) {\n          revert(\"ERC721A: transfer to non ERC721Receiver implementer\");\n        } else {\n          assembly {\n            revert(add(32, reason), mload(reason))\n          }\n        }\n      }\n    } else {\n      return true;\n    }\n  }\n\n  /**\n   * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.\n   *\n   * startTokenId - the first token id to be transferred\n   * quantity - the amount to be transferred\n   *\n   * Calling conditions:\n   *\n   * - When `from` and `to` are both non-zero, ``from``\u0027s `tokenId` will be\n   * transferred to `to`.\n   * - When `from` is zero, `tokenId` will be minted for `to`.\n   */\n  function _beforeTokenTransfers(\n    address from,\n    address to,\n    uint256 startTokenId,\n    uint256 quantity\n  ) internal virtual {}\n\n  /**\n   * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes\n   * minting.\n   *\n   * startTokenId - the first token id to be transferred\n   * quantity - the amount to be transferred\n   *\n   * Calling conditions:\n   *\n   * - when `from` and `to` are both non-zero.\n   * - `from` and `to` are never both zero.\n   */\n  function _afterTokenTransfers(\n    address from,\n    address to,\n    uint256 startTokenId,\n    uint256 quantity\n  ) internal virtual {}\n}"},"ERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ERC721.sol\";\nimport \"./IERC721Enumerable.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the EIP that adds\n * enumerability of all the token ids in the contract as well as all token ids owned by each\n * account.\n */\nabstract contract ERC721Enumerable is ERC721, IERC721Enumerable {\n    // Mapping from owner to list of owned token IDs\n    mapping(address =\u003e mapping(uint256 =\u003e uint256)) private _ownedTokens;\n\n    // Mapping from token ID to index of the owner tokens list\n    mapping(uint256 =\u003e uint256) private _ownedTokensIndex;\n\n    // Array with all token ids, used for enumeration\n    uint256[] private _allTokens;\n\n    // Mapping from token id to position in the allTokens array\n    mapping(uint256 =\u003e uint256) private _allTokensIndex;\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n     */\n    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {\n        require(index \u003c ERC721.balanceOf(owner), \"ERC721Enumerable: owner index out of bounds\");\n        return _ownedTokens[owner][index];\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _allTokens.length;\n    }\n\n    /**\n     * @dev See {IERC721Enumerable-tokenByIndex}.\n     */\n    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {\n        require(index \u003c ERC721Enumerable.totalSupply(), \"ERC721Enumerable: global index out of bounds\");\n        return _allTokens[index];\n    }\n\n    /**\n     * @dev Hook that is called before any token transfer. This includes minting\n     * and burning.\n     *\n     * Calling conditions:\n     *\n     * - When `from` and `to` are both non-zero, ``from``\u0027s `tokenId` will be\n     * transferred to `to`.\n     * - When `from` is zero, `tokenId` will be minted for `to`.\n     * - When `to` is zero, ``from``\u0027s `tokenId` will be burned.\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 tokenId\n    ) internal virtual override {\n        super._beforeTokenTransfer(from, to, tokenId);\n\n        if (from == address(0)) {\n            _addTokenToAllTokensEnumeration(tokenId);\n        } else if (from != to) {\n            _removeTokenFromOwnerEnumeration(from, tokenId);\n        }\n        if (to == address(0)) {\n            _removeTokenFromAllTokensEnumeration(tokenId);\n        } else if (to != from) {\n            _addTokenToOwnerEnumeration(to, tokenId);\n        }\n    }\n\n    /**\n     * @dev Private function to add a token to this extension\u0027s ownership-tracking data structures.\n     * @param to address representing the new owner of the given token ID\n     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n     */\n    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n        uint256 length = ERC721.balanceOf(to);\n        _ownedTokens[to][length] = tokenId;\n        _ownedTokensIndex[tokenId] = length;\n    }\n\n    /**\n     * @dev Private function to add a token to this extension\u0027s token tracking data structures.\n     * @param tokenId uint256 ID of the token to be added to the tokens list\n     */\n    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n        _allTokensIndex[tokenId] = _allTokens.length;\n        _allTokens.push(tokenId);\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension\u0027s ownership-tracking data structures. Note that\n     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n     * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n     * @param from address representing the previous owner of the given token ID\n     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n     */\n    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\n        // To prevent a gap in from\u0027s tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;\n        uint256 tokenIndex = _ownedTokensIndex[tokenId];\n\n        // When the token to delete is the last token, the swap operation is unnecessary\n        if (tokenIndex != lastTokenIndex) {\n            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];\n\n            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token\u0027s index\n        }\n\n        // This also deletes the contents at the last position of the array\n        delete _ownedTokensIndex[tokenId];\n        delete _ownedTokens[from][lastTokenIndex];\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension\u0027s token tracking data structures.\n     * This has O(1) time complexity, but alters the order of the _allTokens array.\n     * @param tokenId uint256 ID of the token to be removed from the tokens list\n     */\n    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = _allTokens.length - 1;\n        uint256 tokenIndex = _allTokensIndex[tokenId];\n\n        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n        // an \u0027if\u0027 statement (like in _removeTokenFromOwnerEnumeration)\n        uint256 lastTokenId = _allTokens[lastTokenIndex];\n\n        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token\u0027s index\n\n        // This also deletes the contents at the last position of the array\n        delete _allTokensIndex[tokenId];\n        _allTokens.pop();\n    }\n}"},"IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``\u0027s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the caller.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool _approved) external;\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes calldata data\n    ) external;\n}"},"IERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n    /**\n     * @dev Returns the total amount of tokens stored by the contract.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n     * Use along with {balanceOf} to enumerate all of ``owner``\u0027s tokens.\n     */\n    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n     * Use along with {totalSupply} to enumerate all tokens.\n     */\n    function tokenByIndex(uint256 index) external view returns (uint256);\n}"},"IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}"},"IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}"},"MerkleProof.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev These functions deal with verification of Merkle Trees proofs.\n *\n * The proofs can be generated using the JavaScript library\n * https://github.com/miguelmota/merkletreejs[merkletreejs].\n * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.\n *\n * See `test/utils/cryptography/MerkleProof.test.js` for some examples.\n *\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\n * hashing, or use a hash function other than keccak256 for hashing leaves.\n * This is because the concatenation of a sorted pair of internal nodes in\n * the merkle tree could be reinterpreted as a leaf value.\n */\nlibrary MerkleProof {\n    /**\n     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n     * defined by `root`. For this, a `proof` must be provided, containing\n     * sibling hashes on the branch from the leaf to the root of the tree. Each\n     * pair of leaves and each pair of pre-images are assumed to be sorted.\n     */\n    function verify(\n        bytes32[] memory proof,\n        bytes32 root,\n        bytes32 leaf\n    ) internal pure returns (bool) {\n        return processProof(proof, leaf) == root;\n    }\n\n    /**\n     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n     * hash matches the root of the tree. When processing the proof, the pairs\n     * of leafs \u0026 pre-images are assumed to be sorted.\n     *\n     * _Available since v4.4._\n     */\n    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {\n        bytes32 computedHash = leaf;\n        for (uint256 i = 0; i \u003c proof.length; i++) {\n            bytes32 proofElement = proof[i];\n            if (computedHash \u003c= proofElement) {\n                // Hash(current computed hash + current element of the proof)\n                computedHash = _efficientHash(computedHash, proofElement);\n            } else {\n                // Hash(current element of the proof + current computed hash)\n                computedHash = _efficientHash(proofElement, computedHash);\n            }\n        }\n        return computedHash;\n    }\n\n    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {\n        assembly {\n            mstore(0x00, a)\n            mstore(0x20, b)\n            value := keccak256(0x00, 0x40)\n        }\n    }\n}"},"Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        _;\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}"},"ProbablyNothing.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\nimport \"./ERC721A.sol\";\nimport \"./Ownable.sol\";\nimport \"./ReentrancyGuard.sol\";\nimport \"./MerkleProof.sol\";\n\ncontract ProbablyNothing is ERC721A, Ownable, ReentrancyGuard {\n    string public baseURI;\n    uint256 public maxSupply;\n    bytes32 public merkleRoot;\n\n    bool alOnly;\n    bool mintOpen;\n\n    mapping(address =\u003e bool) public hasMinted;\n    mapping(address =\u003e uint256) public numOfMints;\n\n    event minted(address minter, uint256 id);\n    event burned(address from, address to, uint256 id);\n\n    constructor(\n        string memory name,\n        string memory symbol,\n        uint256 _maxSupply\n    ) ERC721A(name, symbol, 100, _maxSupply) {\n        maxSupply = _maxSupply;\n        alOnly = true;\n        mintOpen = false;\n        baseURI = \"https://ipfs.io/ipfs/QmcQj3Yi1PtytJJ9iepD3awgVLSNzTZB6YMLBFEdrz559F\";\n    }\n\n    function mint(uint256 _amount, bytes32[] calldata _merkleProof) external nonReentrant {\n        require(totalSupply() + _amount \u003c= maxSupply, \"Exceeds max supply\");\n        require(_amount + numOfMints[_msgSender()] \u003c= 2, \"Max two per wallet\");\n        require(mintOpen, \"Minting is paused\");\n\n        numOfMints[_msgSender()] += _amount;\n\n        if(isAllowListed(_msgSender(), _merkleProof) \u0026\u0026 !hasMinted[_msgSender()]) {\n            if(numOfMints[_msgSender()] == 2){\n                hasMinted[_msgSender()] = true;\n            }\n        } else {\n            require(!alOnly, \"Only allow listed addresses can mint\");\n        }\n\n        _safeMint(_msgSender(), _amount);\n        emit minted(_msgSender(), totalSupply());\n    }\n\n    function ownerMint(address _recipient, uint256 _amount) external onlyOwner {\n        require(totalSupply() + _amount \u003c= maxSupply, \"Exceeds max supply\");\n        _safeMint(_recipient, _amount);\n        emit minted(_recipient, totalSupply());\n    }\n\n    function isAllowListed(address _recipient, bytes32[] calldata _merkleProof) public view returns(bool) {\n        bytes32 leaf = keccak256(abi.encodePacked(_recipient));\n        bool isal = MerkleProof.verify(_merkleProof, merkleRoot, leaf);\n        return isal;\n    }\n\n    function setRoot(bytes32 root) external onlyOwner {\n        merkleRoot = root;\n    }\n\n    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n        return baseURI;\n    }\n\n    function burn(uint256 tokenId) external {\n        transferFrom(_msgSender(), address(0), tokenId);\n        emit burned(_msgSender(), address(0), tokenId);\n    }\n\n    function changeURI(string memory _baseURI) external onlyOwner {\n        baseURI = _baseURI;\n    }\n\n    function flipMintState() external onlyOwner {\n        mintOpen = !mintOpen;\n    }\n\n    function flipALState() external onlyOwner {\n        alOnly = !alOnly;\n    }\n\n    function withdraw() public onlyOwner {\n        (bool success,) = owner().call{value: address(this).balance}(\"\");\n        require(success, \"Transfer fail\");\n    }\n}"},"ReentrancyGuard.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot\u0027s contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler\u0027s defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction\u0027s gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and make it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}"},"Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        // Inspired by OraclizeAPI\u0027s implementation - MIT licence\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n        if (value == 0) {\n            return \"0\";\n        }\n        uint256 temp = value;\n        uint256 digits;\n        while (temp != 0) {\n            digits++;\n            temp /= 10;\n        }\n        bytes memory buffer = new bytes(digits);\n        while (value != 0) {\n            digits -= 1;\n            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n            value /= 10;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        if (value == 0) {\n            return \"0x00\";\n        }\n        uint256 temp = value;\n        uint256 length = 0;\n        while (temp != 0) {\n            length++;\n            temp \u003e\u003e= 8;\n        }\n        return toHexString(value, length);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i \u003e 1; --i) {\n            buffer[i] = _HEX_SYMBOLS[value \u0026 0xf];\n            value \u003e\u003e= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n}"}}

          File 4 of 7: WETH9
          // Copyright (C) 2015, 2016, 2017 Dapphub
          
          // This program is free software: you can redistribute it and/or modify
          // it under the terms of the GNU General Public License as published by
          // the Free Software Foundation, either version 3 of the License, or
          // (at your option) any later version.
          
          // This program is distributed in the hope that it will be useful,
          // but WITHOUT ANY WARRANTY; without even the implied warranty of
          // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
          // GNU General Public License for more details.
          
          // You should have received a copy of the GNU General Public License
          // along with this program.  If not, see <http://www.gnu.org/licenses/>.
          
          pragma solidity ^0.4.18;
          
          contract WETH9 {
              string public name     = "Wrapped Ether";
              string public symbol   = "WETH";
              uint8  public decimals = 18;
          
              event  Approval(address indexed src, address indexed guy, uint wad);
              event  Transfer(address indexed src, address indexed dst, uint wad);
              event  Deposit(address indexed dst, uint wad);
              event  Withdrawal(address indexed src, uint wad);
          
              mapping (address => uint)                       public  balanceOf;
              mapping (address => mapping (address => uint))  public  allowance;
          
              function() public payable {
                  deposit();
              }
              function deposit() public payable {
                  balanceOf[msg.sender] += msg.value;
                  Deposit(msg.sender, msg.value);
              }
              function withdraw(uint wad) public {
                  require(balanceOf[msg.sender] >= wad);
                  balanceOf[msg.sender] -= wad;
                  msg.sender.transfer(wad);
                  Withdrawal(msg.sender, wad);
              }
          
              function totalSupply() public view returns (uint) {
                  return this.balance;
              }
          
              function approve(address guy, uint wad) public returns (bool) {
                  allowance[msg.sender][guy] = wad;
                  Approval(msg.sender, guy, wad);
                  return true;
              }
          
              function transfer(address dst, uint wad) public returns (bool) {
                  return transferFrom(msg.sender, dst, wad);
              }
          
              function transferFrom(address src, address dst, uint wad)
                  public
                  returns (bool)
              {
                  require(balanceOf[src] >= wad);
          
                  if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                      require(allowance[src][msg.sender] >= wad);
                      allowance[src][msg.sender] -= wad;
                  }
          
                  balanceOf[src] -= wad;
                  balanceOf[dst] += wad;
          
                  Transfer(src, dst, wad);
          
                  return true;
              }
          }
          
          
          /*
                              GNU GENERAL PUBLIC LICENSE
                                 Version 3, 29 June 2007
          
           Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
           Everyone is permitted to copy and distribute verbatim copies
           of this license document, but changing it is not allowed.
          
                                      Preamble
          
            The GNU General Public License is a free, copyleft license for
          software and other kinds of works.
          
            The licenses for most software and other practical works are designed
          to take away your freedom to share and change the works.  By contrast,
          the GNU General Public License is intended to guarantee your freedom to
          share and change all versions of a program--to make sure it remains free
          software for all its users.  We, the Free Software Foundation, use the
          GNU General Public License for most of our software; it applies also to
          any other work released this way by its authors.  You can apply it to
          your programs, too.
          
            When we speak of free software, we are referring to freedom, not
          price.  Our General Public Licenses are designed to make sure that you
          have the freedom to distribute copies of free software (and charge for
          them if you wish), that you receive source code or can get it if you
          want it, that you can change the software or use pieces of it in new
          free programs, and that you know you can do these things.
          
            To protect your rights, we need to prevent others from denying you
          these rights or asking you to surrender the rights.  Therefore, you have
          certain responsibilities if you distribute copies of the software, or if
          you modify it: responsibilities to respect the freedom of others.
          
            For example, if you distribute copies of such a program, whether
          gratis or for a fee, you must pass on to the recipients the same
          freedoms that you received.  You must make sure that they, too, receive
          or can get the source code.  And you must show them these terms so they
          know their rights.
          
            Developers that use the GNU GPL protect your rights with two steps:
          (1) assert copyright on the software, and (2) offer you this License
          giving you legal permission to copy, distribute and/or modify it.
          
            For the developers' and authors' protection, the GPL clearly explains
          that there is no warranty for this free software.  For both users' and
          authors' sake, the GPL requires that modified versions be marked as
          changed, so that their problems will not be attributed erroneously to
          authors of previous versions.
          
            Some devices are designed to deny users access to install or run
          modified versions of the software inside them, although the manufacturer
          can do so.  This is fundamentally incompatible with the aim of
          protecting users' freedom to change the software.  The systematic
          pattern of such abuse occurs in the area of products for individuals to
          use, which is precisely where it is most unacceptable.  Therefore, we
          have designed this version of the GPL to prohibit the practice for those
          products.  If such problems arise substantially in other domains, we
          stand ready to extend this provision to those domains in future versions
          of the GPL, as needed to protect the freedom of users.
          
            Finally, every program is threatened constantly by software patents.
          States should not allow patents to restrict development and use of
          software on general-purpose computers, but in those that do, we wish to
          avoid the special danger that patents applied to a free program could
          make it effectively proprietary.  To prevent this, the GPL assures that
          patents cannot be used to render the program non-free.
          
            The precise terms and conditions for copying, distribution and
          modification follow.
          
                                 TERMS AND CONDITIONS
          
            0. Definitions.
          
            "This License" refers to version 3 of the GNU General Public License.
          
            "Copyright" also means copyright-like laws that apply to other kinds of
          works, such as semiconductor masks.
          
            "The Program" refers to any copyrightable work licensed under this
          License.  Each licensee is addressed as "you".  "Licensees" and
          "recipients" may be individuals or organizations.
          
            To "modify" a work means to copy from or adapt all or part of the work
          in a fashion requiring copyright permission, other than the making of an
          exact copy.  The resulting work is called a "modified version" of the
          earlier work or a work "based on" the earlier work.
          
            A "covered work" means either the unmodified Program or a work based
          on the Program.
          
            To "propagate" a work means to do anything with it that, without
          permission, would make you directly or secondarily liable for
          infringement under applicable copyright law, except executing it on a
          computer or modifying a private copy.  Propagation includes copying,
          distribution (with or without modification), making available to the
          public, and in some countries other activities as well.
          
            To "convey" a work means any kind of propagation that enables other
          parties to make or receive copies.  Mere interaction with a user through
          a computer network, with no transfer of a copy, is not conveying.
          
            An interactive user interface displays "Appropriate Legal Notices"
          to the extent that it includes a convenient and prominently visible
          feature that (1) displays an appropriate copyright notice, and (2)
          tells the user that there is no warranty for the work (except to the
          extent that warranties are provided), that licensees may convey the
          work under this License, and how to view a copy of this License.  If
          the interface presents a list of user commands or options, such as a
          menu, a prominent item in the list meets this criterion.
          
            1. Source Code.
          
            The "source code" for a work means the preferred form of the work
          for making modifications to it.  "Object code" means any non-source
          form of a work.
          
            A "Standard Interface" means an interface that either is an official
          standard defined by a recognized standards body, or, in the case of
          interfaces specified for a particular programming language, one that
          is widely used among developers working in that language.
          
            The "System Libraries" of an executable work include anything, other
          than the work as a whole, that (a) is included in the normal form of
          packaging a Major Component, but which is not part of that Major
          Component, and (b) serves only to enable use of the work with that
          Major Component, or to implement a Standard Interface for which an
          implementation is available to the public in source code form.  A
          "Major Component", in this context, means a major essential component
          (kernel, window system, and so on) of the specific operating system
          (if any) on which the executable work runs, or a compiler used to
          produce the work, or an object code interpreter used to run it.
          
            The "Corresponding Source" for a work in object code form means all
          the source code needed to generate, install, and (for an executable
          work) run the object code and to modify the work, including scripts to
          control those activities.  However, it does not include the work's
          System Libraries, or general-purpose tools or generally available free
          programs which are used unmodified in performing those activities but
          which are not part of the work.  For example, Corresponding Source
          includes interface definition files associated with source files for
          the work, and the source code for shared libraries and dynamically
          linked subprograms that the work is specifically designed to require,
          such as by intimate data communication or control flow between those
          subprograms and other parts of the work.
          
            The Corresponding Source need not include anything that users
          can regenerate automatically from other parts of the Corresponding
          Source.
          
            The Corresponding Source for a work in source code form is that
          same work.
          
            2. Basic Permissions.
          
            All rights granted under this License are granted for the term of
          copyright on the Program, and are irrevocable provided the stated
          conditions are met.  This License explicitly affirms your unlimited
          permission to run the unmodified Program.  The output from running a
          covered work is covered by this License only if the output, given its
          content, constitutes a covered work.  This License acknowledges your
          rights of fair use or other equivalent, as provided by copyright law.
          
            You may make, run and propagate covered works that you do not
          convey, without conditions so long as your license otherwise remains
          in force.  You may convey covered works to others for the sole purpose
          of having them make modifications exclusively for you, or provide you
          with facilities for running those works, provided that you comply with
          the terms of this License in conveying all material for which you do
          not control copyright.  Those thus making or running the covered works
          for you must do so exclusively on your behalf, under your direction
          and control, on terms that prohibit them from making any copies of
          your copyrighted material outside their relationship with you.
          
            Conveying under any other circumstances is permitted solely under
          the conditions stated below.  Sublicensing is not allowed; section 10
          makes it unnecessary.
          
            3. Protecting Users' Legal Rights From Anti-Circumvention Law.
          
            No covered work shall be deemed part of an effective technological
          measure under any applicable law fulfilling obligations under article
          11 of the WIPO copyright treaty adopted on 20 December 1996, or
          similar laws prohibiting or restricting circumvention of such
          measures.
          
            When you convey a covered work, you waive any legal power to forbid
          circumvention of technological measures to the extent such circumvention
          is effected by exercising rights under this License with respect to
          the covered work, and you disclaim any intention to limit operation or
          modification of the work as a means of enforcing, against the work's
          users, your or third parties' legal rights to forbid circumvention of
          technological measures.
          
            4. Conveying Verbatim Copies.
          
            You may convey verbatim copies of the Program's source code as you
          receive it, in any medium, provided that you conspicuously and
          appropriately publish on each copy an appropriate copyright notice;
          keep intact all notices stating that this License and any
          non-permissive terms added in accord with section 7 apply to the code;
          keep intact all notices of the absence of any warranty; and give all
          recipients a copy of this License along with the Program.
          
            You may charge any price or no price for each copy that you convey,
          and you may offer support or warranty protection for a fee.
          
            5. Conveying Modified Source Versions.
          
            You may convey a work based on the Program, or the modifications to
          produce it from the Program, in the form of source code under the
          terms of section 4, provided that you also meet all of these conditions:
          
              a) The work must carry prominent notices stating that you modified
              it, and giving a relevant date.
          
              b) The work must carry prominent notices stating that it is
              released under this License and any conditions added under section
              7.  This requirement modifies the requirement in section 4 to
              "keep intact all notices".
          
              c) You must license the entire work, as a whole, under this
              License to anyone who comes into possession of a copy.  This
              License will therefore apply, along with any applicable section 7
              additional terms, to the whole of the work, and all its parts,
              regardless of how they are packaged.  This License gives no
              permission to license the work in any other way, but it does not
              invalidate such permission if you have separately received it.
          
              d) If the work has interactive user interfaces, each must display
              Appropriate Legal Notices; however, if the Program has interactive
              interfaces that do not display Appropriate Legal Notices, your
              work need not make them do so.
          
            A compilation of a covered work with other separate and independent
          works, which are not by their nature extensions of the covered work,
          and which are not combined with it such as to form a larger program,
          in or on a volume of a storage or distribution medium, is called an
          "aggregate" if the compilation and its resulting copyright are not
          used to limit the access or legal rights of the compilation's users
          beyond what the individual works permit.  Inclusion of a covered work
          in an aggregate does not cause this License to apply to the other
          parts of the aggregate.
          
            6. Conveying Non-Source Forms.
          
            You may convey a covered work in object code form under the terms
          of sections 4 and 5, provided that you also convey the
          machine-readable Corresponding Source under the terms of this License,
          in one of these ways:
          
              a) Convey the object code in, or embodied in, a physical product
              (including a physical distribution medium), accompanied by the
              Corresponding Source fixed on a durable physical medium
              customarily used for software interchange.
          
              b) Convey the object code in, or embodied in, a physical product
              (including a physical distribution medium), accompanied by a
              written offer, valid for at least three years and valid for as
              long as you offer spare parts or customer support for that product
              model, to give anyone who possesses the object code either (1) a
              copy of the Corresponding Source for all the software in the
              product that is covered by this License, on a durable physical
              medium customarily used for software interchange, for a price no
              more than your reasonable cost of physically performing this
              conveying of source, or (2) access to copy the
              Corresponding Source from a network server at no charge.
          
              c) Convey individual copies of the object code with a copy of the
              written offer to provide the Corresponding Source.  This
              alternative is allowed only occasionally and noncommercially, and
              only if you received the object code with such an offer, in accord
              with subsection 6b.
          
              d) Convey the object code by offering access from a designated
              place (gratis or for a charge), and offer equivalent access to the
              Corresponding Source in the same way through the same place at no
              further charge.  You need not require recipients to copy the
              Corresponding Source along with the object code.  If the place to
              copy the object code is a network server, the Corresponding Source
              may be on a different server (operated by you or a third party)
              that supports equivalent copying facilities, provided you maintain
              clear directions next to the object code saying where to find the
              Corresponding Source.  Regardless of what server hosts the
              Corresponding Source, you remain obligated to ensure that it is
              available for as long as needed to satisfy these requirements.
          
              e) Convey the object code using peer-to-peer transmission, provided
              you inform other peers where the object code and Corresponding
              Source of the work are being offered to the general public at no
              charge under subsection 6d.
          
            A separable portion of the object code, whose source code is excluded
          from the Corresponding Source as a System Library, need not be
          included in conveying the object code work.
          
            A "User Product" is either (1) a "consumer product", which means any
          tangible personal property which is normally used for personal, family,
          or household purposes, or (2) anything designed or sold for incorporation
          into a dwelling.  In determining whether a product is a consumer product,
          doubtful cases shall be resolved in favor of coverage.  For a particular
          product received by a particular user, "normally used" refers to a
          typical or common use of that class of product, regardless of the status
          of the particular user or of the way in which the particular user
          actually uses, or expects or is expected to use, the product.  A product
          is a consumer product regardless of whether the product has substantial
          commercial, industrial or non-consumer uses, unless such uses represent
          the only significant mode of use of the product.
          
            "Installation Information" for a User Product means any methods,
          procedures, authorization keys, or other information required to install
          and execute modified versions of a covered work in that User Product from
          a modified version of its Corresponding Source.  The information must
          suffice to ensure that the continued functioning of the modified object
          code is in no case prevented or interfered with solely because
          modification has been made.
          
            If you convey an object code work under this section in, or with, or
          specifically for use in, a User Product, and the conveying occurs as
          part of a transaction in which the right of possession and use of the
          User Product is transferred to the recipient in perpetuity or for a
          fixed term (regardless of how the transaction is characterized), the
          Corresponding Source conveyed under this section must be accompanied
          by the Installation Information.  But this requirement does not apply
          if neither you nor any third party retains the ability to install
          modified object code on the User Product (for example, the work has
          been installed in ROM).
          
            The requirement to provide Installation Information does not include a
          requirement to continue to provide support service, warranty, or updates
          for a work that has been modified or installed by the recipient, or for
          the User Product in which it has been modified or installed.  Access to a
          network may be denied when the modification itself materially and
          adversely affects the operation of the network or violates the rules and
          protocols for communication across the network.
          
            Corresponding Source conveyed, and Installation Information provided,
          in accord with this section must be in a format that is publicly
          documented (and with an implementation available to the public in
          source code form), and must require no special password or key for
          unpacking, reading or copying.
          
            7. Additional Terms.
          
            "Additional permissions" are terms that supplement the terms of this
          License by making exceptions from one or more of its conditions.
          Additional permissions that are applicable to the entire Program shall
          be treated as though they were included in this License, to the extent
          that they are valid under applicable law.  If additional permissions
          apply only to part of the Program, that part may be used separately
          under those permissions, but the entire Program remains governed by
          this License without regard to the additional permissions.
          
            When you convey a copy of a covered work, you may at your option
          remove any additional permissions from that copy, or from any part of
          it.  (Additional permissions may be written to require their own
          removal in certain cases when you modify the work.)  You may place
          additional permissions on material, added by you to a covered work,
          for which you have or can give appropriate copyright permission.
          
            Notwithstanding any other provision of this License, for material you
          add to a covered work, you may (if authorized by the copyright holders of
          that material) supplement the terms of this License with terms:
          
              a) Disclaiming warranty or limiting liability differently from the
              terms of sections 15 and 16 of this License; or
          
              b) Requiring preservation of specified reasonable legal notices or
              author attributions in that material or in the Appropriate Legal
              Notices displayed by works containing it; or
          
              c) Prohibiting misrepresentation of the origin of that material, or
              requiring that modified versions of such material be marked in
              reasonable ways as different from the original version; or
          
              d) Limiting the use for publicity purposes of names of licensors or
              authors of the material; or
          
              e) Declining to grant rights under trademark law for use of some
              trade names, trademarks, or service marks; or
          
              f) Requiring indemnification of licensors and authors of that
              material by anyone who conveys the material (or modified versions of
              it) with contractual assumptions of liability to the recipient, for
              any liability that these contractual assumptions directly impose on
              those licensors and authors.
          
            All other non-permissive additional terms are considered "further
          restrictions" within the meaning of section 10.  If the Program as you
          received it, or any part of it, contains a notice stating that it is
          governed by this License along with a term that is a further
          restriction, you may remove that term.  If a license document contains
          a further restriction but permits relicensing or conveying under this
          License, you may add to a covered work material governed by the terms
          of that license document, provided that the further restriction does
          not survive such relicensing or conveying.
          
            If you add terms to a covered work in accord with this section, you
          must place, in the relevant source files, a statement of the
          additional terms that apply to those files, or a notice indicating
          where to find the applicable terms.
          
            Additional terms, permissive or non-permissive, may be stated in the
          form of a separately written license, or stated as exceptions;
          the above requirements apply either way.
          
            8. Termination.
          
            You may not propagate or modify a covered work except as expressly
          provided under this License.  Any attempt otherwise to propagate or
          modify it is void, and will automatically terminate your rights under
          this License (including any patent licenses granted under the third
          paragraph of section 11).
          
            However, if you cease all violation of this License, then your
          license from a particular copyright holder is reinstated (a)
          provisionally, unless and until the copyright holder explicitly and
          finally terminates your license, and (b) permanently, if the copyright
          holder fails to notify you of the violation by some reasonable means
          prior to 60 days after the cessation.
          
            Moreover, your license from a particular copyright holder is
          reinstated permanently if the copyright holder notifies you of the
          violation by some reasonable means, this is the first time you have
          received notice of violation of this License (for any work) from that
          copyright holder, and you cure the violation prior to 30 days after
          your receipt of the notice.
          
            Termination of your rights under this section does not terminate the
          licenses of parties who have received copies or rights from you under
          this License.  If your rights have been terminated and not permanently
          reinstated, you do not qualify to receive new licenses for the same
          material under section 10.
          
            9. Acceptance Not Required for Having Copies.
          
            You are not required to accept this License in order to receive or
          run a copy of the Program.  Ancillary propagation of a covered work
          occurring solely as a consequence of using peer-to-peer transmission
          to receive a copy likewise does not require acceptance.  However,
          nothing other than this License grants you permission to propagate or
          modify any covered work.  These actions infringe copyright if you do
          not accept this License.  Therefore, by modifying or propagating a
          covered work, you indicate your acceptance of this License to do so.
          
            10. Automatic Licensing of Downstream Recipients.
          
            Each time you convey a covered work, the recipient automatically
          receives a license from the original licensors, to run, modify and
          propagate that work, subject to this License.  You are not responsible
          for enforcing compliance by third parties with this License.
          
            An "entity transaction" is a transaction transferring control of an
          organization, or substantially all assets of one, or subdividing an
          organization, or merging organizations.  If propagation of a covered
          work results from an entity transaction, each party to that
          transaction who receives a copy of the work also receives whatever
          licenses to the work the party's predecessor in interest had or could
          give under the previous paragraph, plus a right to possession of the
          Corresponding Source of the work from the predecessor in interest, if
          the predecessor has it or can get it with reasonable efforts.
          
            You may not impose any further restrictions on the exercise of the
          rights granted or affirmed under this License.  For example, you may
          not impose a license fee, royalty, or other charge for exercise of
          rights granted under this License, and you may not initiate litigation
          (including a cross-claim or counterclaim in a lawsuit) alleging that
          any patent claim is infringed by making, using, selling, offering for
          sale, or importing the Program or any portion of it.
          
            11. Patents.
          
            A "contributor" is a copyright holder who authorizes use under this
          License of the Program or a work on which the Program is based.  The
          work thus licensed is called the contributor's "contributor version".
          
            A contributor's "essential patent claims" are all patent claims
          owned or controlled by the contributor, whether already acquired or
          hereafter acquired, that would be infringed by some manner, permitted
          by this License, of making, using, or selling its contributor version,
          but do not include claims that would be infringed only as a
          consequence of further modification of the contributor version.  For
          purposes of this definition, "control" includes the right to grant
          patent sublicenses in a manner consistent with the requirements of
          this License.
          
            Each contributor grants you a non-exclusive, worldwide, royalty-free
          patent license under the contributor's essential patent claims, to
          make, use, sell, offer for sale, import and otherwise run, modify and
          propagate the contents of its contributor version.
          
            In the following three paragraphs, a "patent license" is any express
          agreement or commitment, however denominated, not to enforce a patent
          (such as an express permission to practice a patent or covenant not to
          sue for patent infringement).  To "grant" such a patent license to a
          party means to make such an agreement or commitment not to enforce a
          patent against the party.
          
            If you convey a covered work, knowingly relying on a patent license,
          and the Corresponding Source of the work is not available for anyone
          to copy, free of charge and under the terms of this License, through a
          publicly available network server or other readily accessible means,
          then you must either (1) cause the Corresponding Source to be so
          available, or (2) arrange to deprive yourself of the benefit of the
          patent license for this particular work, or (3) arrange, in a manner
          consistent with the requirements of this License, to extend the patent
          license to downstream recipients.  "Knowingly relying" means you have
          actual knowledge that, but for the patent license, your conveying the
          covered work in a country, or your recipient's use of the covered work
          in a country, would infringe one or more identifiable patents in that
          country that you have reason to believe are valid.
          
            If, pursuant to or in connection with a single transaction or
          arrangement, you convey, or propagate by procuring conveyance of, a
          covered work, and grant a patent license to some of the parties
          receiving the covered work authorizing them to use, propagate, modify
          or convey a specific copy of the covered work, then the patent license
          you grant is automatically extended to all recipients of the covered
          work and works based on it.
          
            A patent license is "discriminatory" if it does not include within
          the scope of its coverage, prohibits the exercise of, or is
          conditioned on the non-exercise of one or more of the rights that are
          specifically granted under this License.  You may not convey a covered
          work if you are a party to an arrangement with a third party that is
          in the business of distributing software, under which you make payment
          to the third party based on the extent of your activity of conveying
          the work, and under which the third party grants, to any of the
          parties who would receive the covered work from you, a discriminatory
          patent license (a) in connection with copies of the covered work
          conveyed by you (or copies made from those copies), or (b) primarily
          for and in connection with specific products or compilations that
          contain the covered work, unless you entered into that arrangement,
          or that patent license was granted, prior to 28 March 2007.
          
            Nothing in this License shall be construed as excluding or limiting
          any implied license or other defenses to infringement that may
          otherwise be available to you under applicable patent law.
          
            12. No Surrender of Others' Freedom.
          
            If conditions are imposed on you (whether by court order, agreement or
          otherwise) that contradict the conditions of this License, they do not
          excuse you from the conditions of this License.  If you cannot convey a
          covered work so as to satisfy simultaneously your obligations under this
          License and any other pertinent obligations, then as a consequence you may
          not convey it at all.  For example, if you agree to terms that obligate you
          to collect a royalty for further conveying from those to whom you convey
          the Program, the only way you could satisfy both those terms and this
          License would be to refrain entirely from conveying the Program.
          
            13. Use with the GNU Affero General Public License.
          
            Notwithstanding any other provision of this License, you have
          permission to link or combine any covered work with a work licensed
          under version 3 of the GNU Affero General Public License into a single
          combined work, and to convey the resulting work.  The terms of this
          License will continue to apply to the part which is the covered work,
          but the special requirements of the GNU Affero General Public License,
          section 13, concerning interaction through a network will apply to the
          combination as such.
          
            14. Revised Versions of this License.
          
            The Free Software Foundation may publish revised and/or new versions of
          the GNU General Public License from time to time.  Such new versions will
          be similar in spirit to the present version, but may differ in detail to
          address new problems or concerns.
          
            Each version is given a distinguishing version number.  If the
          Program specifies that a certain numbered version of the GNU General
          Public License "or any later version" applies to it, you have the
          option of following the terms and conditions either of that numbered
          version or of any later version published by the Free Software
          Foundation.  If the Program does not specify a version number of the
          GNU General Public License, you may choose any version ever published
          by the Free Software Foundation.
          
            If the Program specifies that a proxy can decide which future
          versions of the GNU General Public License can be used, that proxy's
          public statement of acceptance of a version permanently authorizes you
          to choose that version for the Program.
          
            Later license versions may give you additional or different
          permissions.  However, no additional obligations are imposed on any
          author or copyright holder as a result of your choosing to follow a
          later version.
          
            15. Disclaimer of Warranty.
          
            THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
          APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
          HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
          OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
          THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
          PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
          IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
          ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
          
            16. Limitation of Liability.
          
            IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
          WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
          THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
          GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
          USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
          DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
          PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
          EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
          SUCH DAMAGES.
          
            17. Interpretation of Sections 15 and 16.
          
            If the disclaimer of warranty and limitation of liability provided
          above cannot be given local legal effect according to their terms,
          reviewing courts shall apply local law that most closely approximates
          an absolute waiver of all civil liability in connection with the
          Program, unless a warranty or assumption of liability accompanies a
          copy of the Program in return for a fee.
          
                               END OF TERMS AND CONDITIONS
          
                      How to Apply These Terms to Your New Programs
          
            If you develop a new program, and you want it to be of the greatest
          possible use to the public, the best way to achieve this is to make it
          free software which everyone can redistribute and change under these terms.
          
            To do so, attach the following notices to the program.  It is safest
          to attach them to the start of each source file to most effectively
          state the exclusion of warranty; and each file should have at least
          the "copyright" line and a pointer to where the full notice is found.
          
              <one line to give the program's name and a brief idea of what it does.>
              Copyright (C) <year>  <name of author>
          
              This program is free software: you can redistribute it and/or modify
              it under the terms of the GNU General Public License as published by
              the Free Software Foundation, either version 3 of the License, or
              (at your option) any later version.
          
              This program is distributed in the hope that it will be useful,
              but WITHOUT ANY WARRANTY; without even the implied warranty of
              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
              GNU General Public License for more details.
          
              You should have received a copy of the GNU General Public License
              along with this program.  If not, see <http://www.gnu.org/licenses/>.
          
          Also add information on how to contact you by electronic and paper mail.
          
            If the program does terminal interaction, make it output a short
          notice like this when it starts in an interactive mode:
          
              <program>  Copyright (C) <year>  <name of author>
              This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
              This is free software, and you are welcome to redistribute it
              under certain conditions; type `show c' for details.
          
          The hypothetical commands `show w' and `show c' should show the appropriate
          parts of the General Public License.  Of course, your program's commands
          might be different; for a GUI interface, you would use an "about box".
          
            You should also get your employer (if you work as a programmer) or school,
          if any, to sign a "copyright disclaimer" for the program, if necessary.
          For more information on this, and how to apply and follow the GNU GPL, see
          <http://www.gnu.org/licenses/>.
          
            The GNU General Public License does not permit incorporating your program
          into proprietary programs.  If your program is a subroutine library, you
          may consider it more useful to permit linking proprietary applications with
          the library.  If this is what you want to do, use the GNU Lesser General
          Public License instead of this License.  But first, please read
          <http://www.gnu.org/philosophy/why-not-lgpl.html>.
          
          */

          File 5 of 7: TrustedForwarder
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.4;
          import "@openzeppelin/contracts/access/Ownable.sol";
          import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
          import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
          import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
          /**
           * @title  TrustedForwarder
           * @author Limit Break, Inc.
           * @notice TrustedForwarder is a generic message forwarder, which allows you to relay transactions to any contract and preserve the original sender.
           *         The processor acts as a trusted proxy, which can be a way to limit interactions with your contract, or enforce certain conditions.
           */
          contract TrustedForwarder is EIP712, Initializable, Ownable {
              error TrustedForwarder__CannotSetAppSignerToZeroAddress();
              error TrustedForwarder__CannotSetOwnerToZeroAddress();
              error TrustedForwarder__CannotUseWithoutSignature();
              error TrustedForwarder__InvalidSignature();
              error TrustedForwarder__SignerNotAuthorized();
              struct SignatureECDSA {
                  uint8 v;
                  bytes32 r;
                  bytes32 s;
              }
              // keccak256("AppSigner(bytes32 messageHash,address target,address sender)")
              bytes32 public constant APP_SIGNER_TYPEHASH = 0xc83d02443cc9e12c5d2faae8a9a36bf0112f5b4a8cce23c9277a0c68bf638762;
              address public signer;
              constructor() EIP712("TrustedForwarder", "1") {}
              /**
               * @notice Initializes the TrustedForwarder contract.
               *
               * @dev    This should be called atomically with the clone of the contract to prevent bad actors from calling it.
               * @dev    - Throws if the contract is already initialized
               *
               * @param owner           The address to assign the owner role to.
               * @param appSigner       The address to assign the app signer role to.
               */
              function __TrustedForwarder_init(address owner, address appSigner) external initializer {
                  if (owner == address(0)) {
                      revert TrustedForwarder__CannotSetOwnerToZeroAddress();
                  }
                  if (appSigner != address(0)) {
                      signer = appSigner;
                  }
                  _transferOwnership(owner);
              }
              /**
               * @notice Forwards a message to a target contract, preserving the original sender.
               * @notice In the case the forwarder does not require a signature, this function should be used to save gas.
               *
               * @dev    - Throws if the target contract reverts.
               * @dev    - Throws if the target address has no code.
               * @dev    - Throws if `signer` is not address(0).
               *
               * @param target    The address of the contract to forward the message to.
               * @param message   The calldata to forward.
               *
               * @return returnData The return data of the call to the target contract.
               */
              function forwardCall(address target, bytes calldata message)
                  external
                  payable
                  returns (bytes memory returnData)
              {
                  address signerCache = signer;
                  if (signerCache != address(0)) {
                      revert TrustedForwarder__CannotUseWithoutSignature();
                  }
                  bytes memory encodedData = _encodeERC2771Context(message, _msgSender());
                  assembly {
                      let success := call(gas(), target, callvalue(), add(encodedData, 0x20), mload(encodedData), 0, 0)
                      let size := returndatasize()
                      returnData := mload(0x40)
                      mstore(returnData, size)
                      mstore(0x40, add(add(returnData, 0x20), size)) // Adjust memory pointer
                      returndatacopy(add(returnData, 0x20), 0, size) // Copy returndata to memory
                      if iszero(success) {
                          revert(add(returnData, 0x20), size) // Revert with return data on failure
                      }
                      // If the call was successful, but the return data is empty, check if the target address has code
                      if iszero(size) {
                          if iszero(extcodesize(target)) {
                              mstore(0x00, 0x39bf07c1) // Store function selector `TrustedForwarder__TargetAddressHasNoCode()` and revert
                              revert(0x1c, 0x04) // Revert with the custom function selector
                          }
                      }
                  }
              }
              /**
               * @notice Forwards a message to a target contract, preserving the original sender.
               * @notice This should only be used if the forwarder requires a signature.
               * @notice In the case the app signer is not set, use the overloaded `forwardCall` function without a signature variable.
               *
               * @dev    - Throws if the target contract reverts.
               * @dev    - Throws if the target address has no code.
               * @dev    - Throws if `signer` is not address(0) and the signature does not match the signer.
               *
               * @param target    The address of the contract to forward the message to.
               * @param message   The calldata to forward.
               * @param signature The signature of the message.
               *
               * @return returnData The return data of the call to the target contract.
               */
              function forwardCall(address target, bytes calldata message, SignatureECDSA calldata signature)
                  external
                  payable
                  returns (bytes memory returnData)
              {
                  address signerCache = signer;
                  if (signerCache != address(0)) {
                      if (
                              signerCache != _ecdsaRecover(
                                  _hashTypedDataV4(
                                      keccak256(abi.encode(APP_SIGNER_TYPEHASH, keccak256(message), target, _msgSender()))
                                  ),
                                  signature.v,
                                  signature.r,
                                  signature.s
                              )
                      ) {
                          revert TrustedForwarder__SignerNotAuthorized();
                      }
                  }
                  bytes memory encodedData = _encodeERC2771Context(message, _msgSender());
                  assembly {
                      let success := call(gas(), target, callvalue(), add(encodedData, 0x20), mload(encodedData), 0, 0)
                      let size := returndatasize()
                      returnData := mload(0x40)
                      mstore(returnData, size)
                      mstore(0x40, add(add(returnData, 0x20), size)) // Adjust memory pointer
                      returndatacopy(add(returnData, 0x20), 0, size) // Copy returndata to memory
                      if iszero(success) {
                          revert(add(returnData, 0x20), size) // Revert with return data on failure
                      }
                      // If the call was successful, but the return data is empty, check if the target address has code
                      if iszero(size) {
                          if iszero(extcodesize(target)) {
                              mstore(0x00, 0x39bf07c1) // Store function selector `TrustedForwarder__TargetAddressHasNoCode()` and revert
                              revert(0x1c, 0x04) // Revert with the custom function selector
                          }
                      }
                  }
              }
              /**
               * @notice Updates the app signer address. To disable app signing, set signer to address(0).
               *
               * @dev    - Throws if the sender is not the owner.
               *
               * @param signer_ The address to assign the app signer role to.
               */
              function updateSigner(address signer_) external onlyOwner {
                  if (signer_ == address(0)) {
                      revert TrustedForwarder__CannotSetAppSignerToZeroAddress();
                  }
                  signer = signer_;
              }
              /**
               * @notice Resets the app signer address to address(0).
               *
               * @dev    - Throws if the sender is not the owner.
               */
               function deactivateSigner() external onlyOwner {
                  signer = address(0);
              }
              /**
               * @notice Returns the domain separator used in the permit signature
               *
               * @return The domain separator
               */
              function domainSeparatorV4() external view returns (bytes32) {
                  return _domainSeparatorV4();
              }
              /// @dev appends the msg.sender to the end of the calldata
              function _encodeERC2771Context(bytes calldata _data, address _msgSender) internal pure returns (bytes memory encodedData) {
                  assembly  {
                      // Calculate total length: data.length + 20 bytes for the address
                      let totalLength := add(_data.length, 20)
                      // Allocate memory for the combined data
                      encodedData := mload(0x40)
                      mstore(0x40, add(encodedData, add(totalLength, 0x20)))
                      // Set the length of the `encodedData`
                      mstore(encodedData, totalLength)
                      // Copy the `bytes calldata` data
                      calldatacopy(add(encodedData, 0x20), _data.offset, _data.length)
                      // Append the `address`. Addresses are 20 bytes, stored in the last 20 bytes of a 32-byte word
                      mstore(add(add(encodedData, 0x20), _data.length), shl(96, _msgSender))
                  }
              }
              /**
               * @notice Recovers an ECDSA signature
               *
               * @dev    This function is copied from OpenZeppelin's ECDSA library
               *
               * @param digest The digest to recover
               * @param v      The v component of the signature
               * @param r      The r component of the signature
               * @param s      The s component of the signature
               *
               * @return recoveredSigner The signer of the digest
               */
              function _ecdsaRecover(bytes32 digest, uint8 v, bytes32 r, bytes32 s) internal pure returns (address recoveredSigner) {
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      revert TrustedForwarder__InvalidSignature();
                  }
                  recoveredSigner = ecrecover(digest, v, r, s);
                  if (recoveredSigner == address(0)) {
                      revert TrustedForwarder__InvalidSignature();
                  }
              }
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
          pragma solidity ^0.8.0;
          import "../utils/Context.sol";
          /**
           * @dev Contract module which provides a basic access control mechanism, where
           * there is an account (an owner) that can be granted exclusive access to
           * specific functions.
           *
           * By default, the owner account will be the one that deploys the contract. This
           * can later be changed with {transferOwnership}.
           *
           * This module is used through inheritance. It will make available the modifier
           * `onlyOwner`, which can be applied to your functions to restrict their use to
           * the owner.
           */
          abstract contract Ownable is Context {
              address private _owner;
              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
              /**
               * @dev Initializes the contract setting the deployer as the initial owner.
               */
              constructor() {
                  _transferOwnership(_msgSender());
              }
              /**
               * @dev Throws if called by any account other than the owner.
               */
              modifier onlyOwner() {
                  _checkOwner();
                  _;
              }
              /**
               * @dev Returns the address of the current owner.
               */
              function owner() public view virtual returns (address) {
                  return _owner;
              }
              /**
               * @dev Throws if the sender is not the owner.
               */
              function _checkOwner() internal view virtual {
                  require(owner() == _msgSender(), "Ownable: caller is not the owner");
              }
              /**
               * @dev Leaves the contract without owner. It will not be possible to call
               * `onlyOwner` functions. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby disabling any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                  _transferOwnership(newOwner);
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Internal function without access restriction.
               */
              function _transferOwnership(address newOwner) internal virtual {
                  address oldOwner = _owner;
                  _owner = newOwner;
                  emit OwnershipTransferred(oldOwner, newOwner);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
          pragma solidity ^0.8.2;
          import "../../utils/Address.sol";
          /**
           * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
           * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
           * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
           * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
           *
           * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
           * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
           * case an upgrade adds a module that needs to be initialized.
           *
           * For example:
           *
           * [.hljs-theme-light.nopadding]
           * ```solidity
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           *
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
               * constructor.
               *
               * Emits an {Initialized} event.
               */
              modifier initializer() {
                  bool isTopLevelCall = !_initializing;
                  require(
                      (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
                      "Initializable: contract is already initialized"
                  );
                  _initialized = 1;
                  if (isTopLevelCall) {
                      _initializing = true;
                  }
                  _;
                  if (isTopLevelCall) {
                      _initializing = false;
                      emit Initialized(1);
                  }
              }
              /**
               * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
               * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
               * used to initialize parent contracts.
               *
               * A reinitializer may be used after the original initialization step. This is essential to configure modules that
               * are added through upgrades and that require initialization.
               *
               * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
               * cannot be nested. If one is invoked in the context of another, execution will revert.
               *
               * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
               * a contract, executing them in the right order is up to the developer or operator.
               *
               * WARNING: setting the version to 255 will prevent any future reinitialization.
               *
               * Emits an {Initialized} event.
               */
              modifier reinitializer(uint8 version) {
                  require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                  _initialized = version;
                  _initializing = true;
                  _;
                  _initializing = false;
                  emit Initialized(version);
              }
              /**
               * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
               * {initializer} and {reinitializer} modifiers, directly or indirectly.
               */
              modifier onlyInitializing() {
                  require(_initializing, "Initializable: contract is not initializing");
                  _;
              }
              /**
               * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
               * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
               * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
               * through proxies.
               *
               * Emits an {Initialized} event the first time it is successfully executed.
               */
              function _disableInitializers() internal virtual {
                  require(!_initializing, "Initializable: contract is initializing");
                  if (_initialized != type(uint8).max) {
                      _initialized = type(uint8).max;
                      emit Initialized(type(uint8).max);
                  }
              }
              /**
               * @dev Returns the highest version that has been initialized. See {reinitializer}.
               */
              function _getInitializedVersion() internal view returns (uint8) {
                  return _initialized;
              }
              /**
               * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
               */
              function _isInitializing() internal view returns (bool) {
                  return _initializing;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
          pragma solidity ^0.8.8;
          import "./ECDSA.sol";
          import "../ShortStrings.sol";
          import "../../interfaces/IERC5267.sol";
          /**
           * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
           *
           * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
           * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
           * they need in their contracts using a combination of `abi.encode` and `keccak256`.
           *
           * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
           * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
           * ({_hashTypedDataV4}).
           *
           * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
           * the chain id to protect against replay attacks on an eventual fork of the chain.
           *
           * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
           * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
           *
           * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
           * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
           * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
           *
           * _Available since v3.4._
           *
           * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
           */
          abstract contract EIP712 is IERC5267 {
              using ShortStrings for *;
              bytes32 private constant _TYPE_HASH =
                  keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
              // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
              // invalidate the cached domain separator if the chain id changes.
              bytes32 private immutable _cachedDomainSeparator;
              uint256 private immutable _cachedChainId;
              address private immutable _cachedThis;
              bytes32 private immutable _hashedName;
              bytes32 private immutable _hashedVersion;
              ShortString private immutable _name;
              ShortString private immutable _version;
              string private _nameFallback;
              string private _versionFallback;
              /**
               * @dev Initializes the domain separator and parameter caches.
               *
               * The meaning of `name` and `version` is specified in
               * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
               *
               * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
               * - `version`: the current major version of the signing domain.
               *
               * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
               * contract upgrade].
               */
              constructor(string memory name, string memory version) {
                  _name = name.toShortStringWithFallback(_nameFallback);
                  _version = version.toShortStringWithFallback(_versionFallback);
                  _hashedName = keccak256(bytes(name));
                  _hashedVersion = keccak256(bytes(version));
                  _cachedChainId = block.chainid;
                  _cachedDomainSeparator = _buildDomainSeparator();
                  _cachedThis = address(this);
              }
              /**
               * @dev Returns the domain separator for the current chain.
               */
              function _domainSeparatorV4() internal view returns (bytes32) {
                  if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
                      return _cachedDomainSeparator;
                  } else {
                      return _buildDomainSeparator();
                  }
              }
              function _buildDomainSeparator() private view returns (bytes32) {
                  return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
              }
              /**
               * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
               * function returns the hash of the fully encoded EIP712 message for this domain.
               *
               * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
               *
               * ```solidity
               * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
               *     keccak256("Mail(address to,string contents)"),
               *     mailTo,
               *     keccak256(bytes(mailContents))
               * )));
               * address signer = ECDSA.recover(digest, signature);
               * ```
               */
              function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                  return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
              }
              /**
               * @dev See {EIP-5267}.
               *
               * _Available since v4.9._
               */
              function eip712Domain()
                  public
                  view
                  virtual
                  override
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  )
              {
                  return (
                      hex"0f", // 01111
                      _name.toStringWithFallback(_nameFallback),
                      _version.toStringWithFallback(_versionFallback),
                      block.chainid,
                      address(this),
                      bytes32(0),
                      new uint256[](0)
                  );
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
          pragma solidity ^0.8.0;
          import "../Strings.sol";
          /**
           * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
           *
           * These functions can be used to verify that a message was signed by the holder
           * of the private keys of a given address.
           */
          library ECDSA {
              enum RecoverError {
                  NoError,
                  InvalidSignature,
                  InvalidSignatureLength,
                  InvalidSignatureS,
                  InvalidSignatureV // Deprecated in v4.8
              }
              function _throwError(RecoverError error) private pure {
                  if (error == RecoverError.NoError) {
                      return; // no error: do nothing
                  } else if (error == RecoverError.InvalidSignature) {
                      revert("ECDSA: invalid signature");
                  } else if (error == RecoverError.InvalidSignatureLength) {
                      revert("ECDSA: invalid signature length");
                  } else if (error == RecoverError.InvalidSignatureS) {
                      revert("ECDSA: invalid signature 's' value");
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature` or error string. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               *
               * Documentation for signature generation:
               * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
               * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
                  if (signature.length == 65) {
                      bytes32 r;
                      bytes32 s;
                      uint8 v;
                      // ecrecover takes the signature parameters, and the only way to get them
                      // currently is to use assembly.
                      /// @solidity memory-safe-assembly
                      assembly {
                          r := mload(add(signature, 0x20))
                          s := mload(add(signature, 0x40))
                          v := byte(0, mload(add(signature, 0x60)))
                      }
                      return tryRecover(hash, v, r, s);
                  } else {
                      return (address(0), RecoverError.InvalidSignatureLength);
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature`. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               */
              function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, signature);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
               *
               * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
                  bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                  uint8 v = uint8((uint256(vs) >> 255) + 27);
                  return tryRecover(hash, v, r, s);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
               *
               * _Available since v4.2._
               */
              function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, r, vs);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
               * `r` and `s` signature fields separately.
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
                  // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                  // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                  // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                  // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                  //
                  // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                  // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                  // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                  // these malleable signatures as well.
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      return (address(0), RecoverError.InvalidSignatureS);
                  }
                  // If the signature is valid (and not malleable), return the signer address
                  address signer = ecrecover(hash, v, r, s);
                  if (signer == address(0)) {
                      return (address(0), RecoverError.InvalidSignature);
                  }
                  return (signer, RecoverError.NoError);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `v`,
               * `r` and `s` signature fields separately.
               */
              function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from a `hash`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
                  // 32 is the length in bytes of hash,
                  // enforced by the type signature above
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(0x00, "\\x19Ethereum Signed Message:\
          32")
                      mstore(0x1c, hash)
                      message := keccak256(0x00, 0x3c)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from `s`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
          ", Strings.toString(s.length), s));
              }
              /**
               * @dev Returns an Ethereum Signed Typed Data, created from a
               * `domainSeparator` and a `structHash`. This produces hash corresponding
               * to the one signed with the
               * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
               * JSON-RPC method as part of EIP-712.
               *
               * See {recover}.
               */
              function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      let ptr := mload(0x40)
                      mstore(ptr, "\\x19\\x01")
                      mstore(add(ptr, 0x02), domainSeparator)
                      mstore(add(ptr, 0x22), structHash)
                      data := keccak256(ptr, 0x42)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Data with intended validator, created from a
               * `validator` and `data` according to the version 0 of EIP-191.
               *
               * See {recover}.
               */
              function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
              }
          }
          // 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.9.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
          pragma solidity ^0.8.8;
          import "./StorageSlot.sol";
          // | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
          // | length  | 0x                                                              BB |
          type ShortString is bytes32;
          /**
           * @dev This library provides functions to convert short memory strings
           * into a `ShortString` type that can be used as an immutable variable.
           *
           * Strings of arbitrary length can be optimized using this library if
           * they are short enough (up to 31 bytes) by packing them with their
           * length (1 byte) in a single EVM word (32 bytes). Additionally, a
           * fallback mechanism can be used for every other case.
           *
           * Usage example:
           *
           * ```solidity
           * contract Named {
           *     using ShortStrings for *;
           *
           *     ShortString private immutable _name;
           *     string private _nameFallback;
           *
           *     constructor(string memory contractName) {
           *         _name = contractName.toShortStringWithFallback(_nameFallback);
           *     }
           *
           *     function name() external view returns (string memory) {
           *         return _name.toStringWithFallback(_nameFallback);
           *     }
           * }
           * ```
           */
          library ShortStrings {
              // Used as an identifier for strings longer than 31 bytes.
              bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
              error StringTooLong(string str);
              error InvalidShortString();
              /**
               * @dev Encode a string of at most 31 chars into a `ShortString`.
               *
               * This will trigger a `StringTooLong` error is the input string is too long.
               */
              function toShortString(string memory str) internal pure returns (ShortString) {
                  bytes memory bstr = bytes(str);
                  if (bstr.length > 31) {
                      revert StringTooLong(str);
                  }
                  return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
              }
              /**
               * @dev Decode a `ShortString` back to a "normal" string.
               */
              function toString(ShortString sstr) internal pure returns (string memory) {
                  uint256 len = byteLength(sstr);
                  // using `new string(len)` would work locally but is not memory safe.
                  string memory str = new string(32);
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(str, len)
                      mstore(add(str, 0x20), sstr)
                  }
                  return str;
              }
              /**
               * @dev Return the length of a `ShortString`.
               */
              function byteLength(ShortString sstr) internal pure returns (uint256) {
                  uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
                  if (result > 31) {
                      revert InvalidShortString();
                  }
                  return result;
              }
              /**
               * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
               */
              function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
                  if (bytes(value).length < 32) {
                      return toShortString(value);
                  } else {
                      StorageSlot.getStringSlot(store).value = value;
                      return ShortString.wrap(_FALLBACK_SENTINEL);
                  }
              }
              /**
               * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               */
              function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return toString(value);
                  } else {
                      return store;
                  }
              }
              /**
               * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               *
               * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
               * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
               */
              function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return byteLength(value);
                  } else {
                      return bytes(store).length;
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
          pragma solidity ^0.8.0;
          interface IERC5267 {
              /**
               * @dev MAY be emitted to signal that the domain could have changed.
               */
              event EIP712DomainChanged();
              /**
               * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
               * signature.
               */
              function eip712Domain()
                  external
                  view
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  );
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
          pragma solidity ^0.8.0;
          import "./math/Math.sol";
          import "./math/SignedMath.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 `int256` to its ASCII `string` decimal representation.
               */
              function toString(int256 value) internal pure returns (string memory) {
                  return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  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);
              }
              /**
               * @dev Returns true if the two strings are equal.
               */
              function equal(string memory a, string memory b) internal pure returns (bool) {
                  return keccak256(bytes(a)) == keccak256(bytes(b));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
          // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for reading and writing primitive types to specific storage slots.
           *
           * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
           * This library helps with reading and writing to such slots without the need for inline assembly.
           *
           * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
           *
           * Example usage to set ERC1967 implementation slot:
           * ```solidity
           * contract ERC1967 {
           *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
           *
           *     function _getImplementation() internal view returns (address) {
           *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
           *     }
           *
           *     function _setImplementation(address newImplementation) internal {
           *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
           *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
           *     }
           * }
           * ```
           *
           * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
           * _Available since v4.9 for `string`, `bytes`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
              struct BooleanSlot {
                  bool value;
              }
              struct Bytes32Slot {
                  bytes32 value;
              }
              struct Uint256Slot {
                  uint256 value;
              }
              struct StringSlot {
                  string value;
              }
              struct BytesSlot {
                  bytes value;
              }
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
               */
              function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
               */
              function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
               */
              function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` with member `value` located at `slot`.
               */
              function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
               */
              function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` with member `value` located at `slot`.
               */
              function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
               */
              function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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) {
                          // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                          // The surrounding unchecked block does not change this fact.
                          // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1, "Math: mulDiv overflow");
                      ///////////////////////////////////////////////
                      // 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 256, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard signed math utilities missing in the Solidity language.
           */
          library SignedMath {
              /**
               * @dev Returns the largest of two signed numbers.
               */
              function max(int256 a, int256 b) internal pure returns (int256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two signed numbers.
               */
              function min(int256 a, int256 b) internal pure returns (int256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two signed numbers without overflow.
               * The result is rounded towards zero.
               */
              function average(int256 a, int256 b) internal pure returns (int256) {
                  // Formula from the book "Hacker's Delight"
                  int256 x = (a & b) + ((a ^ b) >> 1);
                  return x + (int256(uint256(x) >> 255) & (a ^ b));
              }
              /**
               * @dev Returns the absolute unsigned value of a signed value.
               */
              function abs(int256 n) internal pure returns (uint256) {
                  unchecked {
                      // must be unchecked in order to support `n = type(int256).min`
                      return uint256(n >= 0 ? n : -n);
                  }
              }
          }
          

          File 6 of 7: ModuleTrades
          // SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "./PaymentProcessorModule.sol";
          /*
                                                               @@@@@@@@@@@@@@             
                                                              @@@@@@@@@@@@@@@@@@(         
                                                             @@@@@@@@@@@@@@@@@@@@@        
                                                            @@@@@@@@@@@@@@@@@@@@@@@@      
                                                                     #@@@@@@@@@@@@@@      
                                                                         @@@@@@@@@@@@     
                                      @@@@@@@@@@@@@@*                    @@@@@@@@@@@@     
                                     @@@@@@@@@@@@@@@     @               @@@@@@@@@@@@     
                                    @@@@@@@@@@@@@@@     @                @@@@@@@@@@@      
                                   @@@@@@@@@@@@@@@     @@               @@@@@@@@@@@@      
                                  @@@@@@@@@@@@@@@     #@@             @@@@@@@@@@@@/       
                                  @@@@@@@@@@@@@@.     @@@@@@@@@@@@@@@@@@@@@@@@@@@         
                                 @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@            
                                @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@             
                               @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@           
                              @@@@@@@@@@@@@@@     @@@@@&%%%%%%%%&&@@@@@@@@@@@@@@          
                              @@@@@@@@@@@@@@      @@@@@               @@@@@@@@@@@         
                             @@@@@@@@@@@@@@@     @@@@@                 @@@@@@@@@@@        
                            @@@@@@@@@@@@@@@     @@@@@@                 @@@@@@@@@@@        
                           @@@@@@@@@@@@@@@     @@@@@@@                 @@@@@@@@@@@        
                          @@@@@@@@@@@@@@@     @@@@@@@                 @@@@@@@@@@@&        
                          @@@@@@@@@@@@@@     *@@@@@@@               (@@@@@@@@@@@@         
                         @@@@@@@@@@@@@@@     @@@@@@@@             @@@@@@@@@@@@@@          
                        @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@           
                       @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@            
                      @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@              
                     .@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                 
                     @@@@@@@@@@@@@@%     @@@@@@@@@@@@@@@@@@@@@@@@(                        
                    @@@@@@@@@@@@@@@                                                       
                   @@@@@@@@@@@@@@@                                                        
                  @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                         
                 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                          
                 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&                                          
                @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                           
           
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          contract ModuleTrades is PaymentProcessorModule {
              constructor(address configurationContract) PaymentProcessorModule(configurationContract){}
              /**
               * @notice Executes a buy listing transaction for a single order item.
               *
               * @dev    Throws when the maker's nonce has already been used or has been cancelled.
               * @dev    Throws when the order has expired.
               * @dev    Throws when the combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when the taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when the maker's master nonce does not match the order details.
               * @dev    Throws when the order does not comply with the collection payment settings.
               * @dev    Throws when the maker's signature is invalid.
               * @dev    Throws when the order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when the maker or taker is a banned account for the collection.
               * @dev    Throws when the taker does not have or did not send sufficient funds to complete the purchase.
               * @dev    Throws when the token transfer fails for any reason such as lack of approvals or token no longer owned by maker.
               * @dev    Throws when the maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               * @dev    Any unused native token payment will be returned to the taker as wrapped native token.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Maker's nonce is marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Maker's partially fillable order state is updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. An `BuyListingERC721` event has been emitted for a ERC721 purchase.
               * @dev    6. An `BuyListingERC1155` event has been emitted for a ERC1155 purchase.
               * @dev    7. A `NonceInvalidated` event has been emitted for a ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for a ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  domainSeparator The domain separator to be used when verifying the order signature.
               * @param  saleDetails     The order execution details.
               * @param  sellerSignature The maker's signature authorizing the order execution.
               * @param  cosignature     The additional cosignature for a cosigned order, if applicable.
               * @param  feeOnTop        The additional fee to add on top of the order, paid by taker.
               */
              function buyListing(
                  bytes32 domainSeparator, 
                  Order memory saleDetails, 
                  SignatureECDSA memory sellerSignature,
                  Cosignature memory cosignature,
                  FeeOnTop memory feeOnTop
              ) public payable {
                  uint256 appendedDataLength;
                  unchecked {
                      appendedDataLength = msg.data.length - BASE_MSG_LENGTH_BUY_LISTING;
                  }
                  TradeContext memory context = TradeContext({
                      domainSeparator: domainSeparator,
                      channel: msg.sender,
                      taker: appendedDataLength == 20 ? _msgSender() : msg.sender,
                      disablePartialFill: true
                  });
                  uint256 remainingNativeProceeds = 
                      _executeOrderBuySide(
                          context,
                          msg.value,
                          saleDetails, 
                          sellerSignature,
                          cosignature,
                          feeOnTop
                      );
                  if (remainingNativeProceeds > 0) {
                      _pushProceeds(wrappedNativeCoinAddress, remainingNativeProceeds, gasleft());
                      IERC20(wrappedNativeCoinAddress).
                          transferFrom(address(this), context.taker, remainingNativeProceeds);
                  }
              }
              /**
               * @notice Executes an offer accept transaction for a single order item.
               *
               * @dev    Throws when the maker's nonce has already been used or has been cancelled.
               * @dev    Throws when the order has expired.
               * @dev    Throws when the combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when the taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when the maker's master nonce does not match the order details.
               * @dev    Throws when the order does not comply with the collection payment settings.
               * @dev    Throws when the maker's signature is invalid.
               * @dev    Throws when the order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when the maker or taker is a banned account for the collection.
               * @dev    Throws when the maker does not have sufficient funds to complete the purchase.
               * @dev    Throws when the token transfer fails for any reason such as lack of approvals or token not owned by the taker.
               * @dev    Throws when the token the offer is being accepted for does not match the conditions set by the maker.
               * @dev    Throws when the maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when the order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Maker's nonce is marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Maker's partially fillable order state is updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. An `AcceptOfferERC721` event has been emitted for a ERC721 sale.
               * @dev    6. An `AcceptOfferERC1155` event has been emitted for a ERC1155 sale.
               * @dev    7. A `NonceInvalidated` event has been emitted for a ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for a ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  domainSeparator        The domain separator to be used when verifying the order signature.
               * @param  isCollectionLevelOffer The flag to indicate if an offer is for any token in the collection.
               * @param  saleDetails            The order execution details.
               * @param  buyerSignature         The maker's signature authorizing the order execution.
               * @param  tokenSetProof          The root hash and merkle proofs for an offer that is a subset of tokens in a collection.
               * @param  cosignature            The additional cosignature for a cosigned order, if applicable.
               * @param  feeOnTop               The additional fee to add on top of the order, paid by taker.
               */
              function acceptOffer(
                  bytes32 domainSeparator, 
                  bool isCollectionLevelOffer, 
                  Order memory saleDetails, 
                  SignatureECDSA memory buyerSignature,
                  TokenSetProof memory tokenSetProof,
                  Cosignature memory cosignature,
                  FeeOnTop memory feeOnTop
              ) public {
                  uint256 appendedDataLength;
                  unchecked {
                      appendedDataLength = 
                          msg.data.length - 
                          BASE_MSG_LENGTH_ACCEPT_OFFER - 
                          (PROOF_ELEMENT_SIZE * tokenSetProof.proof.length);
                  }
                  _executeOrderSellSide(
                      TradeContext({
                          domainSeparator: domainSeparator,
                          channel: msg.sender,
                          taker: appendedDataLength == 20 ? _msgSender() : msg.sender,
                          disablePartialFill: true
                      }),
                      isCollectionLevelOffer, 
                      saleDetails, 
                      buyerSignature,
                      tokenSetProof,
                      cosignature,
                      feeOnTop);
              }
              /**
               * @notice Executes a buy listing transaction for multiple order items.
               *
               * @dev    Throws when a maker's nonce has already been used or has been cancelled.
               * @dev    Throws when any order has expired.
               * @dev    Throws when any combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when any taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when a maker's master nonce does not match the order details.
               * @dev    Throws when an order does not comply with the collection payment settings.
               * @dev    Throws when a maker's signature is invalid.
               * @dev    Throws when an order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when any maker or taker is a banned account for the collection.
               * @dev    Throws when the taker does not have or did not send sufficient funds to complete the purchase.
               * @dev    Throws when a maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               * @dev    Will NOT throw when a token fails to transfer but also will not disperse payments for failed items.
               * @dev    Any unused native token payment will be returned to the taker as wrapped native token.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Makers nonces are marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Makers partially fillable order states are updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. `BuyListingERC721` events have been emitted for each ERC721 purchase.
               * @dev    6. `BuyListingERC1155` events have been emitted for each ERC1155 purchase.
               * @dev    7. A `NonceInvalidated` event has been emitted for each ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for each ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  domainSeparator  The domain separator to be used when verifying the order signature.
               * @param  saleDetailsArray An array of order execution details.
               * @param  sellerSignatures An array of maker signatures authorizing the order execution.
               * @param  cosignatures     An array of additional cosignatures for cosigned orders, if applicable.
               * @param  feesOnTop        An array of additional fees to add on top of the orders, paid by taker.
               */
              function bulkBuyListings(
                  bytes32 domainSeparator, 
                  Order[] calldata saleDetailsArray,
                  SignatureECDSA[] calldata sellerSignatures,
                  Cosignature[] calldata cosignatures,
                  FeeOnTop[] calldata feesOnTop
              ) public payable {
                  if (saleDetailsArray.length != sellerSignatures.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (saleDetailsArray.length != cosignatures.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (saleDetailsArray.length != feesOnTop.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (saleDetailsArray.length == 0) {
                      revert PaymentProcessor__InputArrayLengthCannotBeZero();
                  }
                  uint256 remainingNativeProceeds = msg.value;
                  uint256 appendedDataLength;
                  unchecked {
                      appendedDataLength = 
                          msg.data.length - 
                          BASE_MSG_LENGTH_BULK_BUY_LISTINGS - 
                          (BASE_MSG_LENGTH_BULK_BUY_LISTINGS_PER_ITEM * saleDetailsArray.length);
                  }
                  TradeContext memory context = TradeContext({
                      domainSeparator: domainSeparator,
                      channel: msg.sender,
                      taker: appendedDataLength == 20 ? _msgSender() : msg.sender,
                      disablePartialFill: false
                  });
                  Order memory saleDetails;
                  SignatureECDSA memory sellerSignature;
                  Cosignature memory cosignature;
                  FeeOnTop memory feeOnTop;
                  for (uint256 i = 0; i < saleDetailsArray.length;) {
                      saleDetails = saleDetailsArray[i];
                      sellerSignature = sellerSignatures[i];
                      cosignature = cosignatures[i];
                      feeOnTop = feesOnTop[i];
                      if(saleDetails.paymentMethod == address(0)) {
                          remainingNativeProceeds = 
                              _executeOrderBuySide(
                                  context, 
                                  remainingNativeProceeds, 
                                  saleDetails, 
                                  sellerSignature, 
                                  cosignature, 
                                  feeOnTop);
                      } else {
                          _executeOrderBuySide(context, 0, saleDetails, sellerSignature, cosignature, feeOnTop);
                      }
                      unchecked {
                          ++i;
                      }
                  }
                  if (remainingNativeProceeds > 0) {
                      _pushProceeds(wrappedNativeCoinAddress, remainingNativeProceeds, gasleft());
                      IERC20(wrappedNativeCoinAddress).
                          transferFrom(address(this), context.taker, remainingNativeProceeds);
                  }
              }
              /**
               * @notice Executes an accept offer transaction for multiple order items.
               *
               * @dev    Throws when a maker's nonce has already been used or has been cancelled.
               * @dev    Throws when any order has expired.
               * @dev    Throws when any combined marketplace and royalty fee exceeds 100%.
               * @dev    Throws when any taker fee on top exceeds 100% of the item sale price.
               * @dev    Throws when a maker's master nonce does not match the order details.
               * @dev    Throws when an order does not comply with the collection payment settings.
               * @dev    Throws when a maker's signature is invalid.
               * @dev    Throws when an order is a cosigned order and the cosignature is invalid.
               * @dev    Throws when the transaction originates from an untrusted channel if untrusted channels are blocked.
               * @dev    Throws when any maker or taker is a banned account for the collection.
               * @dev    Throws when a maker does not have sufficient funds to complete the purchase.
               * @dev    Throws when the token an offer is being accepted for does not match the conditions set by the maker.
               * @dev    Throws when a maker has revoked the order digest on a ERC1155_PARTIAL_FILL order.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the item price is not evenly divisible by the amount.
               * @dev    Throws when an order is an ERC1155_PARTIAL_FILL order and the remaining fillable quantity is less than the requested minimum fill amount.
               * @dev    Will NOT throw when a token fails to transfer but also will not disperse payments for failed items.
               *
               * @dev    <h4>Postconditions:</h4>
               * @dev    1. Payment amounts and fees are sent to their respective recipients.
               * @dev    2. Purchased tokens are sent to the beneficiary.
               * @dev    3. Makers nonces are marked as used for ERC721_FILL_OR_KILL and ERC1155_FILL_OR_KILL orders.
               * @dev    4. Makers partially fillable order states are updated for ERC1155_PARTIAL_FILL orders.
               * @dev    5. `AcceptOfferERC721` events have been emitted for each ERC721 sale.
               * @dev    6. `AcceptOfferERC1155` events have been emitted for each ERC1155 sale.
               * @dev    7. A `NonceInvalidated` event has been emitted for each ERC721_FILL_OR_KILL or ERC1155_FILL_OR_KILL order.
               * @dev    8. A `OrderDigestInvalidated` event has been emitted for each ERC1155_PARTIAL_FILL order, if fully filled.
               *
               * @param  domainSeparator The domain separator to be used when verifying the order signature.
               * @param  params          The parameters for the bulk offers being accepted.
               */
              function bulkAcceptOffers(
                  bytes32 domainSeparator, 
                  BulkAcceptOffersParams memory params
              ) public {
                  if (params.saleDetailsArray.length != params.isCollectionLevelOfferArray.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (params.saleDetailsArray.length != params.buyerSignaturesArray.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (params.saleDetailsArray.length != params.tokenSetProofsArray.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (params.saleDetailsArray.length != params.cosignaturesArray.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (params.saleDetailsArray.length != params.feesOnTopArray.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (params.saleDetailsArray.length == 0) {
                      revert PaymentProcessor__InputArrayLengthCannotBeZero();
                  }
                  uint256 appendedDataLength;
                  unchecked {
                      appendedDataLength = 
                          msg.data.length - 
                          BASE_MSG_LENGTH_BULK_ACCEPT_OFFERS - 
                          (BASE_MSG_LENGTH_BULK_ACCEPT_OFFERS_PER_ITEM * params.saleDetailsArray.length);
                      for (uint256 i = 0; i < params.tokenSetProofsArray.length;) {
                          appendedDataLength -= PROOF_ELEMENT_SIZE * params.tokenSetProofsArray[i].proof.length;
                          ++i;
                      }
                  }
                  TradeContext memory context = TradeContext({
                      domainSeparator: domainSeparator,
                      channel: msg.sender,
                      taker: appendedDataLength == 20 ? _msgSender() : msg.sender,
                      disablePartialFill: false
                  });
                  for (uint256 i = 0; i < params.saleDetailsArray.length;) {
                      _executeOrderSellSide(
                          context,
                          params.isCollectionLevelOfferArray[i], 
                          params.saleDetailsArray[i], 
                          params.buyerSignaturesArray[i],
                          params.tokenSetProofsArray[i],
                          params.cosignaturesArray[i],
                          params.feesOnTopArray[i]);
                      unchecked {
                          ++i;
                      }
                  }
              }
          }
          // SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "../IOwnable.sol";
          import "../interfaces/IPaymentProcessorConfiguration.sol";
          import "../interfaces/IPaymentProcessorEvents.sol";
          import "../storage/PaymentProcessorStorageAccess.sol";
          import "../Constants.sol";
          import "../Errors.sol";
          import "@openzeppelin/contracts/access/IAccessControl.sol";
          import "@openzeppelin/contracts/interfaces/IERC1271.sol";
          import "@openzeppelin/contracts/interfaces/IERC2981.sol";
          import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
          import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
          import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
          import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
          import {TrustedForwarderERC2771Context} from "@limitbreak/trusted-forwarder/TrustedForwarderERC2771Context.sol";
          /*
                                                               @@@@@@@@@@@@@@             
                                                              @@@@@@@@@@@@@@@@@@(         
                                                             @@@@@@@@@@@@@@@@@@@@@        
                                                            @@@@@@@@@@@@@@@@@@@@@@@@      
                                                                     #@@@@@@@@@@@@@@      
                                                                         @@@@@@@@@@@@     
                                      @@@@@@@@@@@@@@*                    @@@@@@@@@@@@     
                                     @@@@@@@@@@@@@@@     @               @@@@@@@@@@@@     
                                    @@@@@@@@@@@@@@@     @                @@@@@@@@@@@      
                                   @@@@@@@@@@@@@@@     @@               @@@@@@@@@@@@      
                                  @@@@@@@@@@@@@@@     #@@             @@@@@@@@@@@@/       
                                  @@@@@@@@@@@@@@.     @@@@@@@@@@@@@@@@@@@@@@@@@@@         
                                 @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@            
                                @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@             
                               @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@           
                              @@@@@@@@@@@@@@@     @@@@@&%%%%%%%%&&@@@@@@@@@@@@@@          
                              @@@@@@@@@@@@@@      @@@@@               @@@@@@@@@@@         
                             @@@@@@@@@@@@@@@     @@@@@                 @@@@@@@@@@@        
                            @@@@@@@@@@@@@@@     @@@@@@                 @@@@@@@@@@@        
                           @@@@@@@@@@@@@@@     @@@@@@@                 @@@@@@@@@@@        
                          @@@@@@@@@@@@@@@     @@@@@@@                 @@@@@@@@@@@&        
                          @@@@@@@@@@@@@@     *@@@@@@@               (@@@@@@@@@@@@         
                         @@@@@@@@@@@@@@@     @@@@@@@@             @@@@@@@@@@@@@@          
                        @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@           
                       @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@            
                      @@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@              
                     .@@@@@@@@@@@@@@     @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                 
                     @@@@@@@@@@@@@@%     @@@@@@@@@@@@@@@@@@@@@@@@(                        
                    @@@@@@@@@@@@@@@                                                       
                   @@@@@@@@@@@@@@@                                                        
                  @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                         
                 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                          
                 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&                                          
                @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                                           
           
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          abstract contract PaymentProcessorModule is 
              TrustedForwarderERC2771Context, 
              PaymentProcessorStorageAccess, 
              IPaymentProcessorEvents {
              using EnumerableSet for EnumerableSet.AddressSet;
              // Recommendations For Default Immutable Payment Methods Per Chain
              // Default Payment Method 1: Wrapped Native Coin
              // Default Payment Method 2: Wrapped ETH
              // Default Payment Method 3: USDC (Native)
              // Default Payment Method 4: USDC (Bridged)
              /// @dev The amount of gas units to be supplied with native token transfers.
              uint256 private immutable pushPaymentGasLimit;
              /// @dev The address of the ERC20 contract used for wrapped native token.
              address public immutable wrappedNativeCoinAddress;
              /// @dev The first default payment method defined at contract deployment. Immutable to save SLOAD cost.
              address private immutable defaultPaymentMethod1;
              /// @dev The second default payment method defined at contract deployment. Immutable to save SLOAD cost.
              address private immutable defaultPaymentMethod2;
              /// @dev The third default payment method defined at contract deployment. Immutable to save SLOAD cost.
              address private immutable defaultPaymentMethod3;
              /// @dev The fourth default payment method defined at contract deployment. Immutable to save SLOAD cost.
              address private immutable defaultPaymentMethod4;
              constructor(address configurationContract)
              TrustedForwarderERC2771Context(
                  IPaymentProcessorConfiguration(configurationContract).getPaymentProcessorModuleERC2771ContextParams()
              ) {
                  (
                      uint32 pushPaymentGasLimit_,
                      address wrappedNativeCoinAddress_,
                      DefaultPaymentMethods memory defaultPaymentMethods
                  ) = IPaymentProcessorConfiguration(configurationContract).getPaymentProcessorModuleDeploymentParams();
                  
                  if (pushPaymentGasLimit_ == 0 || wrappedNativeCoinAddress_ == address(0)) {
                      revert PaymentProcessor__InvalidConstructorArguments();
                  }
                  pushPaymentGasLimit = pushPaymentGasLimit_;
                  wrappedNativeCoinAddress = wrappedNativeCoinAddress_;
                  defaultPaymentMethod1 = defaultPaymentMethods.defaultPaymentMethod1;
                  defaultPaymentMethod2 = defaultPaymentMethods.defaultPaymentMethod2;
                  defaultPaymentMethod3 = defaultPaymentMethods.defaultPaymentMethod3;
                  defaultPaymentMethod4 = defaultPaymentMethods.defaultPaymentMethod4;
              }
              /*************************************************************************/
              /*                        Default Payment Methods                        */
              /*************************************************************************/
              /**
               * @notice Returns true if `paymentMethod` is a default payment method.
               * 
               * @dev    This function will return true if the default payment method was added after contract deployment.
               */
              function _isDefaultPaymentMethod(address paymentMethod) internal view returns (bool) {
                  if (paymentMethod == address(0)) {
                      return true;
                  } else if (paymentMethod == defaultPaymentMethod1) {
                      return true;
                  } else if (paymentMethod == defaultPaymentMethod2) {
                      return true;
                  } else if (paymentMethod == defaultPaymentMethod3) {
                      return true;
                  } else if (paymentMethod == defaultPaymentMethod4) {
                      return true;
                  } else {
                      // If it isn't one of the gas efficient immutable default payment methods,
                      // it may have bee added to the fallback default payment method whitelist,
                      // but there are SLOAD costs.
                      return appStorage().collectionPaymentMethodWhitelists[DEFAULT_PAYMENT_METHOD_WHITELIST_ID].contains(paymentMethod);
                  }
              }
              /**
               * @notice Returns an array of the default payment methods defined at contract deployment.
               * 
               * @dev    This array will **NOT** include default payment methods added after contract deployment.
               */
              function _getDefaultPaymentMethods() internal view returns (address[] memory) {
                  address[] memory defaultPaymentMethods = new address[](5);
                  defaultPaymentMethods[0] = address(0);
                  defaultPaymentMethods[1] = defaultPaymentMethod1;
                  defaultPaymentMethods[2] = defaultPaymentMethod2;
                  defaultPaymentMethods[3] = defaultPaymentMethod3;
                  defaultPaymentMethods[4] = defaultPaymentMethod4;
                  return defaultPaymentMethods;
              }
              /*************************************************************************/
              /*                            Order Execution                            */
              /*************************************************************************/
              /**
               * @notice Checks order validation and fulfills a buy listing order.
               * 
               * @dev    This function may be called multiple times during a bulk execution.
               * @dev    Throws when a partial fill order is not equally divisible by the number of items in the order.
               * 
               * @param context             The current execution context to determine the taker.
               * @param startingNativeFunds The amount of native funds available at the beginning of the order execution.
               * @param saleDetails         The order execution details.
               * @param signedSellOrder     The maker's signature authorizing the order execution.
               * @param cosignature         The additional cosignature for a cosigned order, if applicable.
               * @param feeOnTop            The additional fee to add on top of the order, paid by taker.
               * 
               * @return endingNativeFunds  The amount of native funds available at the end of the order execution.
               */
              function _executeOrderBuySide(
                  TradeContext memory context,
                  uint256 startingNativeFunds,
                  Order memory saleDetails,
                  SignatureECDSA memory signedSellOrder,
                  Cosignature memory cosignature,
                  FeeOnTop memory feeOnTop
              ) internal returns (uint256 endingNativeFunds) {
                  uint248 quantityToFill = _verifySaleApproval(
                      context, 
                      saleDetails, 
                      signedSellOrder, 
                      cosignature);
                  if (quantityToFill != saleDetails.amount) {
                      if (saleDetails.itemPrice % saleDetails.amount != 0) {
                          revert PaymentProcessor__PartialFillsNotSupportedForNonDivisibleItems();
                      }
                      saleDetails.itemPrice = saleDetails.itemPrice / saleDetails.amount * quantityToFill;
                      saleDetails.amount = quantityToFill;
                  }
                  RoyaltyBackfillAndBounty memory royaltyBackfillAndBounty = _validateBasicOrderDetails(context, saleDetails);
                  endingNativeFunds = _fulfillSingleOrderWithFeeOnTop(
                      startingNativeFunds,
                      context,
                      context.taker,
                      saleDetails.maker,
                      IERC20(saleDetails.paymentMethod),
                      _getOrderFulfillmentFunctionPointers(Sides.Buy, saleDetails.paymentMethod, saleDetails.protocol),
                      saleDetails,
                      royaltyBackfillAndBounty,
                      feeOnTop);
              }
              /**
               * @notice Checks order validation and fulfills an offer acceptance.
               * 
               * @dev    This function may be called multiple times during a bulk execution.
               * @dev    Throws when the payment method is the chain native token.
               * @dev    Throws when the supplied token for a token set offer cannot be validated with the root hash and proof.
               * @dev    Throws when a partial fill order is not equally divisible by the number of items in the order.
               * 
               * @param context                The current execution context to determine the taker.
               * @param  isCollectionLevelOrder The flag to indicate if an offer is for any token in the collection.
               * @param  saleDetails            The order execution details.
               * @param  buyerSignature         The maker's signature authorizing the order execution.
               * @param  tokenSetProof          The root hash and merkle proofs for an offer that is a subset of tokens in a collection.
               * @param  cosignature            The additional cosignature for a cosigned order, if applicable.
               * @param  feeOnTop               The additional fee to add on top of the order, paid by taker.
               */
              function _executeOrderSellSide(
                  TradeContext memory context,
                  bool isCollectionLevelOrder, 
                  Order memory saleDetails,
                  SignatureECDSA memory buyerSignature,
                  TokenSetProof memory tokenSetProof,
                  Cosignature memory cosignature,
                  FeeOnTop memory feeOnTop
              ) internal {
                  if (saleDetails.paymentMethod == address(0)) {
                      revert PaymentProcessor__BadPaymentMethod();
                  }
                  uint248 quantityToFill;
                  if (isCollectionLevelOrder) {
                      if (tokenSetProof.rootHash == bytes32(0)) {
                          quantityToFill = _verifyCollectionOffer(
                              context, 
                              saleDetails, 
                              buyerSignature, 
                              cosignature);
                      } else {
                          if(!MerkleProof.verify(
                              tokenSetProof.proof, 
                              tokenSetProof.rootHash, 
                              keccak256(abi.encode(saleDetails.tokenAddress, saleDetails.tokenId)))) {
                              revert PaymentProcessor__IncorrectTokenSetMerkleProof();
                          }
                          quantityToFill = _verifyTokenSetOffer(
                              context, 
                              saleDetails, 
                              buyerSignature, 
                              tokenSetProof, 
                              cosignature);
                      }
                  } else {
                      quantityToFill = _verifyItemOffer(
                          context,
                          saleDetails, 
                          buyerSignature, 
                          cosignature);
                  }
                  if (quantityToFill != saleDetails.amount) {
                      if (saleDetails.itemPrice % saleDetails.amount != 0) {
                          revert PaymentProcessor__PartialFillsNotSupportedForNonDivisibleItems();
                      }
                      
                      saleDetails.itemPrice = saleDetails.itemPrice / saleDetails.amount * quantityToFill;
                      saleDetails.amount = quantityToFill;
                  }
                  RoyaltyBackfillAndBounty memory royaltyBackfillAndBounty = _validateBasicOrderDetails(context, saleDetails);
                  _fulfillSingleOrderWithFeeOnTop(
                      0,
                      context,
                      saleDetails.maker,
                      context.taker,
                      IERC20(saleDetails.paymentMethod),
                      _getOrderFulfillmentFunctionPointers(Sides.Sell, saleDetails.paymentMethod, saleDetails.protocol),
                      saleDetails,
                      royaltyBackfillAndBounty,
                      feeOnTop);
              }
              /**
               * @notice Checks order validation and fulfills a sweep order.
               * 
               * @dev    Throws when the order protocol is for ERC1155 partial fills.
               * @dev    Throws when the `items`, `signedSellOrders` and `cosignatures` arrays have different lengths.
               * @dev    Throws when the `items` array length is zero.
               * 
               * @param context             The current execution context to determine the taker.
               * @param startingNativeFunds The amount of native funds available at the beginning of the order execution.
               * @param feeOnTop            The additional fee to add on top of the orders, paid by taker.
               * @param sweepOrder          The order information that is common to all items in the sweep.
               * @param items               An array of items that contains the order information unique to each item.
               * @param signedSellOrders    An array of maker signatures authorizing the order execution.
               * @param cosignatures        An array of additional cosignatures for cosigned orders, if applicable.
               * 
               * @return endingNativeFunds  The amount of native funds available at the end of the order execution.
               */
              function _executeSweepOrder(
                  TradeContext memory context,
                  uint256 startingNativeFunds,
                  FeeOnTop memory feeOnTop,
                  SweepOrder memory sweepOrder,
                  SweepItem[] memory items,
                  SignatureECDSA[] memory signedSellOrders,
                  Cosignature[] memory cosignatures
              ) internal returns (uint256 endingNativeFunds) {
                  if (sweepOrder.protocol == OrderProtocols.ERC1155_FILL_PARTIAL) {
                      revert PaymentProcessor__OrderProtocolERC1155FillPartialUnsupportedInSweeps();
                  }
                  if (items.length != signedSellOrders.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (items.length != cosignatures.length) {
                      revert PaymentProcessor__InputArrayLengthMismatch();
                  }
                  if (items.length == 0) {
                      revert PaymentProcessor__InputArrayLengthCannotBeZero();
                  }
                  (Order[] memory saleDetailsBatch, RoyaltyBackfillAndBounty memory royaltyBackfillAndBounty) = 
                      _validateSweepOrder(
                          context,
                          feeOnTop,
                          sweepOrder,
                          items,
                          signedSellOrders,
                          cosignatures
                      );
                  endingNativeFunds = _fulfillSweepOrderWithFeeOnTop(
                      context,
                      startingNativeFunds,
                      SweepCollectionComputeAndDistributeProceedsParams({
                          paymentCoin: IERC20(sweepOrder.paymentMethod),
                          fnPointers: _getOrderFulfillmentFunctionPointers(
                              Sides.Buy, 
                              sweepOrder.paymentMethod, 
                              sweepOrder.protocol),
                          feeOnTop: feeOnTop,
                          royaltyBackfillAndBounty: royaltyBackfillAndBounty,
                          saleDetailsBatch: saleDetailsBatch
                      })
                  );
              }
              /*************************************************************************/
              /*                           Order Validation                            */
              /*************************************************************************/
              /**
               * @notice Loads collection payment settings to validate a single item order.
               * 
               * @dev    This function may be called multiple times during a bulk execution.
               * @dev    Throws when a collection is set to block untrusted channels and the transaction originates 
               * @dev    from an untrusted channel.
               * @dev    Throws when the maker or taker is a banned account for the collection.
               * @dev    Throws when the payment method is not an allowed payment method.
               * @dev    Throws when the sweep order is for ERC721 tokens and the amount is set to a value other than one.
               * @dev    Throws when the sweep order is for ERC1155 tokens and the amount is set to zero.
               * @dev    Throws when the marketplace fee and maximum royalty fee will exceed the sales price of an item.
               * @dev    Throws when the current block time is greater than the order expiration.
               * 
               * @param context     The current execution context to determine the taker.
               * @param saleDetails The order execution details.
               * 
               * @return royaltyBackfillAndBounty The on-chain royalty backfill and bounty information defined by the creator.
               */
              function _validateBasicOrderDetails(
                  TradeContext memory context,
                  Order memory saleDetails
              ) private view returns (RoyaltyBackfillAndBounty memory royaltyBackfillAndBounty) {
                  if (saleDetails.protocol == OrderProtocols.ERC721_FILL_OR_KILL) {
                      if (saleDetails.amount != ONE) {
                          revert PaymentProcessor__AmountForERC721SalesMustEqualOne();
                      }
                  } else {
                      if (saleDetails.amount == 0) {
                          revert PaymentProcessor__AmountForERC1155SalesGreaterThanZero();
                      }
                  }
                  if (block.timestamp > saleDetails.expiration) {
                      revert PaymentProcessor__OrderHasExpired();
                  }
                  if (saleDetails.marketplaceFeeNumerator + saleDetails.maxRoyaltyFeeNumerator > FEE_DENOMINATOR) {
                      revert PaymentProcessor__MarketplaceAndRoyaltyFeesWillExceedSalePrice();
                  }
                  CollectionPaymentSettings storage paymentSettingsForCollection = 
                      appStorage().collectionPaymentSettings[saleDetails.tokenAddress];
                  PaymentSettings paymentSettings = paymentSettingsForCollection.paymentSettings;
                  royaltyBackfillAndBounty.backfillNumerator = paymentSettingsForCollection.royaltyBackfillNumerator;
                  royaltyBackfillAndBounty.bountyNumerator = paymentSettingsForCollection.royaltyBountyNumerator;
                  if (paymentSettingsForCollection.blockBannedAccounts) {
                      EnumerableSet.AddressSet storage bannedAccounts = 
                          appStorage().collectionBannedAccounts[saleDetails.tokenAddress];
                      if (bannedAccounts.contains(saleDetails.maker)) {
                          revert PaymentProcessor__MakerOrTakerIsBannedAccount();
                      }
                      if (bannedAccounts.contains(context.taker)) {
                          revert PaymentProcessor__MakerOrTakerIsBannedAccount();
                      }
                  }
                  if (paymentSettingsForCollection.blockTradesFromUntrustedChannels) {
                      EnumerableSet.AddressSet storage trustedChannels = 
                          appStorage().collectionTrustedChannels[saleDetails.tokenAddress];
                      if (trustedChannels.length() > 0) {
                          if (!trustedChannels.contains(context.channel)) {
                              revert PaymentProcessor__TradeOriginatedFromUntrustedChannel();
                          }
                      }
                  }
                  if (paymentSettingsForCollection.royaltyBackfillNumerator > 0) {
                      royaltyBackfillAndBounty.backfillReceiver = 
                          appStorage().collectionRoyaltyBackfillReceivers[saleDetails.tokenAddress];
                  }
                  if (paymentSettingsForCollection.isRoyaltyBountyExclusive) {
                      royaltyBackfillAndBounty.exclusiveMarketplace = 
                          appStorage().collectionExclusiveBountyReceivers[saleDetails.tokenAddress];
                  }
                  
                  if (paymentSettings == PaymentSettings.DefaultPaymentMethodWhitelist) {
                      if (!_isDefaultPaymentMethod(saleDetails.paymentMethod)) {
                          revert PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
                      }
                  } else if (paymentSettings == PaymentSettings.CustomPaymentMethodWhitelist) {
                      if (!appStorage().collectionPaymentMethodWhitelists[paymentSettingsForCollection.paymentMethodWhitelistId].contains(saleDetails.paymentMethod)) {
                          revert PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
                      }
                  } else if (paymentSettings == PaymentSettings.PricingConstraints) {
                      if (paymentSettingsForCollection.constrainedPricingPaymentMethod != saleDetails.paymentMethod) {
                          revert PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
                      }
                      _validateSalePriceInRange(
                          saleDetails.tokenAddress, 
                          saleDetails.tokenId, 
                          saleDetails.amount, 
                          saleDetails.itemPrice);
                  } else if (paymentSettings == PaymentSettings.Paused) {
                      revert PaymentProcessor__TradingIsPausedForCollection();
                  }
              }
              /**
               * @notice Loads collection payment settings to validate a sweep order.
               * 
               * @dev    Throws when a collection is set to block untrusted channels and the transaction originates 
               * @dev    from an untrusted channel.
               * @dev    Throws when the payment method is not an allowed payment method.
               * @dev    Throws when the sweep order is for ERC721 tokens and the amount is set to a value other than one.
               * @dev    Throws when the sweep order is for ERC1155 tokens and the amount is set to zero.
               * @dev    Throws when the marketplace fee and maximum royalty fee will exceed the sales price of an item.
               * @dev    Throws when the current block time is greater than the order expiration.
               * @dev    Throws when the fee on top amount exceeds the sum of all items.
               * 
               * @param context          The current execution context to determine the taker.
               * @param feeOnTop         The additional fee to add on top of the orders, paid by taker.
               * @param sweepOrder       The order information that is common to all items in the sweep.
               * @param items            An array of items that contains the order information unique to each item.
               * @param signedSellOrders An array of maker signatures authorizing the order execution.
               * @param cosignatures     An array of additional cosignatures for cosigned orders, if applicable.
               * 
               * @return saleDetailsBatch         An array of order execution details.
               * @return royaltyBackfillAndBounty The on-chain royalty backfill and bounty information defined by the creator.
               */
              function _validateSweepOrder(
                  TradeContext memory context,
                  FeeOnTop memory feeOnTop,
                  SweepOrder memory sweepOrder,
                  SweepItem[] memory items,
                  SignatureECDSA[] memory signedSellOrders,
                  Cosignature[] memory cosignatures
              ) private returns (Order[] memory saleDetailsBatch, RoyaltyBackfillAndBounty memory royaltyBackfillAndBounty) {
                  CollectionPaymentSettings storage paymentSettingsForCollection = 
                      appStorage().collectionPaymentSettings[sweepOrder.tokenAddress];
                  PaymentSettings paymentSettings = paymentSettingsForCollection.paymentSettings;
                  royaltyBackfillAndBounty.backfillNumerator = paymentSettingsForCollection.royaltyBackfillNumerator;
                  royaltyBackfillAndBounty.bountyNumerator = paymentSettingsForCollection.royaltyBountyNumerator;
                  if (paymentSettingsForCollection.blockTradesFromUntrustedChannels) {
                      EnumerableSet.AddressSet storage trustedChannels = 
                          appStorage().collectionTrustedChannels[sweepOrder.tokenAddress];
                      if (trustedChannels.length() > 0) {
                          if (!trustedChannels.contains(context.channel)) {
                              revert PaymentProcessor__TradeOriginatedFromUntrustedChannel();
                          }
                      }
                  }
                  if (paymentSettingsForCollection.royaltyBackfillNumerator > 0) {
                      royaltyBackfillAndBounty.backfillReceiver = 
                          appStorage().collectionRoyaltyBackfillReceivers[sweepOrder.tokenAddress];
                  }
                  if (paymentSettingsForCollection.isRoyaltyBountyExclusive) {
                      royaltyBackfillAndBounty.exclusiveMarketplace = 
                          appStorage().collectionExclusiveBountyReceivers[sweepOrder.tokenAddress];
                  }
                  if (paymentSettings == PaymentSettings.DefaultPaymentMethodWhitelist) {
                      if (!_isDefaultPaymentMethod(sweepOrder.paymentMethod)) {
                          revert PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
                      }
                  } else if (paymentSettings == PaymentSettings.CustomPaymentMethodWhitelist) {
                      if (!appStorage().collectionPaymentMethodWhitelists[paymentSettingsForCollection.paymentMethodWhitelistId].contains(sweepOrder.paymentMethod)) {
                          revert PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
                      }
                  } else if (paymentSettings == PaymentSettings.PricingConstraints) {
                      if (paymentSettingsForCollection.constrainedPricingPaymentMethod != sweepOrder.paymentMethod) {
                          revert PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
                      }
                  } else if (paymentSettings == PaymentSettings.Paused) {
                      revert PaymentProcessor__TradingIsPausedForCollection();
                  }
                  EnumerableSet.AddressSet storage bannedAccounts = 
                      appStorage().collectionBannedAccounts[sweepOrder.tokenAddress];
                  if (paymentSettingsForCollection.blockBannedAccounts) {
                      if (bannedAccounts.contains(context.taker)) {
                          revert PaymentProcessor__MakerOrTakerIsBannedAccount();
                      }
                  }
                  uint256 itemsLength = items.length;
                  saleDetailsBatch = new Order[](itemsLength);
                  uint256 sumListingPrices;
                  for (uint256 i = 0; i < itemsLength;) {
                      Order memory saleDetails = 
                          Order({
                              protocol: sweepOrder.protocol,
                              maker: items[i].maker,
                              beneficiary: sweepOrder.beneficiary,
                              marketplace: items[i].marketplace,
                              fallbackRoyaltyRecipient: items[i].fallbackRoyaltyRecipient,
                              paymentMethod: sweepOrder.paymentMethod,
                              tokenAddress: sweepOrder.tokenAddress,
                              tokenId: items[i].tokenId,
                              amount: items[i].amount,
                              itemPrice: items[i].itemPrice,
                              nonce: items[i].nonce,
                              expiration: items[i].expiration,
                              marketplaceFeeNumerator: items[i].marketplaceFeeNumerator,
                              maxRoyaltyFeeNumerator: items[i].maxRoyaltyFeeNumerator,
                              requestedFillAmount: items[i].amount,
                              minimumFillAmount: items[i].amount
                          });
                      saleDetailsBatch[i] = saleDetails;
                      sumListingPrices += saleDetails.itemPrice;
                      if (paymentSettingsForCollection.blockBannedAccounts) {
                          if (bannedAccounts.contains(saleDetails.maker)) {
                              revert PaymentProcessor__MakerOrTakerIsBannedAccount();
                          }
                      }
                      if (saleDetails.protocol == OrderProtocols.ERC721_FILL_OR_KILL) {
                          if (saleDetails.amount != ONE) {
                              revert PaymentProcessor__AmountForERC721SalesMustEqualOne();
                          }
                      } else {
                          if (saleDetails.amount == 0) {
                              revert PaymentProcessor__AmountForERC1155SalesGreaterThanZero();
                          }
                      }
                      if (saleDetails.marketplaceFeeNumerator + saleDetails.maxRoyaltyFeeNumerator > FEE_DENOMINATOR) {
                          revert PaymentProcessor__MarketplaceAndRoyaltyFeesWillExceedSalePrice();
                      }
                      if (paymentSettings == PaymentSettings.PricingConstraints) {
                          _validateSalePriceInRange(
                              saleDetails.tokenAddress, 
                              saleDetails.tokenId, 
                              saleDetails.amount, 
                              saleDetails.itemPrice);
                      }
                      if (block.timestamp > saleDetails.expiration) {
                              revert PaymentProcessor__OrderHasExpired();
                      }
                      _verifySaleApproval(context, saleDetails, signedSellOrders[i], cosignatures[i]);
                      unchecked {
                          ++i;
                      }
                  }
                  if (feeOnTop.amount > sumListingPrices) {
                      revert PaymentProcessor__FeeOnTopCannotBeGreaterThanItemPrice();
                  }
              }
              /**
               * @notice Validates the sales price for a token is within the bounds set.
               * 
               * @dev    Throws when the unit price is above the ceiling bound.
               * @dev    Throws when the unit price is below the floor bound.
               * 
               * @param tokenAddress The contract address for the token.
               * @param tokenId      The token id.
               * @param amount       The quantity of the token being transacted.
               * @param salePrice    The total price for the token quantity.
               */
              function _validateSalePriceInRange(
                  address tokenAddress, 
                  uint256 tokenId, 
                  uint256 amount, 
                  uint256 salePrice
              ) private view {
                  (uint256 floorPrice, uint256 ceilingPrice) = _getFloorAndCeilingPrices(tokenAddress, tokenId);
                  unchecked {
                      uint256 unitPrice = salePrice / amount;
                      if (unitPrice > ceilingPrice) {
                          revert PaymentProcessor__SalePriceAboveMaximumCeiling();
                      }
                      if (unitPrice < floorPrice) {
                          revert PaymentProcessor__SalePriceBelowMinimumFloor();
                      }
                  }
              }
              /**
               * @notice Returns the floor and ceiling price for a token for collections set to use pricing constraints.
               * 
               * @dev    Returns token pricing bounds if token bounds are set. 
               * @dev    If token bounds are not set then returns collection pricing bounds if they are set.
               * @dev    If collection bounds are not set, returns zero floor bound and uint256 max ceiling bound.
               * 
               * @param tokenAddress The contract address for the token.
               * @param tokenId      The token id.
               */
              function _getFloorAndCeilingPrices(
                  address tokenAddress, 
                  uint256 tokenId
              ) internal view returns (uint256, uint256) {
                  PricingBounds memory tokenLevelPricingBounds = appStorage().tokenPricingBounds[tokenAddress][tokenId];
                  if (tokenLevelPricingBounds.isSet) {
                      return (tokenLevelPricingBounds.floorPrice, tokenLevelPricingBounds.ceilingPrice);
                  } else {
                      PricingBounds memory collectionLevelPricingBounds = appStorage().collectionPricingBounds[tokenAddress];
                      if (collectionLevelPricingBounds.isSet) {
                          return (collectionLevelPricingBounds.floorPrice, collectionLevelPricingBounds.ceilingPrice);
                      }
                  }
                  return (0, type(uint256).max);
              }
              /*************************************************************************/
              /*                           Order Fulfillment                           */
              /*************************************************************************/
              /**
               * @notice Dispenses tokens and proceeds for a single order.
               * 
               * @dev    This function may be called multiple times during a bulk execution.
               * @dev    Throws when a token false to dispense AND partial fills are disabled.
               * @dev    Throws when the taker did not supply enough native funds.
               * @dev    Throws when the fee on top amount is greater than the item price.
               * 
               * @param startingNativeFunds      The amount of native funds remaining at the beginning of the function call.
               * @param context                  The current execution context to determine the taker.
               * @param purchaser                The user that is buying the token.
               * @param seller                   The user that is selling the token.
               * @param paymentCoin              The ERC20 token used for payment, will be zero values for chain native token.
               * @param fnPointers               Struct containing the function pointers for dispensing tokens, sending payments
               *                                 and emitting events.
               * @param saleDetails              The order execution details.
               * @param royaltyBackfillAndBounty Struct containing the royalty backfill and bounty information.
               * @param feeOnTop                 The additional fee on top of the item sales price to be paid by the taker.
               *
               * @return endingNativeFunds       The amount of native funds remaining at the end of the function call.
               */
              function _fulfillSingleOrderWithFeeOnTop(
                  uint256 startingNativeFunds,
                  TradeContext memory context,
                  address purchaser,
                  address seller,
                  IERC20 paymentCoin,
                  FulfillOrderFunctionPointers memory fnPointers,
                  Order memory saleDetails,
                  RoyaltyBackfillAndBounty memory royaltyBackfillAndBounty,
                  FeeOnTop memory feeOnTop
              ) private returns (uint256 endingNativeFunds) {
                  endingNativeFunds = startingNativeFunds;
                  if (!fnPointers.funcDispenseToken(
                          seller, 
                          saleDetails.beneficiary, 
                          saleDetails.tokenAddress, 
                          saleDetails.tokenId, 
                          saleDetails.amount)) {
                      if (context.disablePartialFill) {
                          revert PaymentProcessor__DispensingTokenWasUnsuccessful();
                      }
                  } else {
                      SplitProceeds memory proceeds =
                          _computePaymentSplits(
                              saleDetails.itemPrice,
                              saleDetails.tokenAddress,
                              saleDetails.tokenId,
                              saleDetails.marketplace,
                              saleDetails.marketplaceFeeNumerator,
                              saleDetails.maxRoyaltyFeeNumerator,
                              saleDetails.fallbackRoyaltyRecipient,
                              royaltyBackfillAndBounty
                          );
                      uint256 feeOnTopAmount;
                      if (feeOnTop.recipient != address(0)) {
                          feeOnTopAmount = feeOnTop.amount;
                      }
                      if (saleDetails.paymentMethod == address(0)) {
                          uint256 nativeProceedsToSpend = saleDetails.itemPrice + feeOnTopAmount;
                          if (endingNativeFunds < nativeProceedsToSpend) {
                              revert PaymentProcessor__RanOutOfNativeFunds();
                          }
                          unchecked {
                              endingNativeFunds -= nativeProceedsToSpend;
                          }
                      }
                      if (proceeds.royaltyProceeds > 0) {
                          fnPointers.funcPayout(proceeds.royaltyRecipient, purchaser, paymentCoin, proceeds.royaltyProceeds, pushPaymentGasLimit);
                      }
                      if (proceeds.marketplaceProceeds > 0) {
                          fnPointers.funcPayout(saleDetails.marketplace, purchaser, paymentCoin, proceeds.marketplaceProceeds, pushPaymentGasLimit);
                      }
                      if (proceeds.sellerProceeds > 0) {
                          fnPointers.funcPayout(seller, purchaser, paymentCoin, proceeds.sellerProceeds, pushPaymentGasLimit);
                      }
                      if (feeOnTopAmount > 0) {
                          if (feeOnTopAmount > saleDetails.itemPrice) {
                              revert PaymentProcessor__FeeOnTopCannotBeGreaterThanItemPrice();
                          }
                          fnPointers.funcPayout(feeOnTop.recipient, context.taker, paymentCoin, feeOnTop.amount, pushPaymentGasLimit);
                      }
                      fnPointers.funcEmitOrderExecutionEvent(context, saleDetails);
                  }
              }
              /**
               * @notice Dispenses tokens and proceeds for a sweep order.
               * 
               * @dev    This function will **NOT** throw if a token fails to dispense.
               * @dev    Throws when the taker did not supply enough native funds.
               * 
               * @param context             The current execution context to determine the taker.
               * @param startingNativeFunds The amount of native funds remaining at the beginning of the function call.
               * @param params              Struct containing the order execution details, backfilled royalty information 
               *                            and fulfillment function pointers.
               *
               * @return endingNativeFunds  The amount of native funds remaining at the end of the function call.
               */
              function _fulfillSweepOrderWithFeeOnTop(
                  TradeContext memory context,
                  uint256 startingNativeFunds,
                  SweepCollectionComputeAndDistributeProceedsParams memory params
              ) private returns (uint256 endingNativeFunds) {
                  endingNativeFunds = startingNativeFunds;
                  PayoutsAccumulator memory accumulator = PayoutsAccumulator({
                      lastSeller: address(0),
                      lastMarketplace: address(0),
                      lastRoyaltyRecipient: address(0),
                      accumulatedSellerProceeds: 0,
                      accumulatedMarketplaceProceeds: 0,
                      accumulatedRoyaltyProceeds: 0
                  });
                  for (uint256 i = 0; i < params.saleDetailsBatch.length;) {
                      Order memory saleDetails = params.saleDetailsBatch[i];
                      if (!params.fnPointers.funcDispenseToken(
                              saleDetails.maker, 
                              saleDetails.beneficiary, 
                              saleDetails.tokenAddress, 
                              saleDetails.tokenId, 
                              saleDetails.amount)) {
                      } else {
                          SplitProceeds memory proceeds =
                              _computePaymentSplits(
                                  saleDetails.itemPrice,
                                  saleDetails.tokenAddress,
                                  saleDetails.tokenId,
                                  saleDetails.marketplace,
                                  saleDetails.marketplaceFeeNumerator,
                                  saleDetails.maxRoyaltyFeeNumerator,
                                  saleDetails.fallbackRoyaltyRecipient,
                                  params.royaltyBackfillAndBounty
                              );
                          if (saleDetails.paymentMethod == address(0)) {
                              if (endingNativeFunds < saleDetails.itemPrice) {
                                  revert PaymentProcessor__RanOutOfNativeFunds();
                              }
              
                              unchecked {
                                  endingNativeFunds -= saleDetails.itemPrice;
                              }
                          }
              
                          if (proceeds.royaltyRecipient != accumulator.lastRoyaltyRecipient) {
                              if(accumulator.accumulatedRoyaltyProceeds > 0) {
                                  params.fnPointers.funcPayout(accumulator.lastRoyaltyRecipient, context.taker, params.paymentCoin, accumulator.accumulatedRoyaltyProceeds, pushPaymentGasLimit);
                              }
              
                              accumulator.lastRoyaltyRecipient = proceeds.royaltyRecipient;
                              accumulator.accumulatedRoyaltyProceeds = 0;
                          }
              
                          if (saleDetails.marketplace != accumulator.lastMarketplace) {
                              if(accumulator.accumulatedMarketplaceProceeds > 0) {
                                  params.fnPointers.funcPayout(accumulator.lastMarketplace, context.taker, params.paymentCoin, accumulator.accumulatedMarketplaceProceeds, pushPaymentGasLimit);
                              }
              
                              accumulator.lastMarketplace = saleDetails.marketplace;
                              accumulator.accumulatedMarketplaceProceeds = 0;
                          }
              
                          if (saleDetails.maker != accumulator.lastSeller) {
                              if(accumulator.accumulatedSellerProceeds > 0) {
                                  params.fnPointers.funcPayout(accumulator.lastSeller, context.taker, params.paymentCoin, accumulator.accumulatedSellerProceeds, pushPaymentGasLimit);
                              }
              
                              accumulator.lastSeller = saleDetails.maker;
                              accumulator.accumulatedSellerProceeds = 0;
                          }
                          unchecked {
                              accumulator.accumulatedRoyaltyProceeds += proceeds.royaltyProceeds;
                              accumulator.accumulatedMarketplaceProceeds += proceeds.marketplaceProceeds;
                              accumulator.accumulatedSellerProceeds += proceeds.sellerProceeds;
                          }
                          params.fnPointers.funcEmitOrderExecutionEvent(context, saleDetails);
                      }
                      unchecked {
                          ++i;
                      }
                  }
                  if(accumulator.accumulatedRoyaltyProceeds > 0) {
                      params.fnPointers.funcPayout(accumulator.lastRoyaltyRecipient, context.taker, params.paymentCoin, accumulator.accumulatedRoyaltyProceeds, pushPaymentGasLimit);
                  }
                  if(accumulator.accumulatedMarketplaceProceeds > 0) {
                      params.fnPointers.funcPayout(accumulator.lastMarketplace, context.taker, params.paymentCoin, accumulator.accumulatedMarketplaceProceeds, pushPaymentGasLimit);
                  }
                  if(accumulator.accumulatedSellerProceeds > 0) {
                      params.fnPointers.funcPayout(accumulator.lastSeller, context.taker, params.paymentCoin, accumulator.accumulatedSellerProceeds, pushPaymentGasLimit);
                  }
                  if (params.feeOnTop.recipient != address(0)) {
                      if (params.feeOnTop.amount > 0) {
                          if (address(params.paymentCoin) == address(0)) {
                              if (endingNativeFunds < params.feeOnTop.amount) {
                                  revert PaymentProcessor__RanOutOfNativeFunds();
                              }
              
                              unchecked {
                                  endingNativeFunds -= params.feeOnTop.amount;
                              }
                          }
                          params.fnPointers.funcPayout(params.feeOnTop.recipient, context.taker, params.paymentCoin, params.feeOnTop.amount, pushPaymentGasLimit);
                      }
                  }
              }
              /**
               * @notice Calculates the payment splits between seller, creator and marketplace based
               * @notice on on-chain royalty information or backfilled royalty information if on-chain
               * @notice data is unavailable.
               * 
               * @dev    Throws when ERC2981 on-chain royalties are set to an amount greater than the 
               * @dev    maker signed maximum.
               * 
               * @param salePrice                The sale price for the token being sold.
               * @param tokenAddress             The contract address for the token being sold.
               * @param tokenId                  The token id for the token being sold.
               * @param marketplaceFeeRecipient  The address that will receive the marketplace fee. 
               *                                 If zero, no marketplace fee will be applied.
               * @param marketplaceFeeNumerator  The fee numerator for calculating marketplace fees.
               * @param maxRoyaltyFeeNumerator  The maximum royalty fee authorized by the order maker.
               * @param fallbackRoyaltyRecipient The address that will receive royalties if not defined onchain.
               * @param royaltyBackfillAndBounty The royalty backfill and bounty information set onchain by the creator.
               *
               * @return proceeds A struct containing the split of payment and receiving addresses for the
               *                  seller, creator and marketplace.
               */
              function _computePaymentSplits(
                  uint256 salePrice,
                  address tokenAddress,
                  uint256 tokenId,
                  address marketplaceFeeRecipient,
                  uint256 marketplaceFeeNumerator,
                  uint256 maxRoyaltyFeeNumerator,
                  address fallbackRoyaltyRecipient,
                  RoyaltyBackfillAndBounty memory royaltyBackfillAndBounty
              ) private view returns (SplitProceeds memory proceeds) {
                  proceeds.sellerProceeds = salePrice;
                  try IERC2981(tokenAddress).royaltyInfo(
                      tokenId, 
                      salePrice) 
                      returns (address royaltyReceiver, uint256 royaltyAmount) {
                      if (royaltyReceiver == address(0)) {
                          royaltyAmount = 0;
                      }
                      if (royaltyAmount > 0) {
                          if (royaltyAmount > (salePrice * maxRoyaltyFeeNumerator) / FEE_DENOMINATOR) {
                              revert PaymentProcessor__OnchainRoyaltiesExceedMaximumApprovedRoyaltyFee();
                          }
                          proceeds.royaltyRecipient = royaltyReceiver;
                          proceeds.royaltyProceeds = royaltyAmount;
                          unchecked {
                              proceeds.sellerProceeds -= royaltyAmount;
                          }
                      }
                  } catch (bytes memory) {
                      // If the token doesn't implement the royaltyInfo function, then check if there are backfilled royalties.
                      if (royaltyBackfillAndBounty.backfillReceiver != address(0)) {
                          if (royaltyBackfillAndBounty.backfillNumerator > maxRoyaltyFeeNumerator) {
                              revert PaymentProcessor__OnchainRoyaltiesExceedMaximumApprovedRoyaltyFee();
                          }
                          proceeds.royaltyRecipient = royaltyBackfillAndBounty.backfillReceiver;
                          proceeds.royaltyProceeds = 
                              (salePrice * royaltyBackfillAndBounty.backfillNumerator) / FEE_DENOMINATOR;
                          unchecked {
                              proceeds.sellerProceeds -= proceeds.royaltyProceeds;
                          }
                      } else if (fallbackRoyaltyRecipient != address(0)) {
                          proceeds.royaltyRecipient = fallbackRoyaltyRecipient;
                          proceeds.royaltyProceeds = (salePrice * maxRoyaltyFeeNumerator) / FEE_DENOMINATOR;
                          unchecked {
                              proceeds.sellerProceeds -= proceeds.royaltyProceeds;
                          }
                      }
                  }
                  if (marketplaceFeeRecipient != address(0)) {
                      proceeds.marketplaceProceeds = (salePrice * marketplaceFeeNumerator) / FEE_DENOMINATOR;
                      unchecked {
                          proceeds.sellerProceeds -= proceeds.marketplaceProceeds;
                      }
                      if (royaltyBackfillAndBounty.exclusiveMarketplace == address(0) || 
                          royaltyBackfillAndBounty.exclusiveMarketplace == marketplaceFeeRecipient) {
                          uint256 royaltyBountyProceeds = 
                              proceeds.royaltyProceeds * royaltyBackfillAndBounty.bountyNumerator / FEE_DENOMINATOR;
                      
                          if (royaltyBountyProceeds > 0) {
                              unchecked {
                                  proceeds.royaltyProceeds -= royaltyBountyProceeds;
                                  proceeds.marketplaceProceeds += royaltyBountyProceeds;
                              }
                          }
                      }
                  }
              }
              /**
               * @notice Transfers chain native token to `to`.
               * 
               * @dev    Throws when the native token transfer call reverts.
               * @dev    Throws when the payee uses more gas than `gasLimit_`.
               *
               * @param to                   The address that will receive chain native tokens.
               * @param proceeds             The amount of chain native token value to transfer.
               * @param pushPaymentGasLimit_ The amount of gas units to allow the payee to use.
               */
              function _pushProceeds(address to, uint256 proceeds, uint256 pushPaymentGasLimit_) internal {
                  bool success;
                  assembly {
                      // Transfer the ETH and store if it succeeded or not.
                      success := call(pushPaymentGasLimit_, to, proceeds, 0, 0, 0, 0)
                  }
                  if (!success) {
                      revert PaymentProcessor__FailedToTransferProceeds();
                  }
              }
              /**
               * @notice Transfers chain native token to `payee`.
               * 
               * @dev    Throws when the native token transfer call reverts.
               * @dev    Throws when the payee uses more gas than `gasLimit_`.
               *
               * @param payee     The address that will receive chain native tokens.
               * @param proceeds  The amount of chain native token value to transfer.
               * @param gasLimit_ The amount of gas units to allow the payee to use.
               */
              function _payoutNativeCurrency(
                  address payee, 
                  address /*payer*/, 
                  IERC20 /*paymentCoin*/, 
                  uint256 proceeds, 
                  uint256 gasLimit_) internal {
                  _pushProceeds(payee, proceeds, gasLimit_);
              }
              /**
               * @notice Transfers ERC20 tokens to from `payer` to `payee`.
               * 
               * @dev    Throws when the ERC20 transfer call reverts.
               *
               * @param payee The address that will receive ERC20 tokens.
               * @param payer The address the ERC20 tokens will be sent from.
               * @param paymentCoin The ERC20 token being transferred.
               * @param proceeds The amount of token value to transfer.
               */
              function _payoutCoinCurrency(
                  address payee, 
                  address payer, 
                  IERC20 paymentCoin, 
                  uint256 proceeds, 
                  uint256 /*gasLimit_*/) internal {
                  SafeERC20.safeTransferFrom(paymentCoin, payer, payee, proceeds);
              }
              /**
               * @notice Calls the token contract to transfer an ERC721 token from the seller to the buyer.
               * 
               * @dev    This will **NOT** throw if the transfer fails. It will instead return false
               * @dev    so that the calling function can handle the failed transfer.
               * @dev    Returns true if the transfer does not revert.
               * 
               * @param from         The seller of the token.
               * @param to           The beneficiary of the order execution.
               * @param tokenAddress The contract address for the token being transferred.
               * @param tokenId      The token id for the order.
               */
              function _dispenseERC721Token(
                  address from, 
                  address to, 
                  address tokenAddress, 
                  uint256 tokenId, 
                  uint256 /*amount*/) internal returns (bool) {
                  try IERC721(tokenAddress).transferFrom(from, to, tokenId) {
                      return true;
                  } catch {
                      return false;
                  }
              }
              /**
               * @notice Calls the token contract to transfer an ERC1155 token from the seller to the buyer.
               * 
               * @dev    This will **NOT** throw if the transfer fails. It will instead return false
               * @dev    so that the calling function can handle the failed transfer.
               * @dev    Returns true if the transfer does not revert.
               * 
               * @param from         The seller of the token.
               * @param to           The beneficiary of the order execution.
               * @param tokenAddress The contract address for the token being transferred.
               * @param tokenId      The token id for the order.
               * @param amount       The quantity of the token to transfer.
               */
              function _dispenseERC1155Token(
                  address from, 
                  address to, 
                  address tokenAddress, 
                  uint256 tokenId, 
                  uint256 amount) internal returns (bool) {
                  try IERC1155(tokenAddress).safeTransferFrom(from, to, tokenId, amount, "") {
                      return true;
                  } catch {
                      return false;
                  }
              }
              /**
               * @notice Emits a a BuyListingERC721 event.
               * 
               * @param context The current execution context to determine the taker.
               * @param saleDetails The order execution details.
               */
              function _emitBuyListingERC721Event(TradeContext memory context, Order memory saleDetails) internal {
                  emit BuyListingERC721(
                          context.taker,
                          saleDetails.maker,
                          saleDetails.tokenAddress,
                          saleDetails.beneficiary,
                          saleDetails.paymentMethod,
                          saleDetails.tokenId,
                          saleDetails.itemPrice);
              }
              /**
               * @notice Emits a BuyListingERC1155 event.
               * 
               * @param context The current execution context to determine the taker.
               * @param saleDetails The order execution details.
               */
              function _emitBuyListingERC1155Event(TradeContext memory context, Order memory saleDetails) internal {
                  emit BuyListingERC1155(
                          context.taker,
                          saleDetails.maker,
                          saleDetails.tokenAddress,
                          saleDetails.beneficiary,
                          saleDetails.paymentMethod,
                          saleDetails.tokenId,
                          saleDetails.amount,
                          saleDetails.itemPrice);
              }
              /**
               * @notice Emits an AcceptOfferERC721 event.
               * 
               * @param context The current execution context to determine the taker.
               * @param saleDetails The order execution details.
               */
              function _emitAcceptOfferERC721Event(TradeContext memory context, Order memory saleDetails) internal {
                  emit AcceptOfferERC721(
                          context.taker,
                          saleDetails.maker,
                          saleDetails.tokenAddress,
                          saleDetails.beneficiary,
                          saleDetails.paymentMethod,
                          saleDetails.tokenId,
                          saleDetails.itemPrice);
              }
              /**
               * @notice Emits an AcceptOfferERC1155 event.
               * 
               * @param context The current execution context to determine the taker.
               * @param saleDetails The order execution details.
               */
              function _emitAcceptOfferERC1155Event(TradeContext memory context, Order memory saleDetails) internal {
                  emit AcceptOfferERC1155(
                          context.taker,
                          saleDetails.maker,
                          saleDetails.tokenAddress,
                          saleDetails.beneficiary,
                          saleDetails.paymentMethod,
                          saleDetails.tokenId,
                          saleDetails.amount,
                          saleDetails.itemPrice);
              }
              /**
               * @notice Returns the appropriate function pointers for payouts, dispensing tokens and event emissions.
               *
               * @param side The taker's side of the order.
               * @param paymentMethod The payment method for the order. If address zero, the chain native token.
               * @param orderProtocol The type of token and fill method for the order.
               */
              function _getOrderFulfillmentFunctionPointers(
                  Sides side,
                  address paymentMethod,
                  OrderProtocols orderProtocol
              ) private view returns (FulfillOrderFunctionPointers memory orderFulfillmentFunctionPointers) {
                  orderFulfillmentFunctionPointers = FulfillOrderFunctionPointers({
                      funcPayout: paymentMethod == address(0) ? _payoutNativeCurrency : _payoutCoinCurrency,
                      funcDispenseToken: orderProtocol == OrderProtocols.ERC721_FILL_OR_KILL ? _dispenseERC721Token : _dispenseERC1155Token,
                      funcEmitOrderExecutionEvent: orderProtocol == OrderProtocols.ERC721_FILL_OR_KILL ? 
                          (side == Sides.Buy ? _emitBuyListingERC721Event : _emitAcceptOfferERC721Event) : 
                          (side == Sides.Buy ?_emitBuyListingERC1155Event : _emitAcceptOfferERC1155Event)
                  });
              }
              /*************************************************************************/
              /*                        Signature Verification                         */
              /*************************************************************************/
              /**
               * @notice Updates the remaining fillable amount and order status for partially fillable orders.
               * @notice Performs checks for minimum fillable amount and order status.
               *
               * @dev    Throws when the remaining fillable amount is less than the minimum fillable amount requested.
               * @dev    Throws when the order status is not open.
               *
               * @param account             The maker account for the order.
               * @param orderDigest         The hash digest of the order execution details.
               * @param orderStartAmount    The original amount for the partially fillable order.
               * @param requestedFillAmount The amount the taker is requesting to fill.
               * @param minimumFillAmount   The minimum amount the taker is willing to fill.
               *
               * @return quantityToFill     Lesser of remainingFillableAmount and requestedFillAmount.
               */
              function _checkAndUpdateRemainingFillableItems(
                  address account,
                  bytes32 orderDigest, 
                  uint248 orderStartAmount,
                  uint248 requestedFillAmount,
                  uint248 minimumFillAmount
              ) private returns (uint248 quantityToFill) {
                  quantityToFill = requestedFillAmount;
                  PartiallyFillableOrderStatus storage partialFillStatus = 
                      appStorage().partiallyFillableOrderStatuses[account][orderDigest];
              
                  if (partialFillStatus.state == PartiallyFillableOrderState.Open) {
                      if (partialFillStatus.remainingFillableQuantity == 0) {
                          partialFillStatus.remainingFillableQuantity = uint248(orderStartAmount);
                      }
                      if (quantityToFill > partialFillStatus.remainingFillableQuantity) {
                          quantityToFill = partialFillStatus.remainingFillableQuantity;
                      }
                      if (quantityToFill < minimumFillAmount) {
                          revert PaymentProcessor__UnableToFillMinimumRequestedQuantity();
                      }
                      unchecked {
                          partialFillStatus.remainingFillableQuantity -= quantityToFill;
                      }
                      if (partialFillStatus.remainingFillableQuantity == 0) {
                          partialFillStatus.state = PartiallyFillableOrderState.Filled;
                          emit OrderDigestInvalidated(orderDigest, account, false);
                      }
                  } else {
                      revert PaymentProcessor__OrderIsEitherCancelledOrFilled();
                  }
              }
              /**
               * @notice Invalidates a maker's nonce and emits a NonceInvalidated event.
               * 
               * @dev    Throws when the nonce has already been invalidated.
               * 
               * @param account         The maker account to invalidate `nonce` of.
               * @param nonce           The nonce to invalidate.
               * @param wasCancellation If true, the invalidation is the maker cancelling the nonce. 
               *                        If false, from the nonce being used to execute an order.
               */
              function _checkAndInvalidateNonce(
                  address account, 
                  uint256 nonce, 
                  bool wasCancellation) internal returns (uint256) {
                  // The following code is equivalent to, but saves 115 gas units:
                  // 
                  // mapping(uint256 => uint256) storage ptrInvalidatedSignatureBitmap = 
                  //     appStorage().invalidatedSignatures[account];
                  // unchecked {
                  //     uint256 slot = nonce / 256;
                  //     uint256 offset = nonce % 256;
                  //     uint256 slotValue = ptrInvalidatedSignatureBitmap[slot];
                  // 
                  //     if (((slotValue >> offset) & ONE) == ONE) {
                  //         revert PaymentProcessor__SignatureAlreadyUsedOrRevoked();
                  //     }
                  // 
                  //     ptrInvalidatedSignatureBitmap[slot] = (slotValue | ONE << offset);
                  // }
                  unchecked {
                      if (uint256(appStorage().invalidatedSignatures[account][uint248(nonce >> 8)] ^= (ONE << uint8(nonce))) & 
                          (ONE << uint8(nonce)) == ZERO) {
                          revert PaymentProcessor__SignatureAlreadyUsedOrRevoked();
                      }
                  }
                  emit NonceInvalidated(nonce, account, wasCancellation);
                  return appStorage().masterNonces[account];
              }
              /**
               * @notice Updates the state of a maker's order to cancelled and remaining fillable quantity to zero.
               *
               * @dev    Throws when the current order state is not open.
               *
               * @param account     The maker account to invalid the order for.
               * @param orderDigest The hash digest of the order to invalidate.
               */
              function _revokeOrderDigest(address account, bytes32 orderDigest) internal {
                  PartiallyFillableOrderStatus storage partialFillStatus = 
                      appStorage().partiallyFillableOrderStatuses[account][orderDigest];
              
                  if (partialFillStatus.state == PartiallyFillableOrderState.Open) {
                      partialFillStatus.state = PartiallyFillableOrderState.Cancelled;
                      partialFillStatus.remainingFillableQuantity = 0;
                      emit OrderDigestInvalidated(orderDigest, account, true);
                  } else {
                      revert PaymentProcessor__OrderIsEitherCancelledOrFilled();
                  }
              }
              /**
               * @notice Verifies a token offer is approved by the maker.
               *
               * @dev    Throws when a cosignature is required and the cosignature is invalid.
               * @dev    Throws when the maker signature is invalid.
               * @dev    Throws when the maker's order nonce has already been used or was cancelled.
               * @dev    Throws when a partially fillable order has already been filled, cancelled or 
               * @dev    cannot be filled with the minimum fillable amount.
               *
               * @param context       The current execution context to determine the taker.
               * @param saleDetails   The order execution details.
               * @param signature     The order maker's signature.
               * @param cosignature   The cosignature from the order cosigner, if applicable.
               * 
               * @return quantityToFill The amount of the token that will be filled for this order.
               */
              function _verifyItemOffer(
                  TradeContext memory context, 
                  Order memory saleDetails,
                  SignatureECDSA memory signature,
                  Cosignature memory cosignature
              ) private returns (uint248 quantityToFill) {
                  if (cosignature.signer != address(0)) {
                      _verifyCosignature(context, signature, cosignature);
                  }
                  bytes32 orderDigest = _hashTypedDataV4(context.domainSeparator, keccak256(
                      bytes.concat(
                          abi.encode(
                              ITEM_OFFER_APPROVAL_HASH,
                              uint8(saleDetails.protocol),
                              cosignature.signer,
                              saleDetails.maker,
                              saleDetails.beneficiary,
                              saleDetails.marketplace,
                              saleDetails.fallbackRoyaltyRecipient,
                              saleDetails.paymentMethod,
                              saleDetails.tokenAddress
                          ),
                          abi.encode(
                              saleDetails.tokenId,
                              saleDetails.amount,
                              saleDetails.itemPrice,
                              saleDetails.expiration,
                              saleDetails.marketplaceFeeNumerator,
                              saleDetails.nonce,
                              saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                                  appStorage().masterNonces[saleDetails.maker] :
                                  _checkAndInvalidateNonce(saleDetails.maker, saleDetails.nonce, false)
                          )
                      )
                  ));
                  _verifyMakerSignature(saleDetails.maker, signature, orderDigest);
                  quantityToFill = saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                      _checkAndUpdateRemainingFillableItems(
                          saleDetails.maker, 
                          orderDigest, 
                          saleDetails.amount, 
                          saleDetails.requestedFillAmount,
                          saleDetails.minimumFillAmount) :
                      saleDetails.amount;
              }
              /**
               * @notice Verifies a collection offer is approved by the maker.
               *
               * @dev    Throws when a cosignature is required and the cosignature is invalid.
               * @dev    Throws when the maker signature is invalid.
               * @dev    Throws when the maker's order nonce has already been used or was cancelled.
               * @dev    Throws when a partially fillable order has already been filled, cancelled or 
               * @dev    cannot be filled with the minimum fillable amount.
               *
               * @param context       The current execution context to determine the taker.
               * @param saleDetails   The order execution details.
               * @param signature     The order maker's signature.
               * @param cosignature   The cosignature from the order cosigner, if applicable.
               * 
               * @return quantityToFill The amount of the token that will be filled for this order.
               */
              function _verifyCollectionOffer(
                  TradeContext memory context, 
                  Order memory saleDetails,
                  SignatureECDSA memory signature,
                  Cosignature memory cosignature
              ) private returns (uint248 quantityToFill) {
                  if (cosignature.signer != address(0)) {
                      _verifyCosignature(context, signature, cosignature);
                  }
                  bytes32 orderDigest = _hashTypedDataV4(context.domainSeparator, keccak256(
                      bytes.concat(
                          abi.encode(
                              COLLECTION_OFFER_APPROVAL_HASH,
                              uint8(saleDetails.protocol),
                              cosignature.signer,
                              saleDetails.maker,
                              saleDetails.beneficiary,
                              saleDetails.marketplace,
                              saleDetails.fallbackRoyaltyRecipient,
                              saleDetails.paymentMethod,
                              saleDetails.tokenAddress
                          ),
                          abi.encode(
                              saleDetails.amount,
                              saleDetails.itemPrice,
                              saleDetails.expiration,
                              saleDetails.marketplaceFeeNumerator,
                              saleDetails.nonce,
                              saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                                  appStorage().masterNonces[saleDetails.maker] :
                                  _checkAndInvalidateNonce(saleDetails.maker, saleDetails.nonce, false)
                          )
                      )
                  ));
                  _verifyMakerSignature(saleDetails.maker, signature, orderDigest);
                  quantityToFill = saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                      _checkAndUpdateRemainingFillableItems(
                          saleDetails.maker, 
                          orderDigest, 
                          saleDetails.amount, 
                          saleDetails.requestedFillAmount,
                          saleDetails.minimumFillAmount) :
                      saleDetails.amount;
              }
              /**
               * @notice Verifies a token set offer is approved by the maker.
               *
               * @dev    Throws when a cosignature is required and the cosignature is invalid.
               * @dev    Throws when the maker signature is invalid.
               * @dev    Throws when the maker's order nonce has already been used or was cancelled.
               * @dev    Throws when a partially fillable order has already been filled, cancelled or 
               * @dev    cannot be filled with the minimum fillable amount.
               *
               * @param context       The current execution context to determine the taker.
               * @param saleDetails   The order execution details.
               * @param signature     The order maker's signature.
               * @param tokenSetProof The token set proof that contains the root hash for the merkle  
               *                      tree of allowed tokens for accepting the maker's offer.
               * @param cosignature   The cosignature from the order cosigner, if applicable.
               * 
               * @return quantityToFill The amount of the token that will be filled for this order.
               */
              function _verifyTokenSetOffer(
                  TradeContext memory context, 
                  Order memory saleDetails,
                  SignatureECDSA memory signature,
                  TokenSetProof memory tokenSetProof,
                  Cosignature memory cosignature
              ) private returns (uint248 quantityToFill) {
                  if (cosignature.signer != address(0)) {
                      _verifyCosignature(context, signature, cosignature);
                  }
                  bytes32 orderDigest = _hashTypedDataV4(context.domainSeparator, keccak256(
                      bytes.concat(
                          abi.encode(
                              TOKEN_SET_OFFER_APPROVAL_HASH,
                              uint8(saleDetails.protocol),
                              cosignature.signer,
                              saleDetails.maker,
                              saleDetails.beneficiary,
                              saleDetails.marketplace,
                              saleDetails.fallbackRoyaltyRecipient,
                              saleDetails.paymentMethod,
                              saleDetails.tokenAddress
                          ),
                          abi.encode(
                              saleDetails.amount,
                              saleDetails.itemPrice,
                              saleDetails.expiration,
                              saleDetails.marketplaceFeeNumerator,
                              saleDetails.nonce,
                              saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                                  appStorage().masterNonces[saleDetails.maker] :
                                  _checkAndInvalidateNonce(saleDetails.maker, saleDetails.nonce, false),
                              tokenSetProof.rootHash
                          )
                      )
                  ));
                  _verifyMakerSignature(saleDetails.maker, signature, orderDigest);
                  quantityToFill = saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                      _checkAndUpdateRemainingFillableItems(
                          saleDetails.maker, 
                          orderDigest, 
                          saleDetails.amount, 
                          saleDetails.requestedFillAmount,
                          saleDetails.minimumFillAmount) :
                      saleDetails.amount;
              }
              /**
               * @notice Verifies a listing is approved by the maker.
               *
               * @dev    Throws when a cosignature is required and the cosignature is invalid.
               * @dev    Throws when the maker signature is invalid.
               * @dev    Throws when the maker's order nonce has already been used or was cancelled.
               * @dev    Throws when a partially fillable order has already been filled, cancelled or 
               * @dev    cannot be filled with the minimum fillable amount.
               *
               * @param context     The current execution context to determine the taker.
               * @param saleDetails The order execution details.
               * @param signature   The order maker's signature.
               * @param cosignature The cosignature from the order cosigner, if applicable.
               * 
               * @return quantityToFill The amount of the token that will be filled for this order.
               */
              function _verifySaleApproval(
                  TradeContext memory context, 
                  Order memory saleDetails,
                  SignatureECDSA memory signature,
                  Cosignature memory cosignature
              ) private returns (uint248 quantityToFill) {
                  if (cosignature.signer != address(0)) {
                      _verifyCosignature(context, signature, cosignature);
                  }
                  bytes32 orderDigest = _hashTypedDataV4(context.domainSeparator, keccak256(
                      bytes.concat(
                          abi.encode(
                              SALE_APPROVAL_HASH,
                              uint8(saleDetails.protocol),
                              cosignature.signer,
                              saleDetails.maker,
                              saleDetails.marketplace,
                              saleDetails.fallbackRoyaltyRecipient,
                              saleDetails.paymentMethod,
                              saleDetails.tokenAddress,
                              saleDetails.tokenId
                          ),
                          abi.encode(
                              saleDetails.amount,
                              saleDetails.itemPrice,
                              saleDetails.expiration,
                              saleDetails.marketplaceFeeNumerator,
                              saleDetails.maxRoyaltyFeeNumerator,
                              saleDetails.nonce,
                              saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                                  appStorage().masterNonces[saleDetails.maker] :
                                  _checkAndInvalidateNonce(saleDetails.maker, saleDetails.nonce, false)
                          )
                      )
                  ));
                  _verifyMakerSignature(saleDetails.maker, signature, orderDigest);
                  quantityToFill = saleDetails.protocol == OrderProtocols.ERC1155_FILL_PARTIAL ? 
                      _checkAndUpdateRemainingFillableItems(
                          saleDetails.maker, 
                          orderDigest, 
                          saleDetails.amount, 
                          saleDetails.requestedFillAmount,
                          saleDetails.minimumFillAmount) :
                      saleDetails.amount;
              }
              /**
               * @notice Reverts a transaction when the recovered signer is not the order maker.
               *
               * @dev Throws when the recovered signer for the `signature` and `digest` does not match the order maker AND
               * @dev - The maker address does not have deployed code, OR 
               * @dev - The maker contract does not return the correct ERC1271 value to validate the signature.
               *
               * @param maker The adress for the order maker.
               * @param signature The order maker's signature.
               * @param digest The hash digest of the order.
               */
              function _verifyMakerSignature(address maker, SignatureECDSA memory signature, bytes32 digest ) private view {
                  if (maker != _ecdsaRecover(digest, signature.v, signature.r, signature.s)) {
                      if (maker.code.length > 0) {
                          _verifyEIP1271Signature(maker, digest, signature);
                      } else {
                          revert PaymentProcessor__UnauthorizedOrder();
                      }
                  }
              }
              /**
               * @notice Reverts the transaction when a supplied cosignature is not valid.
               *
               * @dev    Throws when the current block timestamp is greater than the cosignature expiration.
               * @dev    Throws when the order taker does not match the cosignature taker.
               * @dev    Throws when the cosigner has self-destructed their account.
               * @dev    Throws when the recovered address for the cosignature does not match the cosigner address.
               * 
               * @param context     The current execution context to determine the order taker.
               * @param signature   The order maker's signature.
               * @param cosignature The cosignature from the order cosigner.
               */
              function _verifyCosignature(
                  TradeContext memory context, 
                  SignatureECDSA memory signature, 
                  Cosignature memory cosignature
              ) private view {
                  if (block.timestamp > cosignature.expiration) {
                      revert PaymentProcessor__CosignatureHasExpired();
                  }
                  if (context.taker != cosignature.taker) {
                      revert PaymentProcessor__UnauthorizedTaker();
                  }
                  if (appStorage().destroyedCosigners[cosignature.signer]) {
                      revert PaymentProcessor__CosignerHasSelfDestructed();
                  }
                  if (cosignature.signer != _ecdsaRecover(
                      _hashTypedDataV4(context.domainSeparator, keccak256(
                          abi.encode(
                              COSIGNATURE_HASH,
                              signature.v,
                              signature.r,
                              signature.s,
                              cosignature.expiration,
                              cosignature.taker
                          )
                      )), 
                      cosignature.v, 
                      cosignature.r, 
                      cosignature.s)) {
                      revert PaymentProcessor__NotAuthorizedByCosigner();
                  }
              }
              /**
               * @notice Reverts the transaction if the contract at `signer` does not return the ERC1271
               * @notice isValidSignature selector when called with `hash`.
               * 
               * @dev    Throws when attempting to verify a signature from an address that has deployed
               * @dev    contract code using ERC1271 and the contract does not return the isValidSignature
               * @dev    function selector as its return value.
               *
               * @param signer The signer address for a maker order that has deployed contract code.
               * @param hash The ERC712 hash value of the order.
               * @param signature The signature for the order hash.
               */
              function _verifyEIP1271Signature(
                  address signer, 
                  bytes32 hash, 
                  SignatureECDSA memory signature) private view {
                  bool isValidSignatureNow;
                  
                  try IERC1271(signer).isValidSignature(
                      hash, 
                      abi.encodePacked(signature.r, signature.s, signature.v)) 
                      returns (bytes4 magicValue) {
                      isValidSignatureNow = magicValue == IERC1271.isValidSignature.selector;
                  } catch {}
                  if (!isValidSignatureNow) {
                      revert PaymentProcessor__EIP1271SignatureInvalid();
                  }
              }
              /**
               * @notice Recovers the signer address from a hash and signature.
               * 
               * @dev Throws when `s` is greater than 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 to
               * @dev prevent malleable signatures from being utilized. 
               * @dev Throws when the recovered address is zero.
               *
               * @param digest The hash digest that was signed.
               * @param v The v-value of the signature.
               * @param r The r-value of the signature.
               * @param s The s-value of the signature.
               *
               * @return signer The recovered signer address from the signature.
               */
              function _ecdsaRecover(
                  bytes32 digest, 
                  uint8 v, 
                  bytes32 r, 
                  bytes32 s
              ) private pure returns (address signer) {
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      revert PaymentProcessor__UnauthorizedOrder();
                  }
                  signer = ecrecover(digest, v, r, s);
                  if (signer == address(0)) {
                      revert PaymentProcessor__UnauthorizedOrder();
                  }
              }
              /**
               * @notice Returns the EIP-712 hash digest for `domainSeparator` and `structHash`.
               * 
               * @param domainSeparator The domain separator for the EIP-712 hash.
               * @param structHash The hash of the EIP-712 struct.
               */
              function _hashTypedDataV4(bytes32 domainSeparator, bytes32 structHash) private pure returns (bytes32) {
                  return ECDSA.toTypedDataHash(domainSeparator, structHash);
              }
              /*************************************************************************/
              /*                             Miscellaneous                             */
              /*************************************************************************/
              /**
               * @notice Transfers ownership of a payment method whitelist.
               * 
               * @dev    Throws when the caller is not the owner of the payment method whitelist.
               *
               * @param id       The payment method whitelist id to transfer ownership of.
               * @param newOwner The address to transfer ownership to.
               */
              function _reassignOwnershipOfPaymentMethodWhitelist(uint32 id, address newOwner) internal {
                  _requireCallerOwnsPaymentMethodWhitelist(id);
                  appStorage().paymentMethodWhitelistOwners[id] = newOwner;
                  emit ReassignedPaymentMethodWhitelistOwnership(id, newOwner);
              }
              /**
               * @notice Reverts the transaction if the caller is not the owner of the payment method whitelist.
               *
               * @dev    Throws when the caller is not the owner of the payment method whitelist.
               *
               * @param paymentMethodWhitelistId The payment method whitelist id to check ownership for.
               */
              function _requireCallerOwnsPaymentMethodWhitelist(uint32 paymentMethodWhitelistId) internal view {
                  if(_msgSender() != appStorage().paymentMethodWhitelistOwners[paymentMethodWhitelistId]) {
                      revert PaymentProcessor__CallerDoesNotOwnPaymentMethodWhitelist();
                  }
              }
              /**
               * @notice Reverts the transaction if the caller is not the owner or assigned the default
               * @notice admin role of the contract at `tokenAddress`.
               *
               * @dev    Throws when the caller is neither owner nor assigned the default admin role.
               * 
               * @param tokenAddress The contract address of the token to check permissions for.
               */
              function _requireCallerIsNFTOrContractOwnerOrAdmin(address tokenAddress) internal view {
                  bool callerHasPermissions = false;
                  address caller = _msgSender();
                  
                  callerHasPermissions = caller == tokenAddress;
                  if(!callerHasPermissions) {
                      try IOwnable(tokenAddress).owner() returns (address contractOwner) {
                          callerHasPermissions = caller == contractOwner;
                      } catch {}
                      if(!callerHasPermissions) {
                          try IAccessControl(tokenAddress).hasRole(DEFAULT_ACCESS_CONTROL_ADMIN_ROLE, caller) 
                              returns (bool callerIsContractAdmin) {
                              callerHasPermissions = callerIsContractAdmin;
                          } catch {}
                      }
                  }
                  if(!callerHasPermissions) {
                      revert PaymentProcessor__CallerMustHaveElevatedPermissionsForSpecifiedNFT();
                  }
              }
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          /**
           * @dev ERC-173 Ownable Interface
           */
          interface IOwnable {
              function owner() external view returns (address);
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "../DataTypes.sol";
          /** 
          * @title PaymentProcessor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          interface IPaymentProcessorConfiguration {
              /**
               * @notice Returns the ERC2771 context setup params for payment processor modules.
               */
              function getPaymentProcessorModuleERC2771ContextParams() 
                  external 
                  view 
                  returns (
                      address /*trustedForwarderFactory*/
                  );
              /**
               * @notice Returns the setup params for payment processor modules.
               */
              function getPaymentProcessorModuleDeploymentParams() 
                  external 
                  view 
                  returns (
                      uint32, /*defaultPushPaymentGasLimit*/
                      address, /*wrappedNativeCoin*/
                      DefaultPaymentMethods memory /*defaultPaymentMethods*/
                  );
              /**
               * @notice Returns the setup params for payment processor.
               */
              function getPaymentProcessorDeploymentParams()
                  external
                  view
                  returns (
                      address, /*defaultContractOwner*/
                      PaymentProcessorModules memory /*paymentProcessorModules*/
                  );
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "../DataTypes.sol";
          /** 
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          interface IPaymentProcessorEvents {
              /// @notice Emitted when an account is banned from trading a collection
              event BannedAccountAddedForCollection(
                  address indexed tokenAddress, 
                  address indexed account);
              /// @notice Emitted when an account ban has been lifted on a collection
              event BannedAccountRemovedForCollection(
                  address indexed tokenAddress, 
                  address indexed account);
              /// @notice Emitted when an ERC721 listing is purchased.
              event BuyListingERC721(
                  address indexed buyer,
                  address indexed seller,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 salePrice);
              /// @notice Emitted when an ERC1155 listing is purchased.
              event BuyListingERC1155(
                  address indexed buyer,
                  address indexed seller,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 amount,
                  uint256 salePrice);
              /// @notice Emitted when an ERC721 offer is accepted.
              event AcceptOfferERC721(
                  address indexed seller,
                  address indexed buyer,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 salePrice);
              /// @notice Emitted when an ERC1155 offer is accepted.
              event AcceptOfferERC1155(
                  address indexed seller,
                  address indexed buyer,
                  address indexed tokenAddress,
                  address beneficiary,
                  address paymentCoin,
                  uint256 tokenId,
                  uint256 amount,
                  uint256 salePrice);
              /// @notice Emitted when a new payment method whitelist is created.
              event CreatedPaymentMethodWhitelist(
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed whitelistOwner,
                  string whitelistName);
              /// @notice Emitted when a cosigner destroys itself.
              event DestroyedCosigner(address indexed cosigner);
              /// @notice Emitted when a user revokes all of their existing listings or offers that share the master nonce.
              event MasterNonceInvalidated(address indexed account, uint256 nonce);
              /// @notice Emitted when a user revokes a single listing or offer nonce for a specific marketplace.
              event NonceInvalidated(
                  uint256 indexed nonce, 
                  address indexed account, 
                  bool wasCancellation);
              /// @notice Emitted when a user revokes a single listing or offer nonce for a specific marketplace.
              event OrderDigestInvalidated(
                  bytes32 indexed orderDigest, 
                  address indexed account, 
                  bool wasCancellation);
              /// @notice Emitted when a coin is added to the approved coins mapping for a security policy
              event PaymentMethodAddedToWhitelist(
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed paymentMethod);
              /// @notice Emitted when a coin is removed from the approved coins mapping for a security policy
              event PaymentMethodRemovedFromWhitelist(
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed paymentMethod);
              /// @notice Emitted when a payment method whitelist is reassigned to a new owner
              event ReassignedPaymentMethodWhitelistOwnership(uint32 indexed id, address indexed newOwner);
              /// @notice Emitted when a trusted channel is added for a collection
              event TrustedChannelAddedForCollection(
                  address indexed tokenAddress, 
                  address indexed channel);
              /// @notice Emitted when a trusted channel is removed for a collection
              event TrustedChannelRemovedForCollection(
                  address indexed tokenAddress, 
                  address indexed channel);
              /// @notice Emitted whenever pricing bounds change at a collection level for price-constrained collections.
              event UpdatedCollectionLevelPricingBoundaries(
                  address indexed tokenAddress, 
                  uint256 floorPrice, 
                  uint256 ceilingPrice);
              /// @notice Emitted whenever the supported ERC-20 payment is set for price-constrained collections.
              event UpdatedCollectionPaymentSettings(
                  address indexed tokenAddress, 
                  PaymentSettings paymentSettings, 
                  uint32 indexed paymentMethodWhitelistId, 
                  address indexed constrainedPricingPaymentMethod,
                  uint16 royaltyBackfillNumerator,
                  address royaltyBackfillReceiver,
                  uint16 royaltyBountyNumerator,
                  address exclusiveBountyReceiver,
                  bool blockTradesFromUntrustedChannels,
                  bool blockBannedAccounts);
              /// @notice Emitted whenever pricing bounds change at a token level for price-constrained collections.
              event UpdatedTokenLevelPricingBoundaries(
                  address indexed tokenAddress, 
                  uint256 indexed tokenId, 
                  uint256 floorPrice, 
                  uint256 ceilingPrice);
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "../DataTypes.sol";
          /** 
          * @title Payment Processor
          * @custom:version 2.0.0
          * @author Limit Break, Inc.
          */ 
          contract PaymentProcessorStorageAccess {
              /// @dev The base storage slot for Payment Processor contract storage items.
              bytes32 constant DIAMOND_STORAGE_PAYMENT_PROCESSOR = 
                  keccak256("diamond.storage.payment.processor");
              /**
               * @dev Returns a storage object that follows the Diamond standard storage pattern for
               * @dev contract storage across multiple module contracts.
               */
              function appStorage() internal pure returns (PaymentProcessorStorage storage diamondStorage) {
                  bytes32 slot = DIAMOND_STORAGE_PAYMENT_PROCESSOR;
                  assembly {
                      diamondStorage.slot := slot
                  }
              }
          }// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          // keccack256("Cosignature(uint8 v,bytes32 r,bytes32 s,uint256 expiration,address taker)")
          bytes32 constant COSIGNATURE_HASH = 0x347b7818601b168f6faadc037723496e9130b057c1ffef2ec4128311e19142f2;
          // keccack256("CollectionOfferApproval(uint8 protocol,address cosigner,address buyer,address beneficiary,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 nonce,uint256 masterNonce)")
          bytes32 constant COLLECTION_OFFER_APPROVAL_HASH = 0x8fe9498e93fe26b30ebf76fac07bd4705201c8609227362697082288e3b4af9c;
          // keccack256("ItemOfferApproval(uint8 protocol,address cosigner,address buyer,address beneficiary,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 tokenId,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 nonce,uint256 masterNonce)")
          bytes32 constant ITEM_OFFER_APPROVAL_HASH = 0xce2e9706d63e89ddf7ee16ce0508a1c3c9bd1904c582db2e647e6f4690a0bf6b;
          //   keccack256("TokenSetOfferApproval(uint8 protocol,address cosigner,address buyer,address beneficiary,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 nonce,uint256 masterNonce,bytes32 tokenSetMerkleRoot)")
          bytes32 constant TOKEN_SET_OFFER_APPROVAL_HASH = 0x244905ade6b0e455d12fb539a4b17d7f675db14797d514168d09814a09c70e70;
          // keccack256("SaleApproval(uint8 protocol,address cosigner,address seller,address marketplace,address fallbackRoyaltyRecipient,address paymentMethod,address tokenAddress,uint256 tokenId,uint256 amount,uint256 itemPrice,uint256 expiration,uint256 marketplaceFeeNumerator,uint256 maxRoyaltyFeeNumerator,uint256 nonce,uint256 masterNonce)")
          bytes32 constant SALE_APPROVAL_HASH = 0x938786a8256d04dc45d6d5b997005aa07c0c9e3e4925d0d6c33128d240096ebc;
          // The denominator used when calculating the marketplace fee.
          // 0.5% fee numerator is 50, 1% fee numerator is 100, 10% fee numerator is 1,000 and so on.
          uint256 constant FEE_DENOMINATOR = 100_00;
          // Default Payment Method Whitelist Id
          uint32 constant DEFAULT_PAYMENT_METHOD_WHITELIST_ID = 0;
          // Convenience to avoid magic number in bitmask get/set logic.
          uint256 constant ZERO = uint256(0);
          uint256 constant ONE = uint256(1);
          // The default admin role for NFT collections using Access Control.
          bytes32 constant DEFAULT_ACCESS_CONTROL_ADMIN_ROLE = 0x00;
          /// @dev The plain text message to sign for cosigner self-destruct signature verification
          string constant COSIGNER_SELF_DESTRUCT_MESSAGE_TO_SIGN = "COSIGNER_SELF_DESTRUCT";
          /**************************************************************/
          /*                   PRECOMPUTED SELECTORS                    */
          /**************************************************************/
          bytes4 constant SELECTOR_REASSIGN_OWNERSHIP_OF_PAYMENT_METHOD_WHITELIST= hex"a1e6917e";
          bytes4 constant SELECTOR_RENOUNCE_OWNERSHIP_OF_PAYMENT_METHOD_WHITELIST= hex"0886702e";
          bytes4 constant SELECTOR_WHITELIST_PAYMENT_METHOD = hex"bb39ce91";
          bytes4 constant SELECTOR_UNWHITELIST_PAYMENT_METHOD = hex"e9d4c14e";
          bytes4 constant SELECTOR_SET_COLLECTION_PAYMENT_SETTINGS = hex"fc5d8393";
          bytes4 constant SELECTOR_SET_COLLECTION_PRICING_BOUNDS = hex"7141ae10";
          bytes4 constant SELECTOR_SET_TOKEN_PRICING_BOUNDS = hex"22146d70";
          bytes4 constant SELECTOR_ADD_TRUSTED_CHANNEL_FOR_COLLECTION = hex"ab559c14";
          bytes4 constant SELECTOR_REMOVE_TRUSTED_CHANNEL_FOR_COLLECTION = hex"282e89f8";
          bytes4 constant SELECTOR_ADD_BANNED_ACCOUNT_FOR_COLLECTION = hex"e21dde50";
          bytes4 constant SELECTOR_REMOVE_BANNED_ACCOUNT_FOR_COLLECTION = hex"adf14a76";
          bytes4 constant SELECTOR_DESTROY_COSIGNER = hex"2aebdefe";
          bytes4 constant SELECTOR_REVOKE_MASTER_NONCE = hex"226d4adb";
          bytes4 constant SELECTOR_REVOKE_SINGLE_NONCE = hex"b6d7dc33";
          bytes4 constant SELECTOR_REVOKE_ORDER_DIGEST = hex"96ae0380";
          bytes4 constant SELECTOR_BUY_LISTING = hex"a9272951";
          bytes4 constant SELECTOR_ACCEPT_OFFER = hex"e35bb9b7";
          bytes4 constant SELECTOR_BULK_BUY_LISTINGS = hex"27add047";
          bytes4 constant SELECTOR_BULK_ACCEPT_OFFERS = hex"b3cdebdb";
          bytes4 constant SELECTOR_SWEEP_COLLECTION = hex"206576f6";
          /**************************************************************/
          /*                   EXPECTED BASE msg.data LENGTHS           */
          /**************************************************************/
          uint256 constant PROOF_ELEMENT_SIZE = 32;
          // | 4        | 32              | 512         | 96              | 192         | 64       | = 900 bytes
          // | selector | domainSeparator | saleDetails | sellerSignature | cosignature | feeOnTop |
          uint256 constant BASE_MSG_LENGTH_BUY_LISTING = 900;
          // | 4        | 32              | 32                     | 512         |  96             | 32 + (96 + (32 * proof.length)) | 192         | 64       | = 1060 bytes + (32 * proof.length)
          // | selector | domainSeparator | isCollectionLevelOffer | saleDetails |  buyerSignature | tokenSetProof                   | cosignature | feeOnTop |
          uint256 constant BASE_MSG_LENGTH_ACCEPT_OFFER = 1060;
          // | 4        | 32              | 64              | 512 * length      | 64              | 96 * length      | 64              | 192 * length | 64              | 64 * length | = 292 bytes + (864 * saleDetailsArray.length)
          // | selector | domainSeparator | length + offset | saleDetailsArray  | length + offset | sellerSignatures | length + offset | cosignatures | length + offset | feesOnTop   |
          uint256 constant BASE_MSG_LENGTH_BULK_BUY_LISTINGS = 292;
          uint256 constant BASE_MSG_LENGTH_BULK_BUY_LISTINGS_PER_ITEM = 864;
          // | 4        | 32              | 32           | 64              | 32 * length                 | 64              | 512 * length      | 64              | 96 * length          | 64              | 32 + (96 + (32 * proof.length)) | 64              | 192 * length | 64              | 64 * length | = 452 bytes + (1024 * saleDetailsArray.length) + (32 * proof.length [for each element])
          // | selector | domainSeparator | struct info? | length + offset | isCollectionLevelOfferArray | length + offset | saleDetailsArray  | length + offset | buyerSignaturesArray | length + offset | tokenSetProof                   | length + offset | cosignatures | length + offset | feesOnTop   |
          uint256 constant BASE_MSG_LENGTH_BULK_ACCEPT_OFFERS = 452;
          uint256 constant BASE_MSG_LENGTH_BULK_ACCEPT_OFFERS_PER_ITEM = 1024;
          // | 4        | 32              | 64       | 128        | 64              | 320 * length | 64              | 96 * length      | 64              | 192 * length | = 420 bytes + (608 * items.length)
          // | selector | domainSeparator | feeOnTop | sweepOrder | length + offset | items        | length + offset | signedSellOrders | length + offset | cosignatures |
          uint256 constant BASE_MSG_LENGTH_SWEEP_COLLECTION = 420;
          uint256 constant BASE_MSG_LENGTH_SWEEP_COLLECTION_PER_ITEM = 608;// SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          /// @dev Thrown when an order is an ERC721 order and the amount is not one.
          error PaymentProcessor__AmountForERC721SalesMustEqualOne();
          /// @dev Thrown when an order is an ERC1155 order and the amount is zero.
          error PaymentProcessor__AmountForERC1155SalesGreaterThanZero();
          /// @dev Thrown when an offer is being accepted and the payment method is the chain native token.
          error PaymentProcessor__BadPaymentMethod();
          /// @dev Thrown when adding or removing a payment method from a whitelist that the caller does not own.
          error PaymentProcessor__CallerDoesNotOwnPaymentMethodWhitelist();
          /**
           * @dev Thrown when modifying collection payment settings, pricing bounds, or trusted channels on a collection
           * @dev that the caller is not the owner of or a member of the default admin role for.
           */
          error PaymentProcessor__CallerMustHaveElevatedPermissionsForSpecifiedNFT();
          /// @dev Thrown when setting a collection or token pricing constraint with a floor price greater than ceiling price.
          error PaymentProcessor__CeilingPriceMustBeGreaterThanFloorPrice();
          /// @dev Thrown when adding a trusted channel that is not a trusted forwarder deployed by the trusted forwarder factory.
          error PaymentProcessor__ChannelIsNotTrustedForwarder();
          /// @dev Thrown when removing a payment method from a whitelist when that payment method is not on the whitelist.
          error PaymentProcessor__CoinIsNotApproved();
          /// @dev Thrown when the current block time is greater than the expiration time for the cosignature.
          error PaymentProcessor__CosignatureHasExpired();
          /// @dev Thrown when the cosigner has self destructed.
          error PaymentProcessor__CosignerHasSelfDestructed();
          /// @dev Thrown when a token failed to transfer to the beneficiary and partial fills are disabled.
          error PaymentProcessor__DispensingTokenWasUnsuccessful();
          /// @dev Thrown when a maker is a contract and the contract does not return the correct EIP1271 response to validate the signature.
          error PaymentProcessor__EIP1271SignatureInvalid();
          /// @dev Thrown when a native token transfer call fails to transfer the tokens.
          error PaymentProcessor__FailedToTransferProceeds();
          /// @dev Thrown when the additional fee on top exceeds the item price.
          error PaymentProcessor__FeeOnTopCannotBeGreaterThanItemPrice();
          /// @dev Thrown when the supplied root hash, token and proof do not match.
          error PaymentProcessor__IncorrectTokenSetMerkleProof();
          /// @dev Thrown when an input array has zero items in a location where it must have items.
          error PaymentProcessor__InputArrayLengthCannotBeZero();
          /// @dev Thrown when multiple input arrays have different lengths but are required to be the same length.
          error PaymentProcessor__InputArrayLengthMismatch();
          /// @dev Thrown when Payment Processor or a module is being deployed with invalid constructor arguments.
          error PaymentProcessor__InvalidConstructorArguments();
          /// @dev Thrown when the maker or taker is a banned account on the collection being traded.
          error PaymentProcessor__MakerOrTakerIsBannedAccount();
          /// @dev Thrown when the combined marketplace and royalty fees will exceed the item price.
          error PaymentProcessor__MarketplaceAndRoyaltyFeesWillExceedSalePrice();
          /// @dev Thrown when the recovered address from a cosignature does not match the order cosigner.
          error PaymentProcessor__NotAuthorizedByCosigner();
          /// @dev Thrown when the ERC2981 or backfilled royalties exceed the maximum fee specified by the order maker.
          error PaymentProcessor__OnchainRoyaltiesExceedMaximumApprovedRoyaltyFee();
          /// @dev Thrown when the current block timestamp is greater than the order expiration time.
          error PaymentProcessor__OrderHasExpired();
          /// @dev Thrown when attempting to fill a partially fillable order that has already been filled or cancelled.
          error PaymentProcessor__OrderIsEitherCancelledOrFilled();
          /// @dev Thrown when attempting to execute a sweep order for partially fillable orders.
          error PaymentProcessor__OrderProtocolERC1155FillPartialUnsupportedInSweeps();
          /// @dev Thrown when attempting to partially fill an order where the item price is not equally divisible by the amount of tokens.
          error PaymentProcessor__PartialFillsNotSupportedForNonDivisibleItems();
          /// @dev Thrown when attempting to execute an order with a payment method that is not allowed by the collection payment settings.
          error PaymentProcessor__PaymentCoinIsNotAnApprovedPaymentMethod();
          /// @dev Thrown when adding a payment method to a whitelist when that payment method is already on the list.
          error PaymentProcessor__PaymentMethodIsAlreadyApproved();
          /// @dev Thrown when setting collection payment settings with a whitelist id that does not exist.
          error PaymentProcessor__PaymentMethodWhitelistDoesNotExist();
          /// @dev Thrown when attempting to transfer ownership of a payment method whitelist to the zero address.
          error PaymentProcessor__PaymentMethodWhitelistOwnershipCannotBeTransferredToZeroAddress();
          /// @dev Thrown when distributing payments and fees in native token and the amount remaining is less than the amount to distribute.
          error PaymentProcessor__RanOutOfNativeFunds();
          /// @dev Thrown when attempting to set a royalty backfill numerator that would result in royalties greater than 100%.
          error PaymentProcessor__RoyaltyBackfillNumeratorCannotExceedFeeDenominator();
          /// @dev Thrown when attempting to set a royalty bounty numerator that would result in royalty bounties greater than 100%.
          error PaymentProcessor__RoyaltyBountyNumeratorCannotExceedFeeDenominator();
          /// @dev Thrown when a collection is set to pricing constraints and the item price exceeds the defined maximum price.
          error PaymentProcessor__SalePriceAboveMaximumCeiling();
          /// @dev Thrown when a collection is set to pricing constraints and the item price is below the defined minimum price.
          error PaymentProcessor__SalePriceBelowMinimumFloor();
          /// @dev Thrown when a maker's nonce has already been used for an executed order or cancelled by the maker.
          error PaymentProcessor__SignatureAlreadyUsedOrRevoked();
          /**
           * @dev Thrown when a collection is set to block untrusted channels and the order execution originates from a channel 
           * @dev that is not in the collection's trusted channel list.
           */ 
          error PaymentProcessor__TradeOriginatedFromUntrustedChannel();
          /// @dev Thrown when a trading of a specific collection has been paused by the collection owner or admin.
          error PaymentProcessor__TradingIsPausedForCollection();
          /**
           * @dev Thrown when attempting to fill a partially fillable order and the amount available to fill 
           * @dev is less than the specified minimum to fill.
           */
          error PaymentProcessor__UnableToFillMinimumRequestedQuantity();
          /// @dev Thrown when the recovered signer for an order does not match the order maker.
          error PaymentProcessor__UnauthorizedOrder();
          /// @dev Thrown when the taker on a cosigned order does not match the taker on the cosignature.
          error PaymentProcessor__UnauthorizedTaker();
          /// @dev Thrown when the Payment Processor or a module is being deployed with uninitialized configuration values.
          error PaymentProcessor__UninitializedConfiguration();// 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 v4.4.1 (interfaces/IERC1271.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC1271 standard signature validation method for
           * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
           *
           * _Available since v4.1._
           */
          interface IERC1271 {
              /**
               * @dev Should return whether the signature provided is valid for the provided data
               * @param hash      Hash of the data to be signed
               * @param signature Signature byte array associated with _data
               */
              function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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.9.3) (token/ERC20/utils/SafeERC20.sol)
          pragma solidity ^0.8.0;
          import "../IERC20.sol";
          import "../extensions/IERC20Permit.sol";
          import "../../../utils/Address.sol";
          /**
           * @title SafeERC20
           * @dev Wrappers around ERC20 operations that throw on failure (when the token
           * contract returns false). Tokens that return no value (and instead revert or
           * throw on failure) are also supported, non-reverting calls are assumed to be
           * successful.
           * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
           * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
           */
          library SafeERC20 {
              using Address for address;
              /**
               * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeTransfer(IERC20 token, address to, uint256 value) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
              }
              /**
               * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
               * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
               */
              function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
              }
              /**
               * @dev Deprecated. This function has issues similar to the ones found in
               * {IERC20-approve}, and its usage is discouraged.
               *
               * Whenever possible, use {safeIncreaseAllowance} and
               * {safeDecreaseAllowance} instead.
               */
              function safeApprove(IERC20 token, address spender, uint256 value) internal {
                  // safeApprove should only be called when setting an initial allowance,
                  // or when resetting it to zero. To increase and decrease it, use
                  // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                  require(
                      (value == 0) || (token.allowance(address(this), spender) == 0),
                      "SafeERC20: approve from non-zero to non-zero allowance"
                  );
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
              }
              /**
               * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  uint256 oldAllowance = token.allowance(address(this), spender);
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
              }
              /**
               * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  unchecked {
                      uint256 oldAllowance = token.allowance(address(this), spender);
                      require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                  }
              }
              /**
               * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
               * to be set to zero before setting it to a non-zero value, such as USDT.
               */
              function forceApprove(IERC20 token, address spender, uint256 value) internal {
                  bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                  if (!_callOptionalReturnBool(token, approvalCall)) {
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                      _callOptionalReturn(token, approvalCall);
                  }
              }
              /**
               * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
               * Revert on invalid signature.
               */
              function safePermit(
                  IERC20Permit token,
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) internal {
                  uint256 nonceBefore = token.nonces(owner);
                  token.permit(owner, spender, value, deadline, v, r, s);
                  uint256 nonceAfter = token.nonces(owner);
                  require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
              }
              /**
               * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
               * on the return value: the return value is optional (but if data is returned, it must not be false).
               * @param token The token targeted by the call.
               * @param data The call data (encoded using abi.encode or one of its variants).
               */
              function _callOptionalReturn(IERC20 token, bytes memory data) private {
                  // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                  // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                  // the target address contains contract code and also asserts for success in the low-level call.
                  bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                  require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
              }
              /**
               * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
               * on the return value: the return value is optional (but if data is returned, it must not be false).
               * @param token The token targeted by the call.
               * @param data The call data (encoded using abi.encode or one of its variants).
               *
               * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
               */
              function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                  // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                  // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                  // and not revert is the subcall reverts.
                  (bool success, bytes memory returndata) = address(token).call(data);
                  return
                      success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (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.9.0) (token/ERC1155/IERC1155.sol)
          pragma solidity ^0.8.0;
          import "../../utils/introspection/IERC165.sol";
          /**
           * @dev Required interface of an ERC1155 compliant contract, as defined in the
           * https://eips.ethereum.org/EIPS/eip-1155[EIP].
           *
           * _Available since v3.1._
           */
          interface IERC1155 is IERC165 {
              /**
               * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
               */
              event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
              /**
               * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
               * transfers.
               */
              event TransferBatch(
                  address indexed operator,
                  address indexed from,
                  address indexed to,
                  uint256[] ids,
                  uint256[] values
              );
              /**
               * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
               * `approved`.
               */
              event ApprovalForAll(address indexed account, address indexed operator, bool approved);
              /**
               * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
               *
               * If an {URI} event was emitted for `id`, the standard
               * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
               * returned by {IERC1155MetadataURI-uri}.
               */
              event URI(string value, uint256 indexed id);
              /**
               * @dev Returns the amount of tokens of token type `id` owned by `account`.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               */
              function balanceOf(address account, uint256 id) external view returns (uint256);
              /**
               * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
               *
               * Requirements:
               *
               * - `accounts` and `ids` must have the same length.
               */
              function balanceOfBatch(
                  address[] calldata accounts,
                  uint256[] calldata ids
              ) external view returns (uint256[] memory);
              /**
               * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
               *
               * Emits an {ApprovalForAll} event.
               *
               * Requirements:
               *
               * - `operator` cannot be the caller.
               */
              function setApprovalForAll(address operator, bool approved) external;
              /**
               * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
               *
               * See {setApprovalForAll}.
               */
              function isApprovedForAll(address account, address operator) external view returns (bool);
              /**
               * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
               *
               * Emits a {TransferSingle} event.
               *
               * Requirements:
               *
               * - `to` cannot be the zero address.
               * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
               * - `from` must have a balance of tokens of type `id` of at least `amount`.
               * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
               * acceptance magic value.
               */
              function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
              /**
               * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
               *
               * Emits a {TransferBatch} event.
               *
               * Requirements:
               *
               * - `ids` and `amounts` must have the same length.
               * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
               * acceptance magic value.
               */
              function safeBatchTransferFrom(
                  address from,
                  address to,
                  uint256[] calldata ids,
                  uint256[] calldata amounts,
                  bytes calldata data
              ) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
          pragma solidity ^0.8.0;
          import "../Strings.sol";
          /**
           * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
           *
           * These functions can be used to verify that a message was signed by the holder
           * of the private keys of a given address.
           */
          library ECDSA {
              enum RecoverError {
                  NoError,
                  InvalidSignature,
                  InvalidSignatureLength,
                  InvalidSignatureS,
                  InvalidSignatureV // Deprecated in v4.8
              }
              function _throwError(RecoverError error) private pure {
                  if (error == RecoverError.NoError) {
                      return; // no error: do nothing
                  } else if (error == RecoverError.InvalidSignature) {
                      revert("ECDSA: invalid signature");
                  } else if (error == RecoverError.InvalidSignatureLength) {
                      revert("ECDSA: invalid signature length");
                  } else if (error == RecoverError.InvalidSignatureS) {
                      revert("ECDSA: invalid signature 's' value");
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature` or error string. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               *
               * Documentation for signature generation:
               * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
               * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
                  if (signature.length == 65) {
                      bytes32 r;
                      bytes32 s;
                      uint8 v;
                      // ecrecover takes the signature parameters, and the only way to get them
                      // currently is to use assembly.
                      /// @solidity memory-safe-assembly
                      assembly {
                          r := mload(add(signature, 0x20))
                          s := mload(add(signature, 0x40))
                          v := byte(0, mload(add(signature, 0x60)))
                      }
                      return tryRecover(hash, v, r, s);
                  } else {
                      return (address(0), RecoverError.InvalidSignatureLength);
                  }
              }
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature`. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               */
              function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, signature);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
               *
               * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
                  bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                  uint8 v = uint8((uint256(vs) >> 255) + 27);
                  return tryRecover(hash, v, r, s);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
               *
               * _Available since v4.2._
               */
              function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, r, vs);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
               * `r` and `s` signature fields separately.
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
                  // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                  // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                  // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                  // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                  //
                  // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                  // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                  // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                  // these malleable signatures as well.
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      return (address(0), RecoverError.InvalidSignatureS);
                  }
                  // If the signature is valid (and not malleable), return the signer address
                  address signer = ecrecover(hash, v, r, s);
                  if (signer == address(0)) {
                      return (address(0), RecoverError.InvalidSignature);
                  }
                  return (signer, RecoverError.NoError);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `v`,
               * `r` and `s` signature fields separately.
               */
              function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
                  _throwError(error);
                  return recovered;
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from a `hash`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
                  // 32 is the length in bytes of hash,
                  // enforced by the type signature above
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(0x00, "\\x19Ethereum Signed Message:\
          32")
                      mstore(0x1c, hash)
                      message := keccak256(0x00, 0x3c)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Message, created from `s`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
          ", Strings.toString(s.length), s));
              }
              /**
               * @dev Returns an Ethereum Signed Typed Data, created from a
               * `domainSeparator` and a `structHash`. This produces hash corresponding
               * to the one signed with the
               * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
               * JSON-RPC method as part of EIP-712.
               *
               * See {recover}.
               */
              function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      let ptr := mload(0x40)
                      mstore(ptr, "\\x19\\x01")
                      mstore(add(ptr, 0x02), domainSeparator)
                      mstore(add(ptr, 0x22), structHash)
                      data := keccak256(ptr, 0x42)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Data with intended validator, created from a
               * `validator` and `data` according to the version 0 of EIP-191.
               *
               * See {recover}.
               */
              function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev These functions deal with verification of Merkle Tree proofs.
           *
           * The tree and the proofs can be generated using our
           * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
           * You will find a quickstart guide in the readme.
           *
           * WARNING: You should avoid using leaf values that are 64 bytes long prior to
           * hashing, or use a hash function other than keccak256 for hashing leaves.
           * This is because the concatenation of a sorted pair of internal nodes in
           * the merkle tree could be reinterpreted as a leaf value.
           * OpenZeppelin's JavaScript library generates merkle trees that are safe
           * against this attack out of the box.
           */
          library MerkleProof {
              /**
               * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
               * defined by `root`. For this, a `proof` must be provided, containing
               * sibling hashes on the branch from the leaf to the root of the tree. Each
               * pair of leaves and each pair of pre-images are assumed to be sorted.
               */
              function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
                  return processProof(proof, leaf) == root;
              }
              /**
               * @dev Calldata version of {verify}
               *
               * _Available since v4.7._
               */
              function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
                  return processProofCalldata(proof, leaf) == root;
              }
              /**
               * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
               * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
               * hash matches the root of the tree. When processing the proof, the pairs
               * of leafs & pre-images are assumed to be sorted.
               *
               * _Available since v4.4._
               */
              function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
                  bytes32 computedHash = leaf;
                  for (uint256 i = 0; i < proof.length; i++) {
                      computedHash = _hashPair(computedHash, proof[i]);
                  }
                  return computedHash;
              }
              /**
               * @dev Calldata version of {processProof}
               *
               * _Available since v4.7._
               */
              function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
                  bytes32 computedHash = leaf;
                  for (uint256 i = 0; i < proof.length; i++) {
                      computedHash = _hashPair(computedHash, proof[i]);
                  }
                  return computedHash;
              }
              /**
               * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
               * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
               *
               * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
               *
               * _Available since v4.7._
               */
              function multiProofVerify(
                  bytes32[] memory proof,
                  bool[] memory proofFlags,
                  bytes32 root,
                  bytes32[] memory leaves
              ) internal pure returns (bool) {
                  return processMultiProof(proof, proofFlags, leaves) == root;
              }
              /**
               * @dev Calldata version of {multiProofVerify}
               *
               * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
               *
               * _Available since v4.7._
               */
              function multiProofVerifyCalldata(
                  bytes32[] calldata proof,
                  bool[] calldata proofFlags,
                  bytes32 root,
                  bytes32[] memory leaves
              ) internal pure returns (bool) {
                  return processMultiProofCalldata(proof, proofFlags, leaves) == root;
              }
              /**
               * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
               * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
               * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
               * respectively.
               *
               * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
               * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
               * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
               *
               * _Available since v4.7._
               */
              function processMultiProof(
                  bytes32[] memory proof,
                  bool[] memory proofFlags,
                  bytes32[] memory leaves
              ) internal pure returns (bytes32 merkleRoot) {
                  // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
                  // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
                  // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
                  // the merkle tree.
                  uint256 leavesLen = leaves.length;
                  uint256 proofLen = proof.length;
                  uint256 totalHashes = proofFlags.length;
                  // Check proof validity.
                  require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
                  // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
                  // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
                  bytes32[] memory hashes = new bytes32[](totalHashes);
                  uint256 leafPos = 0;
                  uint256 hashPos = 0;
                  uint256 proofPos = 0;
                  // At each step, we compute the next hash using two values:
                  // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
                  //   get the next hash.
                  // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
                  //   `proof` array.
                  for (uint256 i = 0; i < totalHashes; i++) {
                      bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                      bytes32 b = proofFlags[i]
                          ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                          : proof[proofPos++];
                      hashes[i] = _hashPair(a, b);
                  }
                  if (totalHashes > 0) {
                      require(proofPos == proofLen, "MerkleProof: invalid multiproof");
                      unchecked {
                          return hashes[totalHashes - 1];
                      }
                  } else if (leavesLen > 0) {
                      return leaves[0];
                  } else {
                      return proof[0];
                  }
              }
              /**
               * @dev Calldata version of {processMultiProof}.
               *
               * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
               *
               * _Available since v4.7._
               */
              function processMultiProofCalldata(
                  bytes32[] calldata proof,
                  bool[] calldata proofFlags,
                  bytes32[] memory leaves
              ) internal pure returns (bytes32 merkleRoot) {
                  // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
                  // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
                  // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
                  // the merkle tree.
                  uint256 leavesLen = leaves.length;
                  uint256 proofLen = proof.length;
                  uint256 totalHashes = proofFlags.length;
                  // Check proof validity.
                  require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
                  // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
                  // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
                  bytes32[] memory hashes = new bytes32[](totalHashes);
                  uint256 leafPos = 0;
                  uint256 hashPos = 0;
                  uint256 proofPos = 0;
                  // At each step, we compute the next hash using two values:
                  // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
                  //   get the next hash.
                  // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
                  //   `proof` array.
                  for (uint256 i = 0; i < totalHashes; i++) {
                      bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                      bytes32 b = proofFlags[i]
                          ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                          : proof[proofPos++];
                      hashes[i] = _hashPair(a, b);
                  }
                  if (totalHashes > 0) {
                      require(proofPos == proofLen, "MerkleProof: invalid multiproof");
                      unchecked {
                          return hashes[totalHashes - 1];
                      }
                  } else if (leavesLen > 0) {
                      return leaves[0];
                  } else {
                      return proof[0];
                  }
              }
              function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
                  return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
              }
              function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(0x00, a)
                      mstore(0x20, b)
                      value := keccak256(0x00, 0x40)
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.3) (metatx/ERC2771Context.sol)
          pragma solidity ^0.8.4;
          import "@openzeppelin/contracts/utils/Context.sol";
          import "./interfaces/ITrustedForwarderFactory.sol";
          /**
           * @title TrustedForwarderERC2771Context
           * @author Limit Break, Inc.
           * @notice Context variant that utilizes the TrustedForwarderFactory contract to determine if the sender is a trusted forwarder.
           */
          abstract contract TrustedForwarderERC2771Context is Context {
              ITrustedForwarderFactory private immutable _factory;
              constructor(address factory) {
                  _factory = ITrustedForwarderFactory(factory);
              }
              /**
               * @notice Returns true if the sender is a trusted forwarder, false otherwise.
               *
               * @dev    This function is required by ERC2771Context.
               *
               * @param forwarder The address to check.
               * @return True if the provided address is a trusted forwarder, false otherwise.
               */
              function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
                  return _factory.isTrustedForwarder(forwarder);
              }
              function _msgSender() internal view virtual override returns (address sender) {
                  if (_factory.isTrustedForwarder(msg.sender)) {
                      if (msg.data.length >= 20) {
                          // The assembly code is more direct than the Solidity version using `abi.decode`.
                          /// @solidity memory-safe-assembly
                          assembly {
                              sender := shr(96, calldataload(sub(calldatasize(), 20)))
                          }
                      } else {
                          return super._msgSender();
                      }
                  } else {
                      return super._msgSender();
                  }
              }
              function _msgData() internal view virtual override returns (bytes calldata data) {
                  if (_factory.isTrustedForwarder(msg.sender)) {
                      assembly {
                          let len := calldatasize()
                          // Create a slice that defaults to the entire calldata
                          data.offset := 0
                          data.length := len
                          // If the calldata is > 20 bytes, it contains the sender address at the end
                          // and needs to be truncated
                          if gt(len, 0x14) {
                              data.length := sub(len, 0x14)
                          }
                      }
                  } else {
                      return super._msgData();
                  }
              }
          }
          // SPDX-License-Identifier: BSL-1.1
          pragma solidity 0.8.19;
          import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
          /**
           * @dev Used internally to indicate which side of the order the taker is on.
           */
          enum Sides { 
              // 0: Taker is on buy side of order.
              Buy, 
              // 1: Taker is on sell side of order.
              Sell 
          }
          /**
           * @dev Defines condition to apply to order execution.
           */
          enum OrderProtocols { 
              // 0: ERC721 order that must execute in full or not at all.
              ERC721_FILL_OR_KILL,
              // 1: ERC1155 order that must execute in full or not at all.
              ERC1155_FILL_OR_KILL,
              // 2: ERC1155 order that may be partially executed.
              ERC1155_FILL_PARTIAL
          }
          /**
           * @dev Defines the rules applied to a collection for payments.
           */
          enum PaymentSettings { 
              // 0: Utilize Payment Processor default whitelist.
              DefaultPaymentMethodWhitelist,
              // 1: Allow any payment method.
              AllowAnyPaymentMethod,
              // 2: Use a custom payment method whitelist.
              CustomPaymentMethodWhitelist,
              // 3: Single payment method with floor and ceiling limits.
              PricingConstraints,
              // 4: Pauses trading for the collection.
              Paused
          }
          /**
           * @dev This struct is used internally for the deployment of the Payment Processor contract and 
           * @dev module deployments to define the default payment method whitelist.
           */
          struct DefaultPaymentMethods {
              address defaultPaymentMethod1;
              address defaultPaymentMethod2;
              address defaultPaymentMethod3;
              address defaultPaymentMethod4;
          }
          /**
           * @dev This struct is used internally for the deployment of the Payment Processor contract to define the
           * @dev module addresses to be used for the contract.
           */
          struct PaymentProcessorModules {
              address modulePaymentSettings;
              address moduleOnChainCancellation;
              address moduleTrades;
              address moduleTradesAdvanced;
          }
          /**
           * @dev This struct defines the payment settings parameters for a collection.
           *
           * @dev **paymentSettings**: The general rule definition for payment methods allowed.
           * @dev **paymentMethodWhitelistId**: The list id to be used when paymentSettings is set to CustomPaymentMethodWhitelist.
           * @dev **constraintedPricingPaymentMethod**: The payment method to be used when paymentSettings is set to PricingConstraints.
           * @dev **royaltyBackfillNumerator**: The royalty fee to apply to the collection when ERC2981 is not supported.
           * @dev **royaltyBountyNumerator**: The percentage of royalties the creator will grant to a marketplace for order fulfillment.
           * @dev **isRoyaltyBountyExclusive**: If true, royalty bounties will only be paid if the order marketplace is the set exclusive marketplace.
           * @dev **blockTradesFromUntrustedChannels**: If true, trades that originate from untrusted channels will not be executed.
           * @dev **blockBannedAccounts**: If true, banned accounts can be neither maker or taker for trades on a per-collection basis.
           */
          struct CollectionPaymentSettings {
              PaymentSettings paymentSettings;
              uint32 paymentMethodWhitelistId;
              address constrainedPricingPaymentMethod;
              uint16 royaltyBackfillNumerator;
              uint16 royaltyBountyNumerator;
              bool isRoyaltyBountyExclusive;
              bool blockTradesFromUntrustedChannels;
              bool blockBannedAccounts;
          }
          /**
           * @dev The `v`, `r`, and `s` components of an ECDSA signature.  For more information
           *      [refer to this article](https://medium.com/mycrypto/the-magic-of-digital-signatures-on-ethereum-98fe184dc9c7).
           */
          struct SignatureECDSA {
              uint8 v;
              bytes32 r;
              bytes32 s;
          }
          /**
           * @dev This struct defines order execution parameters.
           * 
           * @dev **protocol**: The order protocol to apply to the order.
           * @dev **maker**: The user that created and signed the order to be executed by a taker.
           * @dev **beneficiary**: The account that will receive the tokens.
           * @dev **marketplace**: The fee receiver of the marketplace that the order was created on.
           * @dev **fallbackRoyaltyRecipient**: The address that will receive royalties if ERC2981 
           * @dev is not supported by the collection and the creator has not defined backfilled royalties with Payment Processor.
           * @dev **paymentMethod**: The payment method for the order.
           * @dev **tokenAddress**: The address of the token collection the order is for.
           * @dev **tokenId**: The token id that the order is for.
           * @dev **amount**: The quantity of token the order is for.
           * @dev **itemPrice**: The price for the order in base units for the payment method.
           * @dev **nonce**: The maker's nonce for the order.
           * @dev **expiration**: The time, in seconds since the Unix epoch, that the order will expire.
           * @dev **marketplaceFeeNumerator**: The percentage fee that will be sent to the marketplace.
           * @dev **maxRoyaltyFeeNumerator**: The maximum royalty the maker is willing to accept. This will be used
           * @dev as the royalty amount when ERC2981 is not supported by the collection.
           * @dev **requestedFillAmount**: The amount of tokens for an ERC1155 partial fill order that the taker wants to fill.
           * @dev **minimumFillAmount**: The minimum amount of tokens for an ERC1155 partial fill order that the taker will accept.
           */
          struct Order {
              OrderProtocols protocol;
              address maker;
              address beneficiary;
              address marketplace;
              address fallbackRoyaltyRecipient;
              address paymentMethod;
              address tokenAddress;
              uint256 tokenId;
              uint248 amount;
              uint256 itemPrice;
              uint256 nonce;
              uint256 expiration;
              uint256 marketplaceFeeNumerator;
              uint256 maxRoyaltyFeeNumerator;
              uint248 requestedFillAmount;
              uint248 minimumFillAmount;
          }
          /**
           * @dev This struct defines the cosignature for verifying an order that is a cosigned order.
           *
           * @dev **signer**: The address that signed the cosigned order. This must match the cosigner that is part of the order signature.
           * @dev **taker**: The address of the order taker.
           * @dev **expiration**: The time, in seconds since the Unix epoch, that the cosignature will expire.
           * @dev The `v`, `r`, and `s` components of an ECDSA signature.  For more information
           *      [refer to this article](https://medium.com/mycrypto/the-magic-of-digital-signatures-on-ethereum-98fe184dc9c7).
           */
          struct Cosignature {
              address signer;
              address taker;
              uint256 expiration;
              uint8 v;
              bytes32 r;
              bytes32 s;
          }
          /**
           * @dev This struct defines an additional fee on top of an order, paid by taker.
           *
           * @dev **recipient**: The recipient of the additional fee.
           * @dev **amount**: The amount of the additional fee, in base units of the payment token.
           */
          struct FeeOnTop {
              address recipient;
              uint256 amount;
          }
          /**
           * @dev This struct defines the root hash and proof data for accepting an offer that is for a subset
           * @dev of items in a collection. The root hash must match the root hash specified as part of the 
           * @dev maker's order signature.
           * 
           * @dev **rootHash**: The merkletree root hash for the items that may be used to fulfill the offer order.
           * @dev **proof**: The merkle proofs for the item being supplied to fulfill the offer order.
           */
          struct TokenSetProof {
              bytes32 rootHash;
              bytes32[] proof;
          }
          /**
           * @dev Current state of a partially fillable order.
           */
          enum PartiallyFillableOrderState { 
              // 0: Order is open and may continue to be filled.
              Open, 
              // 1: Order has been completely filled.
              Filled, 
              // 2: Order has been cancelled.
              Cancelled
          }
          /**
           * @dev This struct defines the current status of a partially fillable order.
           * 
           * @dev **state**: The current state of the order as defined by the PartiallyFillableOrderState enum.
           * @dev **remainingFillableQuantity**: The remaining quantity that may be filled for the order.
           */
          struct PartiallyFillableOrderStatus {
              PartiallyFillableOrderState state;
              uint248 remainingFillableQuantity;
          }
          /**
           * @dev This struct defines the royalty backfill and bounty information. Its data for an
           * @dev order execution is constructed internally based on the collection settings and
           * @dev order execution details.
           * 
           * @dev **backfillNumerator**: The percentage of the order amount to pay as royalties
           * @dev for a collection that does not support ERC2981.
           * @dev **backfillReceiver**: The recipient of backfill royalties.
           * @dev **bountyNumerator**: The percentage of royalties to share with the marketplace for order fulfillment.
           * @dev **exclusiveMarketplace**: If non-zero, the address of the exclusive marketplace for royalty bounties.
           */
          struct RoyaltyBackfillAndBounty {
              uint16 backfillNumerator;
              address backfillReceiver;
              uint16 bountyNumerator;
              address exclusiveMarketplace;
          }
          /**
           * @dev This struct defines order information that is common to all items in a sweep order.
           * 
           * @dev **protocol**: The order protocol to apply to the order.
           * @dev **tokenAddress**: The address of the token collection the order is for.
           * @dev **paymentMethod**: The payment method for the order.
           * @dev **beneficiary**: The account that will receive the tokens.
           */
          struct SweepOrder {
              OrderProtocols protocol;
              address tokenAddress;
              address paymentMethod;
              address beneficiary;
          }
          /**
           * @dev This struct defines order information that is unique to each item of a sweep order.
           * @dev Combined with the SweepOrder header information to make an Order to execute.
           * 
           * @dev **maker**: The user that created and signed the order to be executed by a taker.
           * @dev **marketplace**: The marketplace that the order was created on.
           * @dev **fallbackRoyaltyRecipient**: The address that will receive royalties if ERC2981 
           * @dev is not supported by the collection and the creator has not defined royalties with Payment Processor.
           * @dev **tokenId**: The token id that the order is for.
           * @dev **amount**: The quantity of token the order is for.
           * @dev **itemPrice**: The price for the order in base units for the payment method.
           * @dev **nonce**: The maker's nonce for the order.
           * @dev **expiration**: The time, in seconds since the Unix epoch, that the order will expire.
           * @dev **marketplaceFeeNumerator**: The percentage fee that will be sent to the marketplace.
           * @dev **maxRoyaltyFeeNumerator**: The maximum royalty the maker is willing to accept. This will be used
           * @dev as the royalty amount when ERC2981 is not supported by the collection.
           */
          struct SweepItem {
              address maker;
              address marketplace;
              address fallbackRoyaltyRecipient;
              uint256 tokenId;
              uint248 amount;
              uint256 itemPrice;
              uint256 nonce;
              uint256 expiration;
              uint256 marketplaceFeeNumerator;
              uint256 maxRoyaltyFeeNumerator;
          }
          /**
           * @dev This struct is used to define pricing constraints for a collection or individual token.
           *
           * @dev **isSet**: When true, this indicates that pricing constraints are set for the collection or token.
           * @dev **floorPrice**: The minimum price for a token or collection.  This is only enforced when 
           * @dev `enforcePricingConstraints` is `true`.
           * @dev **ceilingPrice**: The maximum price for a token or collection.  This is only enforced when
           * @dev `enforcePricingConstraints` is `true`.
           */
          struct PricingBounds {
              bool isSet;
              uint120 floorPrice;
              uint120 ceilingPrice;
          }
          /**
           * @dev This struct defines the parameters for a bulk offer acceptance transaction.
           * 
           * 
           * @dev **isCollectionLevelOfferArray**: An array of flags to indicate if an offer is for any token in the collection.
           * @dev **saleDetailsArray**: An array of order execution details.
           * @dev **buyerSignaturesArray**: An array of maker signatures authorizing the order executions.
           * @dev **tokenSetProofsArray**: An array of root hashes and merkle proofs for offers that are a subset of tokens in a collection.
           * @dev **cosignaturesArray**: An array of additional cosignatures for cosigned orders, as applicable.
           * @dev **feesOnTopArray**: An array of additional fees to add on top of the orders, paid by taker.
           */
          struct BulkAcceptOffersParams {
              bool[] isCollectionLevelOfferArray;
              Order[] saleDetailsArray;
              SignatureECDSA[] buyerSignaturesArray;
              TokenSetProof[] tokenSetProofsArray;
              Cosignature[] cosignaturesArray;
              FeeOnTop[] feesOnTopArray;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
          struct SplitProceeds {
              address royaltyRecipient;
              uint256 royaltyProceeds;
              uint256 marketplaceProceeds;
              uint256 sellerProceeds;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
          struct PayoutsAccumulator {
              address lastSeller;
              address lastMarketplace;
              address lastRoyaltyRecipient;
              uint256 accumulatedSellerProceeds;
              uint256 accumulatedMarketplaceProceeds;
              uint256 accumulatedRoyaltyProceeds;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
          struct SweepCollectionComputeAndDistributeProceedsParams {
              IERC20 paymentCoin;
              FulfillOrderFunctionPointers fnPointers;
              FeeOnTop feeOnTop;
              RoyaltyBackfillAndBounty royaltyBackfillAndBounty;
              Order[] saleDetailsBatch;
          }
          /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
           struct FulfillOrderFunctionPointers {
              function(address,address,IERC20,uint256,uint256) funcPayout;
              function(address,address,address,uint256,uint256) returns (bool) funcDispenseToken;
              function(TradeContext memory, Order memory) funcEmitOrderExecutionEvent;
           }
           /** 
           * @dev Internal contract use only - this is not a public-facing struct
           */
           struct TradeContext {
              bytes32 domainSeparator;
              address channel;
              address taker;
              bool disablePartialFill;
           }
          /**
           * @dev This struct defines contract-level storage to be used across all Payment Processor modules.
           * @dev Follows the Diamond storage pattern.
           */
          struct PaymentProcessorStorage {
              /// @dev Tracks the most recently created payment method whitelist id
              uint32 lastPaymentMethodWhitelistId;
              /**
               * @notice User-specific master nonce that allows buyers and sellers to efficiently cancel all listings or offers
               *         they made previously. The master nonce for a user only changes when they explicitly request to revoke all
               *         existing listings and offers.
               *
               * @dev    When prompting sellers to sign a listing or offer, marketplaces must query the current master nonce of
               *         the user and include it in the listing/offer signature data.
               */
              mapping(address => uint256) masterNonces;
              /**
               * @dev The mapping key is the keccak256 hash of marketplace address and user address.
               *
               * @dev ```keccak256(abi.encodePacked(marketplace, user))```
               *
               * @dev The mapping value is another nested mapping of "slot" (key) to a bitmap (value) containing boolean flags
               *      indicating whether or not a nonce has been used or invalidated.
               *
               * @dev Marketplaces MUST track their own nonce by user, incrementing it for every signed listing or offer the user
               *      creates.  Listings and purchases may be executed out of order, and they may never be executed if orders
               *      are not matched prior to expriation.
               *
               * @dev The slot and the bit offset within the mapped value are computed as:
               *
               * @dev ```slot = nonce / 256;```
               * @dev ```offset = nonce % 256;```
               */
              mapping(address => mapping(uint256 => uint256)) invalidatedSignatures;
              
              /// @dev Mapping of token contract addresses to the collection payment settings.
              mapping (address => CollectionPaymentSettings) collectionPaymentSettings;
              /// @dev Mapping of payment method whitelist id to the owner address for the list.
              mapping (uint32 => address) paymentMethodWhitelistOwners;
              /// @dev Mapping of payment method whitelist id to a defined list of allowed payment methods.
              mapping (uint32 => EnumerableSet.AddressSet) collectionPaymentMethodWhitelists;
              /// @dev Mapping of token contract addresses to the collection-level pricing boundaries (floor and ceiling price).
              mapping (address => PricingBounds) collectionPricingBounds;
              /// @dev Mapping of token contract addresses to the token-level pricing boundaries (floor and ceiling price).
              mapping (address => mapping (uint256 => PricingBounds)) tokenPricingBounds;
              /// @dev Mapping of token contract addresses to the defined royalty backfill receiver addresses.
              mapping (address => address) collectionRoyaltyBackfillReceivers;
              /// @dev Mapping of token contract addresses to the defined exclusive bounty receivers.
              mapping (address => address) collectionExclusiveBountyReceivers;
              /// @dev Mapping of maker addresses to a mapping of order digests to the status of the partially fillable order for that digest.
              mapping (address => mapping(bytes32 => PartiallyFillableOrderStatus)) partiallyFillableOrderStatuses;
              /// @dev Mapping of token contract addresses to the defined list of trusted channels for the token contract.
              mapping (address => EnumerableSet.AddressSet) collectionTrustedChannels;
              /// @dev Mapping of token contract addresses to the defined list of banned accounts for the token contract.
              mapping (address => EnumerableSet.AddressSet) collectionBannedAccounts;
              /// @dev A mapping of all co-signers that have self-destructed and can never be used as cosigners again.
              mapping (address => bool) destroyedCosigners;
          }// 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.9.0) (token/ERC20/IERC20.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20 {
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
              /**
               * @dev Moves `amount` tokens from the caller's account to `to`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address to, uint256 amount) external returns (bool);
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
              /**
               * @dev Moves `amount` tokens from `from` to `to` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(address from, address to, uint256 amount) external returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
           * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
           *
           * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
           * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
           * need to send a transaction, and thus is not required to hold Ether at all.
           */
          interface IERC20Permit {
              /**
               * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
               * given ``owner``'s signed approval.
               *
               * IMPORTANT: The same issues {IERC20-approve} has related to transaction
               * ordering also apply here.
               *
               * Emits an {Approval} event.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               * - `deadline` must be a timestamp in the future.
               * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
               * over the EIP712-formatted function arguments.
               * - the signature must use ``owner``'s current nonce (see {nonces}).
               *
               * For more information on the signature format, see the
               * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
               * section].
               */
              function permit(
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) external;
              /**
               * @dev Returns the current nonce for `owner`. This value must be
               * included whenever a signature is generated for {permit}.
               *
               * Every successful call to {permit} increases ``owner``'s nonce by one. This
               * prevents a signature from being used multiple times.
               */
              function nonces(address owner) external view returns (uint256);
              /**
               * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
               */
              // solhint-disable-next-line func-name-mixedcase
              function DOMAIN_SEPARATOR() external view returns (bytes32);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
          pragma solidity ^0.8.0;
          import "./math/Math.sol";
          import "./math/SignedMath.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 `int256` to its ASCII `string` decimal representation.
               */
              function toString(int256 value) internal pure returns (string memory) {
                  return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  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);
              }
              /**
               * @dev Returns true if the two strings are equal.
               */
              function equal(string memory a, string memory b) internal pure returns (bool) {
                  return keccak256(bytes(a)) == keccak256(bytes(b));
              }
          }
          // 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
          pragma solidity ^0.8.4;
          interface ITrustedForwarderFactory {
              error TrustedForwarderFactory__TrustedForwarderInitFailed(address admin, address appSigner);
              event TrustedForwarderCreated(address indexed trustedForwarder);
              function cloneTrustedForwarder(address admin, address appSigner, bytes32 salt)
                  external
                  returns (address trustedForwarder);
              function forwarders(address) external view returns (bool);
              function isTrustedForwarder(address sender) external view returns (bool);
              function trustedForwarderImplementation() external view returns (address);
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
          // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```solidity
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           *
           * [WARNING]
           * ====
           * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
           * unusable.
           * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
           *
           * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
           * array of EnumerableSet.
           * ====
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastValue = set._values[lastIndex];
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastValue;
                          // Update the index for the moved value
                          set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                      }
                      // Delete the slot where the moved value was stored
                      set._values.pop();
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
              // Bytes32Set
              struct Bytes32Set {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  bytes32[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // AddressSet
              struct AddressSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // UintSet
              struct UintSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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) {
                          // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                          // The surrounding unchecked block does not change this fact.
                          // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1, "Math: mulDiv overflow");
                      ///////////////////////////////////////////////
                      // 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 256, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard signed math utilities missing in the Solidity language.
           */
          library SignedMath {
              /**
               * @dev Returns the largest of two signed numbers.
               */
              function max(int256 a, int256 b) internal pure returns (int256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two signed numbers.
               */
              function min(int256 a, int256 b) internal pure returns (int256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two signed numbers without overflow.
               * The result is rounded towards zero.
               */
              function average(int256 a, int256 b) internal pure returns (int256) {
                  // Formula from the book "Hacker's Delight"
                  int256 x = (a & b) + ((a ^ b) >> 1);
                  return x + (int256(uint256(x) >> 255) & (a ^ b));
              }
              /**
               * @dev Returns the absolute unsigned value of a signed value.
               */
              function abs(int256 n) internal pure returns (uint256) {
                  unchecked {
                      // must be unchecked in order to support `n = type(int256).min`
                      return uint256(n >= 0 ? n : -n);
                  }
              }
          }
          

          File 7 of 7: TrustedForwarderFactory
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.4;
          import "@openzeppelin/contracts/proxy/Clones.sol";
          contract TrustedForwarderFactory {
              error TrustedForwarderFactory__TrustedForwarderInitFailed(address admin, address appSigner);
              event TrustedForwarderCreated(address indexed creator, address indexed trustedForwarder);
              // keccak256("__TrustedForwarder_init(address,address)")
              bytes4 constant private INIT_SELECTOR = 0x81ab13d7;
              address immutable public trustedForwarderImplementation;
              mapping(address => bool) public forwarders;
              constructor(address trustedForwarderImplementation_) {
                  trustedForwarderImplementation = trustedForwarderImplementation_;
              }
              /**
               * @notice Returns true if the sender is a trusted forwarder, false otherwise.
               * @notice Addresses are added to the `forwarders` mapping when they are cloned via the `cloneTrustedForwarder` function.
               *
               * @dev    This function allows for the TrustedForwarder contracts to be used as trusted forwarders within the TrustedForwarderERC2771Context mixin.
               * 
               * @param sender The address to check.
               * @return True if the sender is a trusted forwarder, false otherwise.
               */
              function isTrustedForwarder(address sender) external view returns (bool) {
                  return forwarders[sender];
              }
              /**
               * @notice Clones the TrustedForwarder implementation and initializes it.
               *
               * @dev    To prevent hostile deployments, we hash the sender's address with the salt to create the final salt.
               * @dev    This prevents the mining of specific contract addresses for deterministic deployments, but still allows for
               * @dev    a canonical address to be created for each sender.
               *
               * @param admin             The address to assign the admin role to.
               * @param appSigner         The address to assign the app signer role to. This will be ignored if `enableAppSigner` is false.
               * @param salt              The salt to use for the deterministic deployment.  This is hashed with the sender's address to create the final salt.
               *
               * @return trustedForwarder The address of the newly created TrustedForwarder contract.
               */
              function cloneTrustedForwarder(address admin, address appSigner, bytes32 salt) external returns (address trustedForwarder) {
                  trustedForwarder = Clones.cloneDeterministic(trustedForwarderImplementation, keccak256(abi.encode(msg.sender, salt)));
                  (bool success, ) = trustedForwarder.call(abi.encodeWithSelector(INIT_SELECTOR, admin, appSigner));
                  if (!success) {
                      revert TrustedForwarderFactory__TrustedForwarderInitFailed(admin, appSigner);
                  }
                  forwarders[trustedForwarder] = true;
                  emit TrustedForwarderCreated(msg.sender, trustedForwarder);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
           * deploying minimal proxy contracts, also known as "clones".
           *
           * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
           * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
           *
           * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
           * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
           * deterministic method.
           *
           * _Available since v3.4._
           */
          library Clones {
              /**
               * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
               *
               * This function uses the create opcode, which should never revert.
               */
              function clone(address implementation) internal returns (address instance) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
                      // of the `implementation` address with the bytecode before the address.
                      mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
                      // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
                      mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
                      instance := create(0, 0x09, 0x37)
                  }
                  require(instance != address(0), "ERC1167: create failed");
              }
              /**
               * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
               *
               * This function uses the create2 opcode and a `salt` to deterministically deploy
               * the clone. Using the same `implementation` and `salt` multiple time will revert, since
               * the clones cannot be deployed twice at the same address.
               */
              function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
                      // of the `implementation` address with the bytecode before the address.
                      mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
                      // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
                      mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
                      instance := create2(0, 0x09, 0x37, salt)
                  }
                  require(instance != address(0), "ERC1167: create2 failed");
              }
              /**
               * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
               */
              function predictDeterministicAddress(
                  address implementation,
                  bytes32 salt,
                  address deployer
              ) internal pure returns (address predicted) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      let ptr := mload(0x40)
                      mstore(add(ptr, 0x38), deployer)
                      mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
                      mstore(add(ptr, 0x14), implementation)
                      mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
                      mstore(add(ptr, 0x58), salt)
                      mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
                      predicted := keccak256(add(ptr, 0x43), 0x55)
                  }
              }
              /**
               * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
               */
              function predictDeterministicAddress(
                  address implementation,
                  bytes32 salt
              ) internal view returns (address predicted) {
                  return predictDeterministicAddress(implementation, salt, address(this));
              }
          }