ETH Price: $2,445.15 (+1.33%)

Transaction Decoder

Block:
18905785 at Dec-31-2023 01:33:35 PM +UTC
Transaction Fee:
0.000900889004735706 ETH $2.20
Gas Used:
63,894 Gas / 14.099743399 Gwei

Emitted Events:

119 ERC1967Proxy.0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31( 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31, 0x000000000000000000000000b5507aa0efd9e1b6c343c9ec3f5b4e5c40cef654, 0x0000000000000000000000001e0049783f008a0085193e00003d00cd54003c71, 0000000000000000000000000000000000000000000000000000000000000001 )

Account State Difference:

  Address   Before After State Difference Code
(Titan Builder)
17.20366469376774857 Eth17.20367108316774857 Eth0.0000063894
0xB052D9CC...19f84d500
0xB5507Aa0...C40cEF654
0.04976382910186693 Eth
Nonce: 816
0.048862940097131224 Eth
Nonce: 817
0.000900889004735706

Execution Trace

ERC1967Proxy.a22cb465( )
  • EsnxComponent.setApprovalForAll( operator=0x1E0049783F008A0085193E00003D00cd54003c71, approved=True )
    • OperatorFilterRegistry.isOperatorAllowed( registrant=0xB052D9CC92c8CE58010880b4d9AE6ec19f84d500, operator=0x1E0049783F008A0085193E00003D00cd54003c71 ) => ( True )
      setApprovalForAll[EsnxComponent (ln:161)]
      File 1 of 3: ERC1967Proxy
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.0;
      
      /**
       * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
       * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
       * be specified by overriding the virtual {_implementation} function.
       *
       * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
       * different contract through the {_delegate} function.
       *
       * The success and return data of the delegated call will be returned back to the caller of the proxy.
       */
      abstract contract Proxy {
          /**
           * @dev Delegates the current call to `implementation`.
           *
           * This function does not return to its internall call site, it will return directly to the external caller.
           */
          function _delegate(address implementation) internal virtual {
              // solhint-disable-next-line no-inline-assembly
              assembly {
              // Copy msg.data. We take full control of memory in this inline assembly
              // block because it will not return to Solidity code. We overwrite the
              // Solidity scratch pad at memory position 0.
                  calldatacopy(0, 0, calldatasize())
      
              // Call the implementation.
              // out and outsize are 0 because we don't know the size yet.
                  let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
      
              // Copy the returned data.
                  returndatacopy(0, 0, returndatasize())
      
                  switch result
                  // delegatecall returns 0 on error.
                  case 0 { revert(0, returndatasize()) }
                  default { return(0, returndatasize()) }
              }
          }
      
          /**
           * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
           * and {_fallback} should delegate.
           */
          function _implementation() internal view virtual returns (address);
      
          /**
           * @dev Delegates the current call to the address returned by `_implementation()`.
           *
           * This function does not return to its internall call site, it will return directly to the external caller.
           */
          function _fallback() internal virtual {
              _beforeFallback();
              _delegate(_implementation());
          }
      
          /**
           * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
           * function in the contract matches the call data.
           */
          fallback () external payable virtual {
              _fallback();
          }
      
          /**
           * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
           * is empty.
           */
          receive () external payable virtual {
              _fallback();
          }
      
          /**
           * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
           * call, or as part of the Solidity `fallback` or `receive` functions.
           *
           * If overriden should call `super._beforeFallback()`.
           */
          function _beforeFallback() internal virtual {
          }
      }
      
      
      /**
       * @dev This abstract contract provides getters and event emitting update functions for
       * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
       *
       * _Available since v4.1._
       *
       */
      abstract contract ERC1967Upgrade {
          // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
          bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
      
          /**
           * @dev Storage slot with the address of the current implementation.
           * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
           * validated in the constructor.
           */
          bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
      
          /**
           * @dev Emitted when the implementation is upgraded.
           */
          event Upgraded(address indexed implementation);
      
          /**
           * @dev Returns the current implementation address.
           */
          function _getImplementation() internal view returns (address) {
              return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
          }
      
          /**
           * @dev Stores a new address in the EIP1967 implementation slot.
           */
          function _setImplementation(address newImplementation) private {
              require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
              StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
          }
      
          /**
           * @dev Perform implementation upgrade
           *
           * Emits an {Upgraded} event.
           */
          function _upgradeTo(address newImplementation) internal {
              _setImplementation(newImplementation);
              emit Upgraded(newImplementation);
          }
      
          /**
           * @dev Perform implementation upgrade with additional setup call.
           *
           * Emits an {Upgraded} event.
           */
          function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
              _setImplementation(newImplementation);
              emit Upgraded(newImplementation);
              if (data.length > 0 || forceCall) {
                  Address.functionDelegateCall(newImplementation, data);
              }
          }
      
          /**
           * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
           *
           * Emits an {Upgraded} event.
           */
          function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
              address oldImplementation = _getImplementation();
      
              // Initial upgrade and setup call
              _setImplementation(newImplementation);
              if (data.length > 0 || forceCall) {
                  Address.functionDelegateCall(newImplementation, data);
              }
      
              // Perform rollback test if not already in progress
              StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
              if (!rollbackTesting.value) {
                  // Trigger rollback using upgradeTo from the new implementation
                  rollbackTesting.value = true;
                  Address.functionDelegateCall(
                      newImplementation,
                      abi.encodeWithSignature(
                          "upgradeTo(address)",
                          oldImplementation
                      )
                  );
                  rollbackTesting.value = false;
                  // Check rollback was effective
                  require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                  // Finally reset to the new implementation and log the upgrade
                  _setImplementation(newImplementation);
                  emit Upgraded(newImplementation);
              }
          }
      
          /**
           * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
           * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
           *
           * Emits a {BeaconUpgraded} event.
           */
          function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
              _setBeacon(newBeacon);
              emit BeaconUpgraded(newBeacon);
              if (data.length > 0 || forceCall) {
                  Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
              }
          }
      
          /**
           * @dev Storage slot with the admin of the contract.
           * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
           * validated in the constructor.
           */
          bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
      
          /**
           * @dev Emitted when the admin account has changed.
           */
          event AdminChanged(address previousAdmin, address newAdmin);
      
          /**
           * @dev Returns the current admin.
           */
          function _getAdmin() internal view returns (address) {
              return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
          }
      
          /**
           * @dev Stores a new address in the EIP1967 admin slot.
           */
          function _setAdmin(address newAdmin) private {
              require(newAdmin != address(0), "ERC1967: new admin is the zero address");
              StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
          }
      
          /**
           * @dev Changes the admin of the proxy.
           *
           * Emits an {AdminChanged} event.
           */
          function _changeAdmin(address newAdmin) internal {
              emit AdminChanged(_getAdmin(), newAdmin);
              _setAdmin(newAdmin);
          }
      
          /**
           * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
           * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
           */
          bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
      
          /**
           * @dev Emitted when the beacon is upgraded.
           */
          event BeaconUpgraded(address indexed beacon);
      
          /**
           * @dev Returns the current beacon.
           */
          function _getBeacon() internal view returns (address) {
              return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
          }
      
          /**
           * @dev Stores a new beacon in the EIP1967 beacon slot.
           */
          function _setBeacon(address newBeacon) private {
              require(
                  Address.isContract(newBeacon),
                  "ERC1967: new beacon is not a contract"
              );
              require(
                  Address.isContract(IBeacon(newBeacon).implementation()),
                  "ERC1967: beacon implementation is not a contract"
              );
              StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
          }
      }
      
      /**
       * @dev This is the interface that {BeaconProxy} expects of its beacon.
       */
      interface IBeacon {
          /**
           * @dev Must return an address that can be used as a delegate call target.
           *
           * {BeaconProxy} will check that this address is a contract.
           */
          function implementation() external view returns (address);
      }
      
      /**
       * @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
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies on extcodesize, which returns 0 for contracts in
              // construction, since the code is only stored at the end of the
              // constructor execution.
      
              uint256 size;
              // solhint-disable-next-line no-inline-assembly
              assembly { size := extcodesize(account) }
              return size > 0;
          }
      
          /**
           * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
           * `recipient`, forwarding all available gas and reverting on errors.
           *
           * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
           * of certain opcodes, possibly making contracts go over the 2300 gas limit
           * imposed by `transfer`, making them unable to receive funds via
           * `transfer`. {sendValue} removes this limitation.
           *
           * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
           *
           * IMPORTANT: because control is transferred to `recipient`, care must be
           * taken to not create reentrancy vulnerabilities. Consider using
           * {ReentrancyGuard} or the
           * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
      
              // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
              (bool success, ) = recipient.call{ value: amount }("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
      
          /**
           * @dev Performs a Solidity function call using a low level `call`. A
           * plain`call` is an unsafe replacement for a function call: use this
           * function instead.
           *
           * If `target` reverts with a revert reason, it is bubbled up by this
           * function (like regular Solidity function calls).
           *
           * Returns the raw returned data. To convert to the expected return value,
           * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
           *
           * Requirements:
           *
           * - `target` must be a contract.
           * - calling `target` with `data` must not revert.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCall(target, data, "Address: low-level call failed");
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
      
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              require(isContract(target), "Address: call to non-contract");
      
              // solhint-disable-next-line avoid-low-level-calls
              (bool success, bytes memory returndata) = target.call{ value: value }(data);
              return _verifyCallResult(success, returndata, errorMessage);
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
              require(isContract(target), "Address: static call to non-contract");
      
              // solhint-disable-next-line avoid-low-level-calls
              (bool success, bytes memory returndata) = target.staticcall(data);
              return _verifyCallResult(success, returndata, errorMessage);
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionDelegateCall(target, data, "Address: low-level delegate call failed");
          }
      
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
              require(isContract(target), "Address: delegate call to non-contract");
      
              // solhint-disable-next-line avoid-low-level-calls
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return _verifyCallResult(success, returndata, errorMessage);
          }
      
          function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
      
                      // solhint-disable-next-line no-inline-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
      }
      
      /**
       * @dev Library for reading and writing primitive types to specific storage slots.
       *
       * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
       * This library helps with reading and writing to such slots without the need for inline assembly.
       *
       * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
       *
       * Example usage to set ERC1967 implementation slot:
       * ```
       * contract ERC1967 {
       *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
       *
       *     function _getImplementation() internal view returns (address) {
       *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
       *     }
       *
       *     function _setImplementation(address newImplementation) internal {
       *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
       *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
       *     }
       * }
       * ```
       *
       * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
       */
      library StorageSlot {
          struct AddressSlot {
              address value;
          }
      
          struct BooleanSlot {
              bool value;
          }
      
          struct Bytes32Slot {
              bytes32 value;
          }
      
          struct Uint256Slot {
              uint256 value;
          }
      
          /**
           * @dev Returns an `AddressSlot` with member `value` located at `slot`.
           */
          function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
              assembly {
                  r.slot := slot
              }
          }
      
          /**
           * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
           */
          function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
              assembly {
                  r.slot := slot
              }
          }
      
          /**
           * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
           */
          function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
              assembly {
                  r.slot := slot
              }
          }
      
          /**
           * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
           */
          function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
              assembly {
                  r.slot := slot
              }
          }
      }
      
      /*
       * @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) {
              this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
              return msg.data;
          }
      }
      
      /**
       * @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 () {
              address msgSender = _msgSender();
              _owner = msgSender;
              emit OwnershipTransferred(address(0), msgSender);
          }
      
          /**
           * @dev Returns the address of the current owner.
           */
          function owner() public view virtual returns (address) {
              return _owner;
          }
      
          /**
           * @dev Throws if called by any account other than the owner.
           */
          modifier onlyOwner() {
              require(owner() == _msgSender(), "Ownable: caller is not the owner");
              _;
          }
      
          /**
           * @dev Leaves the contract without owner. It will not be possible to call
           * `onlyOwner` functions anymore. Can only be called by the current owner.
           *
           * NOTE: Renouncing ownership will leave the contract without an owner,
           * thereby removing any functionality that is only available to the owner.
           */
          function renounceOwnership() public virtual onlyOwner {
              emit OwnershipTransferred(_owner, address(0));
              _owner = 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");
              emit OwnershipTransferred(_owner, newOwner);
              _owner = newOwner;
          }
      }
      
      /**
       * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
       * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
       */
      contract ProxyAdmin is Ownable {
      
          /**
           * @dev Returns the current implementation of `proxy`.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
              // We need to manually run the static call since the getter cannot be flagged as view
              // bytes4(keccak256("implementation()")) == 0x5c60da1b
              (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
              require(success);
              return abi.decode(returndata, (address));
          }
      
          /**
           * @dev Returns the current admin of `proxy`.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
              // We need to manually run the static call since the getter cannot be flagged as view
              // bytes4(keccak256("admin()")) == 0xf851a440
              (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
              require(success);
              return abi.decode(returndata, (address));
          }
      
          /**
           * @dev Changes the admin of `proxy` to `newAdmin`.
           *
           * Requirements:
           *
           * - This contract must be the current admin of `proxy`.
           */
          function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
              proxy.changeAdmin(newAdmin);
          }
      
          /**
           * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
              proxy.upgradeTo(implementation);
          }
      
          /**
           * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
           * {TransparentUpgradeableProxy-upgradeToAndCall}.
           *
           * Requirements:
           *
           * - This contract must be the admin of `proxy`.
           */
          function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
              proxy.upgradeToAndCall{value: msg.value}(implementation, data);
          }
      }
      
      
      /**
       * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
       * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
       * continuation of the upgradability.
       *
       * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
       *
       * _Available since v4.1._
       */
      abstract contract UUPSUpgradeable is ERC1967Upgrade {
          function upgradeTo(address newImplementation) external virtual {
              _authorizeUpgrade(newImplementation);
              _upgradeToAndCallSecure(newImplementation, bytes(""), false);
          }
      
          function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
              _authorizeUpgrade(newImplementation);
              _upgradeToAndCallSecure(newImplementation, data, true);
          }
      
          function _authorizeUpgrade(address newImplementation) internal virtual;
      }
      
      
      abstract contract Proxiable is UUPSUpgradeable {
          function _authorizeUpgrade(address newImplementation) internal override {
              _beforeUpgrade(newImplementation);
          }
      
          function _beforeUpgrade(address newImplementation) internal virtual;
      }
      
      contract ChildOfProxiable is Proxiable {
          function _beforeUpgrade(address newImplementation) internal virtual override {}
      }
      
      
      /**
       * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
       * implementation address that can be changed. This address is stored in storage in the location specified by
       * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
       * implementation behind the proxy.
       */
      contract ERC1967Proxy is Proxy, ERC1967Upgrade {
          /**
           * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
           *
           * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
           * function call, and allows initializating the storage of the proxy like a Solidity constructor.
           */
          constructor(address _logic, bytes memory _data) payable {
              assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
              _upgradeToAndCall(_logic, _data, false);
          }
      
          /**
           * @dev Returns the current implementation address.
           */
          function _implementation() internal view virtual override returns (address impl) {
              return ERC1967Upgrade._getImplementation();
          }
      }
      
      /**
       * @dev This contract implements a proxy that is upgradeable by an admin.
       *
       * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
       * clashing], which can potentially be used in an attack, this contract uses the
       * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
       * things that go hand in hand:
       *
       * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
       * that call matches one of the admin functions exposed by the proxy itself.
       * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
       * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
       * "admin cannot fallback to proxy target".
       *
       * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
       * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
       * to sudden errors when trying to call a function from the proxy implementation.
       *
       * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
       * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
       */
      contract TransparentUpgradeableProxy is ERC1967Proxy {
          /**
           * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
           * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
           */
          constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
              assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
              _changeAdmin(admin_);
          }
      
          /**
           * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
           */
          modifier ifAdmin() {
              if (msg.sender == _getAdmin()) {
                  _;
              } else {
                  _fallback();
              }
          }
      
          /**
           * @dev Returns the current admin.
           *
           * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
           *
           * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
           * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
           * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
           */
          function admin() external ifAdmin returns (address admin_) {
              admin_ = _getAdmin();
          }
      
          /**
           * @dev Returns the current implementation.
           *
           * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
           *
           * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
           * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
           * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
           */
          function implementation() external ifAdmin returns (address implementation_) {
              implementation_ = _implementation();
          }
      
          /**
           * @dev Changes the admin of the proxy.
           *
           * Emits an {AdminChanged} event.
           *
           * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
           */
          function changeAdmin(address newAdmin) external virtual ifAdmin {
              _changeAdmin(newAdmin);
          }
      
          /**
           * @dev Upgrade the implementation of the proxy.
           *
           * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
           */
          function upgradeTo(address newImplementation) external ifAdmin {
              _upgradeToAndCall(newImplementation, bytes(""), false);
          }
      
          /**
           * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
           * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
           * proxied contract.
           *
           * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
           */
          function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
              _upgradeToAndCall(newImplementation, data, true);
          }
      
          /**
           * @dev Returns the current admin.
           */
          function _admin() internal view virtual returns (address) {
              return _getAdmin();
          }
      
          /**
           * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
           */
          function _beforeFallback() internal virtual override {
              require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
              super._beforeFallback();
          }
      }
      
      
      // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
      contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
          constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {}
      }

      File 2 of 3: EsnxComponent
      //SPDX-License-Identifier: BUSL-1.1
      pragma solidity ^0.8.17;
      /**
      `7MM"""YMM   .M"""bgd `7MN.   `7MF'`YMM'   `MP'
        MM    `7  ,MI    "Y   MMN.    M    VMb.  ,P
        MM   d    `MMb.       M YMb   M     `MM.M'
        MMmmMM      `YMMNq.   M  `MN. M       MMb
        MM   Y  , .     `MM   M   `MM.M     ,M'`Mb.
        MM     ,M Mb     dM   M     YMM    ,P   `MM.
      .JMMmmmmMMM P"Ybmmd"  .JML.    YM  .MM:.  .:MMa.
      powered by ctor.xyz
       */
      import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
      import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
      import "@openzeppelin/contracts-upgradeable/token/common/ERC2981Upgradeable.sol";
      import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
      import "closedsea/src/OperatorFilterer.sol";
      import "erc1155delta/contracts/extensions/ERC1155DeltaQueryableUpgradeable.sol";
      import "ctorlab-solidity/contracts/supply-control/DeflationSupplyCapLinear.sol";
      interface IEsnxMecha {
          function mint(address to, uint256[] calldata ids) external;
      }
      contract EsnxComponent is
          Initializable,
          UUPSUpgradeable,
          ERC1155DeltaQueryableUpgradeable,
          ERC2981Upgradeable,
          OwnableUpgradeable,
          OperatorFilterer
      {
          using DeflationSupplyCapLinear for DeflationSupplyCapLinear.DeflationSupplyCapLinearParameter;
          uint256 public constant HEAD_TOKEN_ID = 0;
          uint256 public constant BODY_TOKEN_ID = 1;
          uint256 public constant ARMS_TOKEN_ID = 2;
          uint256 public constant LEGS_TOKEN_ID = 3;
          uint256 public constant EQUIPMENT_TOKEN_ID = 4;
          uint256 public constant NUM_PARTS = 5;
          address public immutable recoder;
          IEsnxMecha public esnxMecha;
          uint256 public assemblingStartTime;
          uint256 public assemblingEndTime;
          DeflationSupplyCapLinear.DeflationSupplyCapLinearParameter
              public supplyCapParam;
          error NotRecoder();
          error NotEOA();
          error NotStarted();
          error Ended();
          error InvalidTime();
          error InvalidLength();
          error InvalidPart();
          modifier onlyRecoder() {
              if (msg.sender != recoder) {
                  revert NotRecoder();
              }
              _;
          }
          modifier onlyEOA() {
              if (msg.sender != tx.origin) {
                  revert NotEOA();
              }
              _;
          }
          modifier onlyDuring(uint256 startTime, uint256 endTime) {
              uint256 blockTime = block.timestamp;
              if (blockTime < startTime) {
                  revert NotStarted();
              }
              if (blockTime >= endTime) {
                  revert Ended();
              }
              _;
          }
          /// @custom:oz-upgrades-unsafe-allow constructor
          constructor(address recoder_) {
              _disableInitializers();
              recoder = recoder_;
          }
          function initialize() external initializer {
              __ERC1155Delta_init("https://api.elysiumshell.xyz/esnxc/{id}");
              __Ownable_init();
              _setDefaultRoyalty(
                  address(0xd188Db484A78C147dCb14EC8F12b5ca1fcBC17f5),
                  750
              );
              _registerForOperatorFiltering();
              assemblingStartTime = type(uint256).max;
              assemblingEndTime = type(uint256).max;
          }
          function supportsInterface(bytes4 interfaceId)
              public
              view
              override(ERC1155DeltaUpgradeable, ERC2981Upgradeable)
              returns (bool)
          {
              return super.supportsInterface(interfaceId);
          }
          function setUri(string calldata uri_) external onlyOwner {
              _setURI(uri_);
          }
          function setEsnxMecha(address esnxMecha_) external onlyOwner {
              esnxMecha = IEsnxMecha(esnxMecha_);
          }
          function setAssemblingTime(uint256 start, uint256 end) external onlyOwner {
              if (end <= start) {
                  revert InvalidTime();
              }
              assemblingStartTime = start;
              assemblingEndTime = end;
          }
          function setDefaultRoyalty(address receiver, uint96 feeNumerator)
              external
              onlyOwner
          {
              _setDefaultRoyalty(receiver, feeNumerator);
          }
          function setTokenRoyalty(
              uint256 tokenId,
              address receiver,
              uint96 feeNumerator
          ) external onlyOwner {
              _setTokenRoyalty(tokenId, receiver, feeNumerator);
          }
          function mint(address to) external onlyRecoder {
              supplyCapParam.checkMintingAndUpdate(_totalMinted(), NUM_PARTS);
              _mint(to, NUM_PARTS);
          }
          function totalMinted() external view returns (uint256) {
              return _totalMinted();
          }
          function assemble(uint256[] calldata ids)
              external
              onlyDuring(assemblingStartTime, assemblingEndTime)
              onlyEOA
          {
              if (ids.length != NUM_PARTS) {
                  revert InvalidLength();
              }
              _burnBatch(msg.sender, ids);
              esnxMecha.mint(msg.sender, ids);
          }
          function currentSupplyCap() external view returns (uint256) {
              return supplyCapParam.currentSupplyCap();
          }
          function availableForRecoding() external view returns (uint256) {
              return supplyCapParam.availableToMint(_totalMinted()) / NUM_PARTS;
          }
          function initializeSupplyCap(
              uint64 decayStart,
              uint64 decayPeriod,
              uint32 initialSupply,
              uint32 supplyDecay
          ) external onlyOwner {
              supplyCapParam.initializeParam(
                  decayStart,
                  decayPeriod,
                  initialSupply,
                  supplyDecay
              );
          }
          function _authorizeUpgrade(address) internal override onlyOwner {}
          function setApprovalForAll(address operator, bool approved)
              public
              override
              onlyAllowedOperatorApproval(operator)
          {
              super.setApprovalForAll(operator, approved);
          }
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              uint256 amount,
              bytes memory data
          ) public override onlyAllowedOperator(from) {
              super.safeTransferFrom(from, to, tokenId, amount, data);
          }
          function safeBatchTransferFrom(
              address from,
              address to,
              uint256[] memory ids,
              uint256[] memory amounts,
              bytes memory data
          ) public virtual override onlyAllowedOperator(from) {
              super.safeBatchTransferFrom(from, to, ids, amounts, data);
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.4;
      /// @notice Optimized and flexible operator filterer to abide to OpenSea's
      /// mandatory on-chain royalty enforcement in order for new collections to
      /// receive royalties.
      /// For more information, see:
      /// See: https://github.com/ProjectOpenSea/operator-filter-registry
      abstract contract OperatorFilterer {
          /// @dev The default OpenSea operator blocklist subscription.
          address internal constant _DEFAULT_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6;
          /// @dev The OpenSea operator filter registry.
          address internal constant _OPERATOR_FILTER_REGISTRY = 0x000000000000AAeB6D7670E522A718067333cd4E;
          /// @dev Registers the current contract to OpenSea's operator filter,
          /// and subscribe to the default OpenSea operator blocklist.
          /// Note: Will not revert nor update existing settings for repeated registration.
          function _registerForOperatorFiltering() internal virtual {
              _registerForOperatorFiltering(_DEFAULT_SUBSCRIPTION, true);
          }
          /// @dev Registers the current contract to OpenSea's operator filter.
          /// Note: Will not revert nor update existing settings for repeated registration.
          function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual {
              /// @solidity memory-safe-assembly
              assembly {
                  let functionSelector := 0x7d3e3dbe // `registerAndSubscribe(address,address)`.
                  // Clean the upper 96 bits of `subscriptionOrRegistrantToCopy` in case they are dirty.
                  subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy))
                  // prettier-ignore
                  for {} iszero(subscribe) {} {
                      if iszero(subscriptionOrRegistrantToCopy) {
                          functionSelector := 0x4420e486 // `register(address)`.
                          break
                      }
                      functionSelector := 0xa0af2903 // `registerAndCopyEntries(address,address)`.
                      break
                  }
                  // Store the function selector.
                  mstore(0x00, shl(224, functionSelector))
                  // Store the `address(this)`.
                  mstore(0x04, address())
                  // Store the `subscriptionOrRegistrantToCopy`.
                  mstore(0x24, subscriptionOrRegistrantToCopy)
                  // Register into the registry.
                  pop(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x00))
                  // Restore the part of the free memory pointer that was overwritten,
                  // which is guaranteed to be zero, because of Solidity's memory size limits.
                  mstore(0x24, 0)
              }
          }
          /// @dev Modifier to guard a function and revert if the caller is a blocked operator.
          modifier onlyAllowedOperator(address from) virtual {
              if (from != msg.sender)
                  if (!_isPriorityOperator(msg.sender))
                      if (_operatorFilteringEnabled()) _revertIfBlocked(msg.sender);
              _;
          }
          /// @dev Modifier to guard a function from approving a blocked operator..
          modifier onlyAllowedOperatorApproval(address operator) virtual {
              if (!_isPriorityOperator(operator))
                  if (_operatorFilteringEnabled()) _revertIfBlocked(operator);
              _;
          }
          /// @dev Helper function that reverts if the `operator` is blocked by the registry.
          function _revertIfBlocked(address operator) private view {
              /// @solidity memory-safe-assembly
              assembly {
                  // Store the function selector of `isOperatorAllowed(address,address)`,
                  // shifted left by 6 bytes, which is enough for 8tb of memory.
                  // We waste 6-3 = 3 bytes to save on 6 runtime gas (PUSH1 0x224 SHL).
                  mstore(0x00, 0xc6171134001122334455)
                  // Store the `address(this)`.
                  mstore(0x1a, address())
                  // Store the `operator`.
                  mstore(0x3a, operator)
                  // `isOperatorAllowed` always returns true if it does not revert.
                  if iszero(staticcall(gas(), _OPERATOR_FILTER_REGISTRY, 0x16, 0x44, 0x00, 0x00)) {
                      // Bubble up the revert if the staticcall reverts.
                      returndatacopy(0x00, 0x00, returndatasize())
                      revert(0x00, returndatasize())
                  }
                  // We'll skip checking if `from` is inside the blacklist.
                  // Even though that can block transferring out of wrapper contracts,
                  // we don't want tokens to be stuck.
                  // Restore the part of the free memory pointer that was overwritten,
                  // which is guaranteed to be zero, if less than 8tb of memory is used.
                  mstore(0x3a, 0)
              }
          }
          /// @dev For deriving contracts to override, so that operator filtering
          /// can be turned on / off.
          function _operatorFilteringEnabled() internal view virtual returns (bool) {
              return true;
          }
          /// @dev For deriving contracts to override, such that preferred marketplaces can
          /// skip the operator filtering, helping users save gas.
          function _isPriorityOperator(address) internal view virtual returns (bool) {
              return false;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)
      pragma solidity ^0.8.2;
      import "../../utils/AddressUpgradeable.sol";
      /**
       * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
       * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
       * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
       * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
       *
       * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
       * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
       * case an upgrade adds a module that needs to be initialized.
       *
       * For example:
       *
       * [.hljs-theme-light.nopadding]
       * ```
       * contract MyToken is ERC20Upgradeable {
       *     function initialize() initializer public {
       *         __ERC20_init("MyToken", "MTK");
       *     }
       * }
       * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
       *     function initializeV2() reinitializer(2) public {
       *         __ERC20Permit_init("MyToken");
       *     }
       * }
       * ```
       *
       * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
       * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
       *
       * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
       * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
       *
       * [CAUTION]
       * ====
       * Avoid leaving a contract uninitialized.
       *
       * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
       * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
       * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
       *
       * [.hljs-theme-light.nopadding]
       * ```
       * /// @custom:oz-upgrades-unsafe-allow constructor
       * constructor() {
       *     _disableInitializers();
       * }
       * ```
       * ====
       */
      abstract contract Initializable {
          /**
           * @dev Indicates that the contract has been initialized.
           * @custom:oz-retyped-from bool
           */
          uint8 private _initialized;
          /**
           * @dev Indicates that the contract is in the process of being initialized.
           */
          bool private _initializing;
          /**
           * @dev Triggered when the contract has been initialized or reinitialized.
           */
          event Initialized(uint8 version);
          /**
           * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
           * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
           */
          modifier initializer() {
              bool isTopLevelCall = !_initializing;
              require(
                  (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                  "Initializable: contract is already initialized"
              );
              _initialized = 1;
              if (isTopLevelCall) {
                  _initializing = true;
              }
              _;
              if (isTopLevelCall) {
                  _initializing = false;
                  emit Initialized(1);
              }
          }
          /**
           * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
           * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
           * used to initialize parent contracts.
           *
           * `initializer` is equivalent to `reinitializer(1)`, so 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.
           *
           * 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.
           */
          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.
           */
          function _disableInitializers() internal virtual {
              require(!_initializing, "Initializable: contract is initializing");
              if (_initialized < type(uint8).max) {
                  _initialized = type(uint8).max;
                  emit Initialized(type(uint8).max);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
      pragma solidity ^0.8.0;
      import "../utils/ContextUpgradeable.sol";
      import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
          address private _owner;
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /**
           * @dev Initializes the contract setting the deployer as the initial owner.
           */
          function __Ownable_init() internal onlyInitializing {
              __Ownable_init_unchained();
          }
          function __Ownable_init_unchained() internal onlyInitializing {
              _transferOwnership(_msgSender());
          }
          /**
           * @dev Throws if called by any account other than the owner.
           */
          modifier onlyOwner() {
              _checkOwner();
              _;
          }
          /**
           * @dev Returns the address of the current owner.
           */
          function owner() public view virtual returns (address) {
              return _owner;
          }
          /**
           * @dev Throws if the sender is not the owner.
           */
          function _checkOwner() internal view virtual {
              require(owner() == _msgSender(), "Ownable: caller is not the owner");
          }
          /**
           * @dev Leaves the contract without owner. It will not be possible to call
           * `onlyOwner` functions anymore. Can only be called by the current owner.
           *
           * NOTE: Renouncing ownership will leave the contract without an owner,
           * thereby removing any functionality that is only available to the owner.
           */
          function renounceOwnership() public virtual onlyOwner {
              _transferOwnership(address(0));
          }
          /**
           * @dev Transfers ownership of the contract to a new account (`newOwner`).
           * Can only be called by the current owner.
           */
          function transferOwnership(address newOwner) public virtual onlyOwner {
              require(newOwner != address(0), "Ownable: new owner is the zero address");
              _transferOwnership(newOwner);
          }
          /**
           * @dev Transfers ownership of the contract to a new account (`newOwner`).
           * Internal function without access restriction.
           */
          function _transferOwnership(address newOwner) internal virtual {
              address oldOwner = _owner;
              _owner = newOwner;
              emit OwnershipTransferred(oldOwner, newOwner);
          }
          /**
           * @dev This empty reserved space is put in place to allow future versions to add new
           * variables without shifting down storage in the inheritance chain.
           * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
           */
          uint256[49] private __gap;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
      pragma solidity ^0.8.0;
      import "../../interfaces/IERC2981Upgradeable.sol";
      import "../../utils/introspection/ERC165Upgradeable.sol";
      import "../../proxy/utils/Initializable.sol";
      /**
       * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
       *
       * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
       * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
       *
       * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
       * fee is specified in basis points by default.
       *
       * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
       * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
       * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
       *
       * _Available since v4.5._
       */
      abstract contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {
          function __ERC2981_init() internal onlyInitializing {
          }
          function __ERC2981_init_unchained() internal onlyInitializing {
          }
          struct RoyaltyInfo {
              address receiver;
              uint96 royaltyFraction;
          }
          RoyaltyInfo private _defaultRoyaltyInfo;
          mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC165Upgradeable) returns (bool) {
              return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId);
          }
          /**
           * @inheritdoc IERC2981Upgradeable
           */
          function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
              RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
              if (royalty.receiver == address(0)) {
                  royalty = _defaultRoyaltyInfo;
              }
              uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
              return (royalty.receiver, royaltyAmount);
          }
          /**
           * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
           * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
           * override.
           */
          function _feeDenominator() internal pure virtual returns (uint96) {
              return 10000;
          }
          /**
           * @dev Sets the royalty information that all ids in this contract will default to.
           *
           * Requirements:
           *
           * - `receiver` cannot be the zero address.
           * - `feeNumerator` cannot be greater than the fee denominator.
           */
          function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
              require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
              require(receiver != address(0), "ERC2981: invalid receiver");
              _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
          }
          /**
           * @dev Removes default royalty information.
           */
          function _deleteDefaultRoyalty() internal virtual {
              delete _defaultRoyaltyInfo;
          }
          /**
           * @dev Sets the royalty information for a specific token id, overriding the global default.
           *
           * Requirements:
           *
           * - `receiver` cannot be the zero address.
           * - `feeNumerator` cannot be greater than the fee denominator.
           */
          function _setTokenRoyalty(
              uint256 tokenId,
              address receiver,
              uint96 feeNumerator
          ) internal virtual {
              require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
              require(receiver != address(0), "ERC2981: Invalid parameters");
              _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
          }
          /**
           * @dev Resets royalty information for the token id back to the global default.
           */
          function _resetTokenRoyalty(uint256 tokenId) internal virtual {
              delete _tokenRoyaltyInfo[tokenId];
          }
          /**
           * @dev This empty reserved space is put in place to allow future versions to add new
           * variables without shifting down storage in the inheritance chain.
           * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
           */
          uint256[48] private __gap;
      }
      // SPDX-License-Identifier: MIT
      // Creator: Ctor Lab (https://ctor.xyz)
      pragma solidity ^0.8.0;
      library DeflationSupplyCapLinear {
          error ExceedSupplyCap();
          error InvalidDecayPeriod();
          // All the parameters are packed into a single storage slot for gas saving.
          // In practice, 2** 32 token supply is enough for most of the NFT applications.
          struct DeflationSupplyCapLinearParameter{
              uint64 decayPeriod; // The time for supply cap to decay if no minting events happend.
              uint32 lastSupplyCap; // The supply cap of the last minting event.
              uint32 supplyDecay; // Amount of reduction in the supply cap every `decayPeriod`.
              uint64 lastMint; // Timestamp of the last minting event.
          }
          /// @dev Insert this function in the minting logic.
          function checkMintingAndUpdate(
              DeflationSupplyCapLinearParameter storage param,
              uint256 totalMinted,
              uint256 numToMint
          ) internal {
              uint256 supplyCap = currentSupplyCap(param);
              if(numToMint + totalMinted > supplyCap ) {
                  revert ExceedSupplyCap();
              }
              if(block.timestamp > param.lastMint) {
                  param.lastMint = uint64(block.timestamp);
                  param.lastSupplyCap = uint32(supplyCap);
              }
          }
          function currentSupplyCap(
              DeflationSupplyCapLinearParameter storage param
          ) internal view returns (uint256) {
              uint256 time = block.timestamp;
              if (time < param.lastMint) {
                  return param.lastSupplyCap;
              }
              if(param.decayPeriod == 0) {
                  return 0;
              }
              uint256 reduction = 0;
              unchecked {
                  reduction = (time - uint256(param.lastMint)) / uint256(param.decayPeriod) * param.supplyDecay;
              }
              
              if(reduction > param.lastSupplyCap) {
                  return 0;
              }
              unchecked {
                  return param.lastSupplyCap - reduction;
              }
          }
          /// @dev Calculate the number of token that is still available to be minted.
          function availableToMint(
              DeflationSupplyCapLinearParameter storage param,
              uint256 totalMinted
          ) internal view returns (uint256){
              uint256 supplyCap = currentSupplyCap(param);
              if(supplyCap > totalMinted) {
                  unchecked {
                      return supplyCap - totalMinted;
                  }  
              } 
              return 0;
          }
          function initializeParam(
              DeflationSupplyCapLinearParameter storage param,
              uint64 decayStart,
              uint64 decayPeriod,
              uint32 initialSupply,
              uint32 supplyDecay
          ) internal {
              if(decayPeriod == 0) {
                  revert InvalidDecayPeriod();
              }
              
              param.decayPeriod = decayPeriod;
              param.lastSupplyCap = initialSupply;
              param.supplyDecay = supplyDecay;
              param.lastMint = decayStart;
          }
      }// SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol)
      pragma solidity ^0.8.0;
      import "../../interfaces/draft-IERC1822Upgradeable.sol";
      import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
      import "./Initializable.sol";
      /**
       * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
       * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
       *
       * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
       * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
       * `UUPSUpgradeable` with a custom implementation of upgrades.
       *
       * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
       *
       * _Available since v4.1._
       */
      abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
          function __UUPSUpgradeable_init() internal onlyInitializing {
          }
          function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
          }
          /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
          address private immutable __self = address(this);
          /**
           * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
           * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
           * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
           * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
           * fail.
           */
          modifier onlyProxy() {
              require(address(this) != __self, "Function must be called through delegatecall");
              require(_getImplementation() == __self, "Function must be called through active proxy");
              _;
          }
          /**
           * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
           * callable on the implementing contract but not through proxies.
           */
          modifier notDelegated() {
              require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
              _;
          }
          /**
           * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
           * implementation. It is used to validate that the this implementation remains valid after an upgrade.
           *
           * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
           * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
           * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
           */
          function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
              return _IMPLEMENTATION_SLOT;
          }
          /**
           * @dev Upgrade the implementation of the proxy to `newImplementation`.
           *
           * Calls {_authorizeUpgrade}.
           *
           * Emits an {Upgraded} event.
           */
          function upgradeTo(address newImplementation) external virtual onlyProxy {
              _authorizeUpgrade(newImplementation);
              _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
          }
          /**
           * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
           * encoded in `data`.
           *
           * Calls {_authorizeUpgrade}.
           *
           * Emits an {Upgraded} event.
           */
          function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
              _authorizeUpgrade(newImplementation);
              _upgradeToAndCallUUPS(newImplementation, data, true);
          }
          /**
           * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
           * {upgradeTo} and {upgradeToAndCall}.
           *
           * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
           *
           * ```solidity
           * function _authorizeUpgrade(address) internal override onlyOwner {}
           * ```
           */
          function _authorizeUpgrade(address newImplementation) internal virtual;
          /**
           * @dev This empty reserved space is put in place to allow future versions to add new
           * variables without shifting down storage in the inheritance chain.
           * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
           */
          uint256[50] private __gap;
      }
      // SPDX-License-Identifier: MIT
      // Creator: Ctor Lab (https://ctor.xyz)
      pragma solidity ^0.8.0;
      import "solidity-bits/contracts/BitMaps.sol";
      import "../ERC1155DeltaUpgradeable.sol";
      import "./IERC1155DeltaQueryable.sol";
      abstract contract ERC1155DeltaQueryableUpgradeable is IERC1155DeltaQueryable, ERC1155DeltaUpgradeable {
          using BitMaps for BitMaps.BitMap;
          /**
           * @dev Returns the number of tokens owned by `owner`.
           */
          function balanceOf(address owner) public view virtual override returns (uint256) {
              return balanceOf(owner, _startTokenId(), _nextTokenId());
          }
          /**
           * @dev Returns the number of tokens owned by `owner`,
           * in the range [`start`, `stop`)
           * (i.e. `start <= tokenId < stop`).
           *
           * Requirements:
           *
           * - `start < stop`
           */
          function balanceOf(address owner, uint256 start, uint256 stop) public view virtual override returns (uint256) {
              return _owned[owner].popcountB(start, stop - start);
          }
          /**
           * @dev Returns an array of token IDs owned by `owner`,
           * in the range [`start`, `stop`)
           * (i.e. `start <= tokenId < stop`).
           *
           * This function allows for tokens to be queried if the collection
           * grows too big for a single call of {ERC1155DelataQueryable-tokensOfOwner}.
           *
           * Requirements:
           *
           * - `start < stop`
           */
          function tokensOfOwnerIn(
              address owner,
              uint256 start,
              uint256 stop
          ) public view virtual override returns (uint256[] memory) {
              unchecked {
                  if (start >= stop) revert InvalidQueryRange();
                  
                  
                  // Set `start = max(start, _startTokenId())`.
                  if (start < _startTokenId()) {
                      start = _startTokenId();
                  }
                  
                  // Set `stop = min(stop, stopLimit)`.
                  uint256 stopLimit = _nextTokenId();
                  if (stop > stopLimit) {
                      stop = stopLimit;
                  }
                  uint256 tokenIdsLength;
                  if(start < stop) {
                      tokenIdsLength = balanceOf(owner, start, stop);
                  } else {
                      tokenIdsLength = 0;
                  }
                  
                  uint256[] memory tokenIds = new uint256[](tokenIdsLength);
                  BitMaps.BitMap storage bmap = _owned[owner];
                  
                  for ((uint256 i, uint256 tokenIdsIdx) = (start, 0); tokenIdsIdx != tokenIdsLength; ++i) {
                      if(bmap.get(i) ) {
                          tokenIds[tokenIdsIdx++] = i;
                      }
                  }
                  return tokenIds;
              }
          }
          /**
           * @dev Returns an array of token IDs owned by `owner`.
           *
           * This function scans the ownership mapping and is O(`totalSupply`) in complexity.
           * It is meant to be called off-chain.
           *
           * See {ERC1155DeltaQueryable-tokensOfOwnerIn} for splitting the scan into
           * multiple smaller scans if the collection is large enough to cause
           * an out-of-gas error (10K collections should be fine).
           */
          function tokensOfOwner(address owner) public view virtual override returns (uint256[] memory) {
              if(_totalMinted() == 0) {
                  return new uint256[](0);
              }
              return tokensOfOwnerIn(owner, _startTokenId(), _nextTokenId());
          }
      }// SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
      pragma solidity ^0.8.1;
      /**
       * @dev Collection of functions related to the address type
       */
      library AddressUpgradeable {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           * ====
           *
           * [IMPORTANT]
           * ====
           * You shouldn't rely on `isContract` to protect against flash loan attacks!
           *
           * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
           * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
           * constructor.
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies on extcodesize/address.code.length, which returns 0
              // for contracts in construction, since the code is only stored at the end
              // of the constructor execution.
              return account.code.length > 0;
          }
          /**
           * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
           * `recipient`, forwarding all available gas and reverting on errors.
           *
           * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
           * of certain opcodes, possibly making contracts go over the 2300 gas limit
           * imposed by `transfer`, making them unable to receive funds via
           * `transfer`. {sendValue} removes this limitation.
           *
           * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
           *
           * IMPORTANT: because control is transferred to `recipient`, care must be
           * taken to not create reentrancy vulnerabilities. Consider using
           * {ReentrancyGuard} or the
           * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
              (bool success, ) = recipient.call{value: amount}("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
          /**
           * @dev Performs a Solidity function call using a low level `call`. A
           * plain `call` is an unsafe replacement for a function call: use this
           * function instead.
           *
           * If `target` reverts with a revert reason, it is bubbled up by this
           * function (like regular Solidity function calls).
           *
           * Returns the raw returned data. To convert to the expected return value,
           * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
           *
           * Requirements:
           *
           * - `target` must be a contract.
           * - calling `target` with `data` must not revert.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCall(target, data, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              require(isContract(target), "Address: call to non-contract");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResult(success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              require(isContract(target), "Address: static call to non-contract");
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResult(success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
      pragma solidity ^0.8.0;
      import "../proxy/utils/Initializable.sol";
      /**
       * @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 ContextUpgradeable is Initializable {
          function __Context_init() internal onlyInitializing {
          }
          function __Context_init_unchained() internal onlyInitializing {
          }
          function _msgSender() internal view virtual returns (address) {
              return msg.sender;
          }
          function _msgData() internal view virtual returns (bytes calldata) {
              return msg.data;
          }
          /**
           * @dev This empty reserved space is put in place to allow future versions to add new
           * variables without shifting down storage in the inheritance chain.
           * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
           */
          uint256[50] private __gap;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
      pragma solidity ^0.8.0;
      import "../utils/introspection/IERC165Upgradeable.sol";
      /**
       * @dev Interface for the NFT Royalty Standard.
       *
       * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
       * support for royalty payments across all NFT marketplaces and ecosystem participants.
       *
       * _Available since v4.5._
       */
      interface IERC2981Upgradeable is IERC165Upgradeable {
          /**
           * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
           * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
           */
          function royaltyInfo(uint256 tokenId, uint256 salePrice)
              external
              view
              returns (address receiver, uint256 royaltyAmount);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.0;
      import "./IERC165Upgradeable.sol";
      import "../../proxy/utils/Initializable.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
       * for the additional interface id that will be supported. For example:
       *
       * ```solidity
       * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
       *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
       * }
       * ```
       *
       * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
       */
      abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
          function __ERC165_init() internal onlyInitializing {
          }
          function __ERC165_init_unchained() internal onlyInitializing {
          }
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IERC165Upgradeable).interfaceId;
          }
          /**
           * @dev This empty reserved space is put in place to allow future versions to add new
           * variables without shifting down storage in the inheritance chain.
           * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
           */
          uint256[50] private __gap;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * Implementers can declare support of contract interfaces, which can then be
       * queried by others ({ERC165Checker}).
       *
       * For an implementation, see {ERC165}.
       */
      interface IERC165Upgradeable {
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30 000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
       * proxy whose upgrades are fully controlled by the current implementation.
       */
      interface IERC1822ProxiableUpgradeable {
          /**
           * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
           * address.
           *
           * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
           * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
           * function revert if invoked through a proxy.
           */
          function proxiableUUID() external view returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
      pragma solidity ^0.8.2;
      import "../beacon/IBeaconUpgradeable.sol";
      import "../../interfaces/draft-IERC1822Upgradeable.sol";
      import "../../utils/AddressUpgradeable.sol";
      import "../../utils/StorageSlotUpgradeable.sol";
      import "../utils/Initializable.sol";
      /**
       * @dev This abstract contract provides getters and event emitting update functions for
       * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
       *
       * _Available since v4.1._
       *
       * @custom:oz-upgrades-unsafe-allow delegatecall
       */
      abstract contract ERC1967UpgradeUpgradeable is Initializable {
          function __ERC1967Upgrade_init() internal onlyInitializing {
          }
          function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
          }
          // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
          bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
          /**
           * @dev Storage slot with the address of the current implementation.
           * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
           * validated in the constructor.
           */
          bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
          /**
           * @dev Emitted when the implementation is upgraded.
           */
          event Upgraded(address indexed implementation);
          /**
           * @dev Returns the current implementation address.
           */
          function _getImplementation() internal view returns (address) {
              return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
          }
          /**
           * @dev Stores a new address in the EIP1967 implementation slot.
           */
          function _setImplementation(address newImplementation) private {
              require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
              StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
          }
          /**
           * @dev Perform implementation upgrade
           *
           * Emits an {Upgraded} event.
           */
          function _upgradeTo(address newImplementation) internal {
              _setImplementation(newImplementation);
              emit Upgraded(newImplementation);
          }
          /**
           * @dev Perform implementation upgrade with additional setup call.
           *
           * Emits an {Upgraded} event.
           */
          function _upgradeToAndCall(
              address newImplementation,
              bytes memory data,
              bool forceCall
          ) internal {
              _upgradeTo(newImplementation);
              if (data.length > 0 || forceCall) {
                  _functionDelegateCall(newImplementation, data);
              }
          }
          /**
           * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
           *
           * Emits an {Upgraded} event.
           */
          function _upgradeToAndCallUUPS(
              address newImplementation,
              bytes memory data,
              bool forceCall
          ) internal {
              // Upgrades from old implementations will perform a rollback test. This test requires the new
              // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
              // this special case will break upgrade paths from old UUPS implementation to new ones.
              if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
                  _setImplementation(newImplementation);
              } else {
                  try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                      require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
                  } catch {
                      revert("ERC1967Upgrade: new implementation is not UUPS");
                  }
                  _upgradeToAndCall(newImplementation, data, forceCall);
              }
          }
          /**
           * @dev Storage slot with the admin of the contract.
           * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
           * validated in the constructor.
           */
          bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
          /**
           * @dev Emitted when the admin account has changed.
           */
          event AdminChanged(address previousAdmin, address newAdmin);
          /**
           * @dev Returns the current admin.
           */
          function _getAdmin() internal view returns (address) {
              return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
          }
          /**
           * @dev Stores a new address in the EIP1967 admin slot.
           */
          function _setAdmin(address newAdmin) private {
              require(newAdmin != address(0), "ERC1967: new admin is the zero address");
              StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
          }
          /**
           * @dev Changes the admin of the proxy.
           *
           * Emits an {AdminChanged} event.
           */
          function _changeAdmin(address newAdmin) internal {
              emit AdminChanged(_getAdmin(), newAdmin);
              _setAdmin(newAdmin);
          }
          /**
           * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
           * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
           */
          bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
          /**
           * @dev Emitted when the beacon is upgraded.
           */
          event BeaconUpgraded(address indexed beacon);
          /**
           * @dev Returns the current beacon.
           */
          function _getBeacon() internal view returns (address) {
              return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
          }
          /**
           * @dev Stores a new beacon in the EIP1967 beacon slot.
           */
          function _setBeacon(address newBeacon) private {
              require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
              require(
                  AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
                  "ERC1967: beacon implementation is not a contract"
              );
              StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
          }
          /**
           * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
           * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
           *
           * Emits a {BeaconUpgraded} event.
           */
          function _upgradeBeaconToAndCall(
              address newBeacon,
              bytes memory data,
              bool forceCall
          ) internal {
              _setBeacon(newBeacon);
              emit BeaconUpgraded(newBeacon);
              if (data.length > 0 || forceCall) {
                  _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
              }
          }
          /**
           * @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) private returns (bytes memory) {
              require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
              // solhint-disable-next-line avoid-low-level-calls
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
          }
          /**
           * @dev This empty reserved space is put in place to allow future versions to add new
           * variables without shifting down storage in the inheritance chain.
           * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
           */
          uint256[50] private __gap;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Library for reading and writing primitive types to specific storage slots.
       *
       * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
       * This library helps with reading and writing to such slots without the need for inline assembly.
       *
       * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
       *
       * Example usage to set ERC1967 implementation slot:
       * ```
       * contract ERC1967 {
       *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
       *
       *     function _getImplementation() internal view returns (address) {
       *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
       *     }
       *
       *     function _setImplementation(address newImplementation) internal {
       *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
       *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
       *     }
       * }
       * ```
       *
       * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
       */
      library StorageSlotUpgradeable {
          struct AddressSlot {
              address value;
          }
          struct BooleanSlot {
              bool value;
          }
          struct Bytes32Slot {
              bytes32 value;
          }
          struct Uint256Slot {
              uint256 value;
          }
          /**
           * @dev Returns an `AddressSlot` with member `value` located at `slot`.
           */
          function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
              /// @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
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev This is the interface that {BeaconProxy} expects of its beacon.
       */
      interface IBeaconUpgradeable {
          /**
           * @dev Must return an address that can be used as a delegate call target.
           *
           * {BeaconProxy} will check that this address is a contract.
           */
          function implementation() external view returns (address);
      }
      // SPDX-License-Identifier: MIT
      // Creator: Ctor Lab (https://ctor.xyz)
      pragma solidity ^0.8.0;
      import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
      import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
      import "@openzeppelin/contracts-upgradeable/token/ERC1155/extensions/IERC1155MetadataURIUpgradeable.sol";
      import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
      import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
      import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
      import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
      import "solidity-bits/contracts/BitMaps.sol";
      import "./IERC1155Delta.sol";
      contract ERC1155DeltaUpgradeable is  Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, 
          IERC1155MetadataURIUpgradeable, IERC1155Delta {
          using AddressUpgradeable for address;
          using BitMaps for BitMaps.BitMap;
          // Mapping from accout to owned tokens
          mapping(address => BitMaps.BitMap) internal _owned;
          
          // Mapping from account to operator approvals
          mapping(address => mapping(address => bool)) private _operatorApprovals;
          // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
          string private _uri;
          // The next token ID to be minted.
          uint256 private _currentIndex;
          /**
           * @dev See {_setURI}.
           */
          function __ERC1155Delta_init(string memory uri_) internal onlyInitializing {
              __ERC1155Delta_init_unchained(uri_);
          }
          function __ERC1155Delta_init_unchained(string memory uri_) internal onlyInitializing {
              _setURI(uri_);
              _currentIndex = _startTokenId();
          }
          /**
           * @dev Returns the starting token ID.
           * To change the starting token ID, please override this function.
           */
          function _startTokenId() internal pure virtual returns (uint256) {
              return 0;
          }
          /**
           * @dev Returns the next token ID to be minted.
           */
          function _nextTokenId() internal view returns (uint256) {
              return _currentIndex;
          }
          /**
           * @dev Returns the total amount of tokens minted in the contract.
           */
          function _totalMinted() internal view returns (uint256) {
              return _nextTokenId() - _startTokenId();
          }
          /**
           * @dev Returns true if the account owns the `id` token.
           */
          function isOwnerOf(address account, uint256 id) public view virtual override returns(bool) {
              return _owned[account].get(id);
          }
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
              return
                  interfaceId == type(IERC1155Upgradeable).interfaceId ||
                  interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
                  interfaceId == type(IERC1155Delta).interfaceId ||
                  super.supportsInterface(interfaceId);
          }
          /**
           * @dev See {IERC1155MetadataURI-uri}.
           *
           * This implementation returns the same URI for *all* token types. It relies
           * on the token type ID substitution mechanism
           * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
           *
           * Clients calling this function must replace the `\\{id\\}` substring with the
           * actual token type ID.
           */
          function uri(uint256) public view virtual override returns (string memory) {
              return _uri;
          }
          /**
           * @dev See {IERC1155-balanceOf}.
           *
           * Requirements:
           *
           * - `account` cannot be the zero address.
           */
          function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
              if(account == address(0)) {
                  revert BalanceQueryForZeroAddress();
              }
              if(_owned[account].get(id)) {
                  return 1;
              } else {
                  return 0;
              }   
          }
          /**
           * @dev See {IERC1155-balanceOfBatch}.
           *
           * Requirements:
           *
           * - `accounts` and `ids` must have the same length.
           */
          function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
              public
              view
              virtual
              override
              returns (uint256[] memory)
          {
              if(accounts.length != ids.length) {
                  revert InputLengthMistmatch();
              }
              uint256[] memory batchBalances = new uint256[](accounts.length);
              for (uint256 i = 0; i < accounts.length; ++i) {
                  batchBalances[i] = balanceOf(accounts[i], ids[i]);
              }
              return batchBalances;
          }
          /**
           * @dev See {IERC1155-setApprovalForAll}.
           */
          function setApprovalForAll(address operator, bool approved) public virtual override {
              _setApprovalForAll(_msgSender(), operator, approved);
          }
          /**
           * @dev See {IERC1155-isApprovedForAll}.
           */
          function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
              return _operatorApprovals[account][operator];
          }
          /**
           * @dev See {IERC1155-safeTransferFrom}.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes memory data
          ) public virtual override {
              if(from == _msgSender() || isApprovedForAll(from, _msgSender())){
                  _safeTransferFrom(from, to, id, amount, data);
              } else {
                  revert TransferCallerNotOwnerNorApproved();
              }
          }
          /**
           * @dev See {IERC1155-safeBatchTransferFrom}.
           */
          function safeBatchTransferFrom(
              address from,
              address to,
              uint256[] memory ids,
              uint256[] memory amounts,
              bytes memory data
          ) public virtual override {
              if(!(from == _msgSender() || isApprovedForAll(from, _msgSender()))) {
                  revert TransferCallerNotOwnerNorApproved();
              }
              _safeBatchTransferFrom(from, to, ids, amounts, data);
          }
          /**
           * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
           *
           * Emits a {TransferSingle} event.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `amount` cannot be zero.
           * - `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 memory data
          ) internal virtual {
              if(to == address(0)) {
                  revert TransferToZeroAddress();
              }
              address operator = _msgSender();
              uint256[] memory ids = _asSingletonArray(id);
              _beforeTokenTransfer(operator, from, to, ids, data);
              if(amount == 1 && _owned[from].get(id)) {
                  _owned[from].unset(id);
                  _owned[to].set(id);
              } else {
                  revert TransferFromIncorrectOwnerOrInvalidAmount();
              } 
              emit TransferSingle(operator, from, to, id, amount);
              _afterTokenTransfer(operator, from, to, ids, data);
              _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
          }
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
           *
           * Emits a {TransferBatch} event.
           *
           * Requirements:
           *
           * - 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[] memory ids,
              uint256[] memory amounts,
              bytes memory data
          ) internal virtual {
              if(ids.length != amounts.length) {
                  revert InputLengthMistmatch();
              }
              if(to == address(0)) {
                  revert TransferToZeroAddress();
              }
              address operator = _msgSender();
              _beforeTokenTransfer(operator, from, to, ids, data);
              for (uint256 i = 0; i < ids.length; ++i) {
                  uint256 id = ids[i];
                  uint256 amount = amounts[i];
                  if(amount == 1 && _owned[from].get(id)) {
                      _owned[from].unset(id);
                      _owned[to].set(id);
                  } else {
                      revert TransferFromIncorrectOwnerOrInvalidAmount();
                  }
              }
              emit TransferBatch(operator, from, to, ids, amounts);
              _afterTokenTransfer(operator, from, to, ids, data);
              _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
          }
          /**
           * @dev Sets a new URI for all token types, by relying on the token type ID
           * substitution mechanism
           * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
           *
           * By this mechanism, any occurrence of the `\\{id\\}` substring in either the
           * URI or any of the amounts in the JSON file at said URI will be replaced by
           * clients with the token type ID.
           *
           * For example, the `https://token-cdn-domain/\\{id\\}.json` URI would be
           * interpreted by clients as
           * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
           * for token type ID 0x4cce0.
           *
           * See {uri}.
           *
           * Because these URIs cannot be meaningfully represented by the {URI} event,
           * this function emits no events.
           */
          function _setURI(string memory newuri) internal virtual {
              _uri = newuri;
          }
          function _mint(
              address to,
              uint256 amount
          ) internal virtual {
              _mint(to, amount, "");
          }
          /**
           * @dev Creates `amount` tokens, and assigns them to `to`.
           *
           * Emits a {TransferBatch} event.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `amount` cannot be zero.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
           * acceptance magic value.
           */
          function _mint(
              address to,
              uint256 amount,
              bytes memory data
          ) internal virtual {
              if(to == address(0)) {
                  revert MintToZeroAddress();
              }
              if(amount == 0) {
                  revert MintZeroQuantity();
              }
              address operator = _msgSender();
              uint256[] memory ids = new uint256[](amount);
              uint256[] memory amounts = new uint256[](amount);
              uint256 startTokenId = _nextTokenId();
              unchecked {
                  require(type(uint256).max - amount >= startTokenId);
                  for(uint256 i = 0; i < amount; i++) {
                      ids[i] = startTokenId + i;
                      amounts[i] = 1;
                  }
              }
              
              _beforeTokenTransfer(operator, address(0), to, ids, data);
              _owned[to].setBatch(startTokenId, amount);
              _currentIndex += amount;
              emit TransferBatch(operator, address(0), to, ids, amounts);
              _afterTokenTransfer(operator, address(0), to, ids, data);
              _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
          }
          /**
           * @dev Destroys token of token type `id` from `from`
           *
           * Emits a {TransferSingle} event.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `from` must have the token of token type `id`.
           */
          function _burn(
              address from,
              uint256 id
          ) internal virtual {
              if(from == address(0)){
                  revert BurnFromZeroAddress();
              }
              address operator = _msgSender();
              uint256[] memory ids = _asSingletonArray(id);
              _beforeTokenTransfer(operator, from, address(0), ids, "");
              if(!_owned[from].get(id)) {
                  revert BurnFromNonOnwerAddress();
              }
              _owned[from].unset(id);
              emit TransferSingle(operator, from, address(0), id, 1);
              _afterTokenTransfer(operator, from, address(0), ids, "");
          }
          /**
           * @dev Destroys tokens of token types in `ids` from `from`
           *
           * Emits a {TransferBatch} event.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `from` must have the token of token types in `ids`.
           */
          function _burnBatch(
              address from,
              uint256[] memory ids
          ) internal virtual {
              if(from == address(0)){
                  revert BurnFromZeroAddress();
              }
              address operator = _msgSender();
              uint256[] memory amounts = new uint256[](ids.length);
              _beforeTokenTransfer(operator, from, address(0), ids, "");
              unchecked {
                  for(uint256 i = 0; i < ids.length; i++) {
                      amounts[i] = 1;
                      uint256 id = ids[i];
                      if(!_owned[from].get(id)) {
                          revert BurnFromNonOnwerAddress();
                      }
                      _owned[from].unset(id);
                  }
              }
              
              emit TransferBatch(operator, from, address(0), ids, amounts);
              _afterTokenTransfer(operator, from, address(0), ids, "");
          }
           /**
           * @dev Approve `operator` to operate on all of `owner` tokens
           *
           * Emits an {ApprovalForAll} event.
           */
          function _setApprovalForAll(
              address owner,
              address operator,
              bool approved
          ) internal virtual {
              require(owner != operator, "ERC1155: setting approval status for self");
              _operatorApprovals[owner][operator] = approved;
              emit ApprovalForAll(owner, operator, approved);
          }
          /**
           * @dev Hook that is called before any token transfer. This includes minting
           * and burning, as well as batched variants.
           *
           * The same hook is called on both single and batched variants. For single
           * transfers, the length of the `ids` and `amounts` arrays will be 1.
           *
           * Calling conditions (for each `id` and `amount` pair):
           *
           * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
           * of token type `id` will be  transferred to `to`.
           * - When `from` is zero, `amount` tokens of token type `id` will be minted
           * for `to`.
           * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
           * will be burned.
           * - `from` and `to` are never both zero.
           * - `ids` and `amounts` have the same, non-zero length.
           *
           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
           */
          function _beforeTokenTransfer(
              address operator,
              address from,
              address to,
              uint256[] memory ids,
              bytes memory data
          ) internal virtual {}
          /**
           * @dev Hook that is called after any token transfer. This includes minting
           * and burning, as well as batched variants.
           *
           * The same hook is called on both single and batched variants. For single
           * transfers, the length of the `id` and `amount` arrays will be 1.
           *
           * Calling conditions (for each `id` and `amount` pair):
           *
           * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
           * of token type `id` will be  transferred to `to`.
           * - When `from` is zero, `amount` tokens of token type `id` will be minted
           * for `to`.
           * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
           * will be burned.
           * - `from` and `to` are never both zero.
           * - `ids` and `amounts` have the same, non-zero length.
           *
           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
           */
          function _afterTokenTransfer(
              address operator,
              address from,
              address to,
              uint256[] memory ids,
              bytes memory data
          ) internal virtual {}
          function _doSafeTransferAcceptanceCheck(
              address operator,
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes memory data
          ) private {
              if (to.isContract()) {
                  try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
                      if (response != IERC1155Receiver.onERC1155Received.selector) {
                          revert TransferToNonERC1155ReceiverImplementer();
                      }
                  } catch Error(string memory reason) {
                      revert(reason);
                  } catch {
                      revert TransferToNonERC1155ReceiverImplementer();
                  }
              }
          }
          function _doSafeBatchTransferAcceptanceCheck(
              address operator,
              address from,
              address to,
              uint256[] memory ids,
              uint256[] memory amounts,
              bytes memory data
          ) private {
              if (to.isContract()) {
                  try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
                      bytes4 response
                  ) {
                      if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                          revert TransferToNonERC1155ReceiverImplementer();
                      }
                  } catch Error(string memory reason) {
                      revert(reason);
                  } catch {
                      revert TransferToNonERC1155ReceiverImplementer();
                  }
              }
          }
          function _asSingletonArray(uint256 element) private pure returns (uint256[] memory array) {
              array = new uint256[](1);
              array[0] = element;
          }
      }// SPDX-License-Identifier: MIT
      /**
         _____       ___     ___ __           ____  _ __      
        / ___/____  / (_)___/ (_) /___  __   / __ )(_) /______
        \\__ \\/ __ \\/ / / __  / / __/ / / /  / __  / / __/ ___/
       ___/ / /_/ / / / /_/ / / /_/ /_/ /  / /_/ / / /_(__  ) 
      /____/\\____/_/_/\\__,_/_/\\__/\\__, /  /_____/_/\\__/____/  
                                 /____/                        
      - npm: https://www.npmjs.com/package/solidity-bits
      - github: https://github.com/estarriolvetch/solidity-bits
       */
      pragma solidity ^0.8.0;
      import "./BitScan.sol";
      import "./Popcount.sol";
      /**
       * @dev This Library is a modified version of Openzeppelin's BitMaps library with extra features.
       *
       * 1. Functions of finding the index of the closest set bit from a given index are added.
       *    The indexing of each bucket is modifed to count from the MSB to the LSB instead of from the LSB to the MSB.
       *    The modification of indexing makes finding the closest previous set bit more efficient in gas usage.
       * 2. Setting and unsetting the bitmap consecutively.
       * 3. Accounting number of set bits within a given range.   
       *
      */
      /**
       * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
       * Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
       */
      library BitMaps {
          using BitScan for uint256;
          uint256 private constant MASK_INDEX_ZERO = (1 << 255);
          uint256 private constant MASK_FULL = type(uint256).max;
          struct BitMap {
              mapping(uint256 => uint256) _data;
          }
          /**
           * @dev Returns whether the bit at `index` is set.
           */
          function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
              uint256 bucket = index >> 8;
              uint256 mask = MASK_INDEX_ZERO >> (index & 0xff);
              return bitmap._data[bucket] & mask != 0;
          }
          /**
           * @dev Sets the bit at `index` to the boolean `value`.
           */
          function setTo(
              BitMap storage bitmap,
              uint256 index,
              bool value
          ) internal {
              if (value) {
                  set(bitmap, index);
              } else {
                  unset(bitmap, index);
              }
          }
          /**
           * @dev Sets the bit at `index`.
           */
          function set(BitMap storage bitmap, uint256 index) internal {
              uint256 bucket = index >> 8;
              uint256 mask = MASK_INDEX_ZERO >> (index & 0xff);
              bitmap._data[bucket] |= mask;
          }
          /**
           * @dev Unsets the bit at `index`.
           */
          function unset(BitMap storage bitmap, uint256 index) internal {
              uint256 bucket = index >> 8;
              uint256 mask = MASK_INDEX_ZERO >> (index & 0xff);
              bitmap._data[bucket] &= ~mask;
          }
          /**
           * @dev Consecutively sets `amount` of bits starting from the bit at `startIndex`.
           */    
          function setBatch(BitMap storage bitmap, uint256 startIndex, uint256 amount) internal {
              uint256 bucket = startIndex >> 8;
              uint256 bucketStartIndex = (startIndex & 0xff);
              unchecked {
                  if(bucketStartIndex + amount < 256) {
                      bitmap._data[bucket] |= MASK_FULL << (256 - amount) >> bucketStartIndex;
                  } else {
                      bitmap._data[bucket] |= MASK_FULL >> bucketStartIndex;
                      amount -= (256 - bucketStartIndex);
                      bucket++;
                      while(amount > 256) {
                          bitmap._data[bucket] = MASK_FULL;
                          amount -= 256;
                          bucket++;
                      }
                      bitmap._data[bucket] |= MASK_FULL << (256 - amount);
                  }
              }
          }
          /**
           * @dev Consecutively unsets `amount` of bits starting from the bit at `startIndex`.
           */    
          function unsetBatch(BitMap storage bitmap, uint256 startIndex, uint256 amount) internal {
              uint256 bucket = startIndex >> 8;
              uint256 bucketStartIndex = (startIndex & 0xff);
              unchecked {
                  if(bucketStartIndex + amount < 256) {
                      bitmap._data[bucket] &= ~(MASK_FULL << (256 - amount) >> bucketStartIndex);
                  } else {
                      bitmap._data[bucket] &= ~(MASK_FULL >> bucketStartIndex);
                      amount -= (256 - bucketStartIndex);
                      bucket++;
                      while(amount > 256) {
                          bitmap._data[bucket] = 0;
                          amount -= 256;
                          bucket++;
                      }
                      bitmap._data[bucket] &= ~(MASK_FULL << (256 - amount));
                  }
              }
          }
          /**
           * @dev Returns number of set bits within a range.
           */
          function popcountA(BitMap storage bitmap, uint256 startIndex, uint256 amount) internal view returns(uint256 count) {
              uint256 bucket = startIndex >> 8;
              uint256 bucketStartIndex = (startIndex & 0xff);
              unchecked {
                  if(bucketStartIndex + amount < 256) {
                      count +=  Popcount.popcount256A(
                          bitmap._data[bucket] & (MASK_FULL << (256 - amount) >> bucketStartIndex)
                      );
                  } else {
                      count += Popcount.popcount256A(
                          bitmap._data[bucket] & (MASK_FULL >> bucketStartIndex)
                      );
                      amount -= (256 - bucketStartIndex);
                      bucket++;
                      while(amount > 256) {
                          count += Popcount.popcount256A(bitmap._data[bucket]);
                          amount -= 256;
                          bucket++;
                      }
                      count += Popcount.popcount256A(
                          bitmap._data[bucket] & (MASK_FULL << (256 - amount))
                      );
                  }
              }
          }
          /**
           * @dev Returns number of set bits within a range.
           */
          function popcountB(BitMap storage bitmap, uint256 startIndex, uint256 amount) internal view returns(uint256 count) {
              uint256 bucket = startIndex >> 8;
              uint256 bucketStartIndex = (startIndex & 0xff);
              unchecked {
                  if(bucketStartIndex + amount < 256) {
                      count +=  Popcount.popcount256B(
                          bitmap._data[bucket] & (MASK_FULL << (256 - amount) >> bucketStartIndex)
                      );
                  } else {
                      count += Popcount.popcount256B(
                          bitmap._data[bucket] & (MASK_FULL >> bucketStartIndex)
                      );
                      amount -= (256 - bucketStartIndex);
                      bucket++;
                      while(amount > 256) {
                          count += Popcount.popcount256B(bitmap._data[bucket]);
                          amount -= 256;
                          bucket++;
                      }
                      count += Popcount.popcount256B(
                          bitmap._data[bucket] & (MASK_FULL << (256 - amount))
                      );
                  }
              }
          }
          /**
           * @dev Find the closest index of the set bit before `index`.
           */
          function scanForward(BitMap storage bitmap, uint256 index) internal view returns (uint256 setBitIndex) {
              uint256 bucket = index >> 8;
              // index within the bucket
              uint256 bucketIndex = (index & 0xff);
              // load a bitboard from the bitmap.
              uint256 bb = bitmap._data[bucket];
              // offset the bitboard to scan from `bucketIndex`.
              bb = bb >> (0xff ^ bucketIndex); // bb >> (255 - bucketIndex)
              
              if(bb > 0) {
                  unchecked {
                      setBitIndex = (bucket << 8) | (bucketIndex -  bb.bitScanForward256());    
                  }
              } else {
                  while(true) {
                      require(bucket > 0, "BitMaps: The set bit before the index doesn't exist.");
                      unchecked {
                          bucket--;
                      }
                      // No offset. Always scan from the least significiant bit now.
                      bb = bitmap._data[bucket];
                      
                      if(bb > 0) {
                          unchecked {
                              setBitIndex = (bucket << 8) | (255 -  bb.bitScanForward256());
                              break;
                          }
                      } 
                  }
              }
          }
          function getBucket(BitMap storage bitmap, uint256 bucket) internal view returns (uint256) {
              return bitmap._data[bucket];
          }
      }
      // SPDX-License-Identifier: MIT
      // Creator: Ctor Lab (https://ctor.xyz)
      pragma solidity ^0.8.0;
      interface IERC1155DeltaQueryable {
          error InvalidQueryRange();
          function balanceOf(address owner) external view returns (uint256);
          function balanceOf(address owner, uint256 start, uint256 stop) external view returns (uint256);
          function tokensOfOwnerIn(
              address owner,
              uint256 start,
              uint256 stop
          ) external view returns (uint256[] memory);
          function tokensOfOwner(address owner) external view returns (uint256[] memory);
          
      }// SPDX-License-Identifier: MIT
      // Creator: Ctor Lab (https://ctor.xyz)
      pragma solidity ^0.8.0;
      interface IERC1155Delta {
          /**
           * The caller must own the token or be an approved operator.
           */
          error ApprovalCallerNotOwnerNorApproved();
          /**
           * Cannot query the balance for the zero address.
           */
          error BalanceQueryForZeroAddress();
          /**
           * Cannot mint to the zero address.
           */
          error MintToZeroAddress();
          /**
           * The quantity of tokens minted must be more than zero.
           */
          error MintZeroQuantity();
          /**
           * Cannot burn from the zero address.
           */
          error BurnFromZeroAddress();
          /**
           * Cannot burn from the address that doesn't owne the token.
           */
          error BurnFromNonOnwerAddress();
          /**
           * The caller must own the token or be an approved operator.
           */
          error TransferCallerNotOwnerNorApproved();
          /**
           * The token must be owned by `from` or the `amount` is not 1.
           */
          error TransferFromIncorrectOwnerOrInvalidAmount();
          /**
           * Cannot safely transfer to a contract that does not implement the
           * ERC1155Receiver interface.
           */
          error TransferToNonERC1155ReceiverImplementer();
          /**
           * Cannot transfer to the zero address.
           */
          error TransferToZeroAddress();
          /**
           * The length of input arraies is not matching.
           */
          error InputLengthMistmatch();
          
          function isOwnerOf(address account, uint256 id) external view returns(bool);
      }// SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165.sol";
      /**
       * @dev _Available since v3.1._
       */
      interface IERC1155Receiver is IERC165 {
          /**
           * @dev Handles the receipt of a single ERC1155 token type. This function is
           * called at the end of a `safeTransferFrom` after the balance has been updated.
           *
           * NOTE: To accept the transfer, this must return
           * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
           * (i.e. 0xf23a6e61, or its own function selector).
           *
           * @param operator The address which initiated the transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param id The ID of the token being transferred
           * @param value The amount of tokens being transferred
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
           */
          function onERC1155Received(
              address operator,
              address from,
              uint256 id,
              uint256 value,
              bytes calldata data
          ) external returns (bytes4);
          /**
           * @dev Handles the receipt of a multiple ERC1155 token types. This function
           * is called at the end of a `safeBatchTransferFrom` after the balances have
           * been updated.
           *
           * NOTE: To accept the transfer(s), this must return
           * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
           * (i.e. 0xbc197c81, or its own function selector).
           *
           * @param operator The address which initiated the batch transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param ids An array containing ids of each token being transferred (order and length must match values array)
           * @param values An array containing amounts of each token being transferred (order and length must match ids array)
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
           */
          function onERC1155BatchReceived(
              address operator,
              address from,
              uint256[] calldata ids,
              uint256[] calldata values,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable {
          /**
           * @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 v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
      pragma solidity ^0.8.0;
      import "../IERC1155Upgradeable.sol";
      /**
       * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
       * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
       *
       * _Available since v3.1._
       */
      interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
          /**
           * @dev Returns the URI for token type `id`.
           *
           * If the `\\{id\\}` substring is present in the URI, it must be replaced by
           * clients with the actual token type ID.
           */
          function uri(uint256 id) external view returns (string memory);
      }
      // SPDX-License-Identifier: MIT
      /**
         _____       ___     ___ __           ____  _ __      
        / ___/____  / (_)___/ (_) /___  __   / __ )(_) /______
        \\__ \\/ __ \\/ / / __  / / __/ / / /  / __  / / __/ ___/
       ___/ / /_/ / / / /_/ / / /_/ /_/ /  / /_/ / / /_(__  ) 
      /____/\\____/_/_/\\__,_/_/\\__/\\__, /  /_____/_/\\__/____/  
                                 /____/                        
      - npm: https://www.npmjs.com/package/solidity-bits
      - github: https://github.com/estarriolvetch/solidity-bits
       */
      pragma solidity ^0.8.0;
      library Popcount {
          uint256 private constant m1 = 0x5555555555555555555555555555555555555555555555555555555555555555;
          uint256 private constant m2 = 0x3333333333333333333333333333333333333333333333333333333333333333;
          uint256 private constant m4 = 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f;
          uint256 private constant h01 = 0x0101010101010101010101010101010101010101010101010101010101010101;
          function popcount256A(uint256 x) internal pure returns (uint256 count) {
              unchecked{
                  for (count=0; x!=0; count++)
                      x &= x - 1;
              }
          }
          function popcount256B(uint256 x) internal pure returns (uint256) {
              if (x == type(uint256).max) {
                  return 256;
              }
              unchecked {
                  x -= (x >> 1) & m1;             //put count of each 2 bits into those 2 bits
                  x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits 
                  x = (x + (x >> 4)) & m4;        //put count of each 8 bits into those 8 bits 
                  x = (x * h01) >> 248;  //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... 
              }
              return x;
          }
      }// SPDX-License-Identifier: MIT
      /**
         _____       ___     ___ __           ____  _ __      
        / ___/____  / (_)___/ (_) /___  __   / __ )(_) /______
        \\__ \\/ __ \\/ / / __  / / __/ / / /  / __  / / __/ ___/
       ___/ / /_/ / / / /_/ / / /_/ /_/ /  / /_/ / / /_(__  ) 
      /____/\\____/_/_/\\__,_/_/\\__/\\__, /  /_____/_/\\__/____/  
                                 /____/                        
      - npm: https://www.npmjs.com/package/solidity-bits
      - github: https://github.com/estarriolvetch/solidity-bits
       */
      pragma solidity ^0.8.0;
      library BitScan {
          uint256 constant private DEBRUIJN_256 = 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff;
          bytes constant private LOOKUP_TABLE_256 = hex"0001020903110a19042112290b311a3905412245134d2a550c5d32651b6d3a7506264262237d468514804e8d2b95569d0d495ea533a966b11c886eb93bc176c9071727374353637324837e9b47af86c7155181ad4fd18ed32c9096db57d59ee30e2e4a6a5f92a6be3498aae067ddb2eb1d5989b56fd7baf33ca0c2ee77e5caf7ff0810182028303840444c545c646c7425617c847f8c949c48a4a8b087b8c0c816365272829aaec650acd0d28fdad4e22d6991bd97dfdcea58b4d6f29fede4f6fe0f1f2f3f4b5b6b607b8b93a3a7b7bf357199c5abcfd9e168bcdee9b3f1ecf5fd1e3e5a7a8aa2b670c4ced8bbe8f0f4fc3d79a1c3cde7effb78cce6facbf9f8";
          /**
              @dev Isolate the least significant set bit.
           */ 
          function isolateLS1B256(uint256 bb) pure internal returns (uint256) {
              require(bb > 0);
              unchecked {
                  return bb & (0 - bb);
              }
          } 
          /**
              @dev Isolate the most significant set bit.
           */ 
          function isolateMS1B256(uint256 bb) pure internal returns (uint256) {
              require(bb > 0);
              unchecked {
                  bb |= bb >> 128;
                  bb |= bb >> 64;
                  bb |= bb >> 32;
                  bb |= bb >> 16;
                  bb |= bb >> 8;
                  bb |= bb >> 4;
                  bb |= bb >> 2;
                  bb |= bb >> 1;
                  
                  return (bb >> 1) + 1;
              }
          } 
          /**
              @dev Find the index of the lest significant set bit. (trailing zero count)
           */ 
          function bitScanForward256(uint256 bb) pure internal returns (uint8) {
              unchecked {
                  return uint8(LOOKUP_TABLE_256[(isolateLS1B256(bb) * DEBRUIJN_256) >> 248]);
              }   
          }
          /**
              @dev Find the index of the most significant set bit.
           */ 
          function bitScanReverse256(uint256 bb) pure internal returns (uint8) {
              unchecked {
                  return 255 - uint8(LOOKUP_TABLE_256[((isolateMS1B256(bb) * DEBRUIJN_256) >> 248)]);
              }   
          }
          function log2(uint256 bb) pure internal returns (uint8) {
              unchecked {
                  return uint8(LOOKUP_TABLE_256[(isolateMS1B256(bb) * DEBRUIJN_256) >> 248]);
              } 
          }
      }
      // 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);
      }
      

      File 3 of 3: OperatorFilterRegistry
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
      pragma solidity ^0.8.0;
      import "../utils/Context.sol";
      /**
       * @dev Contract module which provides a basic access control mechanism, where
       * there is an account (an owner) that can be granted exclusive access to
       * specific functions.
       *
       * By default, the owner account will be the one that deploys the contract. This
       * can later be changed with {transferOwnership}.
       *
       * This module is used through inheritance. It will make available the modifier
       * `onlyOwner`, which can be applied to your functions to restrict their use to
       * the owner.
       */
      abstract contract Ownable is Context {
          address private _owner;
          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          /**
           * @dev Initializes the contract setting the deployer as the initial owner.
           */
          constructor() {
              _transferOwnership(_msgSender());
          }
          /**
           * @dev Throws if called by any account other than the owner.
           */
          modifier onlyOwner() {
              _checkOwner();
              _;
          }
          /**
           * @dev Returns the address of the current owner.
           */
          function owner() public view virtual returns (address) {
              return _owner;
          }
          /**
           * @dev Throws if the sender is not the owner.
           */
          function _checkOwner() internal view virtual {
              require(owner() == _msgSender(), "Ownable: caller is not the owner");
          }
          /**
           * @dev Leaves the contract without owner. It will not be possible to call
           * `onlyOwner` functions anymore. Can only be called by the current owner.
           *
           * NOTE: Renouncing ownership will leave the contract without an owner,
           * thereby removing any functionality that is only available to the owner.
           */
          function renounceOwnership() public virtual onlyOwner {
              _transferOwnership(address(0));
          }
          /**
           * @dev Transfers ownership of the contract to a new account (`newOwner`).
           * Can only be called by the current owner.
           */
          function transferOwnership(address newOwner) public virtual onlyOwner {
              require(newOwner != address(0), "Ownable: new owner is the zero address");
              _transferOwnership(newOwner);
          }
          /**
           * @dev Transfers ownership of the contract to a new account (`newOwner`).
           * Internal function without access restriction.
           */
          function _transferOwnership(address newOwner) internal virtual {
              address oldOwner = _owner;
              _owner = newOwner;
              emit OwnershipTransferred(oldOwner, newOwner);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts 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.7.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.
       *
       * ```
       * 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
      pragma solidity ^0.8.13;
      import {EnumerableSet} from "openzeppelin-contracts/utils/structs/EnumerableSet.sol";
      interface IOperatorFilterRegistry {
          function isOperatorAllowed(address registrant, address operator) external returns (bool);
          function register(address registrant) external;
          function registerAndSubscribe(address registrant, address subscription) external;
          function registerAndCopyEntries(address registrant, address registrantToCopy) external;
          function updateOperator(address registrant, address operator, bool filtered) external;
          function updateOperators(address registrant, address[] calldata operators, bool filtered) external;
          function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;
          function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;
          function subscribe(address registrant, address registrantToSubscribe) external;
          function unsubscribe(address registrant, bool copyExistingEntries) external;
          function subscriptionOf(address addr) external returns (address registrant);
          function subscribers(address registrant) external returns (address[] memory);
          function subscriberAt(address registrant, uint256 index) external returns (address);
          function copyEntriesOf(address registrant, address registrantToCopy) external;
          function isOperatorFiltered(address registrant, address operator) external returns (bool);
          function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);
          function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);
          function filteredOperators(address addr) external returns (address[] memory);
          function filteredCodeHashes(address addr) external returns (bytes32[] memory);
          function filteredOperatorAt(address registrant, uint256 index) external returns (address);
          function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);
          function isRegistered(address addr) external returns (bool);
          function codeHashOf(address addr) external returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.13;
      import {IOperatorFilterRegistry} from "./IOperatorFilterRegistry.sol";
      import {Ownable} from "openzeppelin-contracts/access/Ownable.sol";
      import {EnumerableSet} from "openzeppelin-contracts/utils/structs/EnumerableSet.sol";
      import {OperatorFilterRegistryErrorsAndEvents} from "./OperatorFilterRegistryErrorsAndEvents.sol";
      /**
       * @title  OperatorFilterRegistry
       * @notice Borrows heavily from the QQL BlacklistOperatorFilter contract:
       *         https://github.com/qql-art/contracts/blob/main/contracts/BlacklistOperatorFilter.sol
       * @notice This contracts allows tokens or token owners to register specific addresses or codeHashes that may be
       * *       restricted according to the isOperatorAllowed function.
       */
      contract OperatorFilterRegistry is IOperatorFilterRegistry, OperatorFilterRegistryErrorsAndEvents {
          using EnumerableSet for EnumerableSet.AddressSet;
          using EnumerableSet for EnumerableSet.Bytes32Set;
          /// @dev initialized accounts have a nonzero codehash (see https://eips.ethereum.org/EIPS/eip-1052)
          /// Note that this will also be a smart contract's codehash when making calls from its constructor.
          bytes32 constant EOA_CODEHASH = keccak256("");
          mapping(address => EnumerableSet.AddressSet) private _filteredOperators;
          mapping(address => EnumerableSet.Bytes32Set) private _filteredCodeHashes;
          mapping(address => address) private _registrations;
          mapping(address => EnumerableSet.AddressSet) private _subscribers;
          /**
           * @notice restricts method caller to the address or EIP-173 "owner()"
           */
          modifier onlyAddressOrOwner(address addr) {
              if (msg.sender != addr) {
                  try Ownable(addr).owner() returns (address owner) {
                      if (msg.sender != owner) {
                          revert OnlyAddressOrOwner();
                      }
                  } catch (bytes memory reason) {
                      if (reason.length == 0) {
                          revert NotOwnable();
                      } else {
                          /// @solidity memory-safe-assembly
                          assembly {
                              revert(add(32, reason), mload(reason))
                          }
                      }
                  }
              }
              _;
          }
          /**
           * @notice Returns true if operator is not filtered for a given token, either by address or codeHash. Also returns
           *         true if supplied registrant address is not registered.
           */
          function isOperatorAllowed(address registrant, address operator) external view returns (bool) {
              address registration = _registrations[registrant];
              if (registration != address(0)) {
                  EnumerableSet.AddressSet storage filteredOperatorsRef;
                  EnumerableSet.Bytes32Set storage filteredCodeHashesRef;
                  filteredOperatorsRef = _filteredOperators[registration];
                  filteredCodeHashesRef = _filteredCodeHashes[registration];
                  if (filteredOperatorsRef.contains(operator)) {
                      revert AddressFiltered(operator);
                  }
                  if (operator.code.length > 0) {
                      bytes32 codeHash = operator.codehash;
                      if (filteredCodeHashesRef.contains(codeHash)) {
                          revert CodeHashFiltered(operator, codeHash);
                      }
                  }
              }
              return true;
          }
          //////////////////
          // AUTH METHODS //
          //////////////////
          /**
           * @notice Registers an address with the registry. May be called by address itself or by EIP-173 owner.
           */
          function register(address registrant) external onlyAddressOrOwner(registrant) {
              if (_registrations[registrant] != address(0)) {
                  revert AlreadyRegistered();
              }
              _registrations[registrant] = registrant;
              emit RegistrationUpdated(registrant, true);
          }
          /**
           * @notice Unregisters an address with the registry and removes its subscription. May be called by address itself or by EIP-173 owner.
           *         Note that this does not remove any filtered addresses or codeHashes.
           *         Also note that any subscriptions to this registrant will still be active and follow the existing filtered addresses and codehashes.
           */
          function unregister(address registrant) external onlyAddressOrOwner(registrant) {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  _subscribers[registration].remove(registrant);
                  emit SubscriptionUpdated(registrant, registration, false);
              }
              _registrations[registrant] = address(0);
              emit RegistrationUpdated(registrant, false);
          }
          /**
           * @notice Registers an address with the registry and "subscribes" to another address's filtered operators and codeHashes.
           */
          function registerAndSubscribe(address registrant, address subscription) external onlyAddressOrOwner(registrant) {
              address registration = _registrations[registrant];
              if (registration != address(0)) {
                  revert AlreadyRegistered();
              }
              if (registrant == subscription) {
                  revert CannotSubscribeToSelf();
              }
              address subscriptionRegistration = _registrations[subscription];
              if (subscriptionRegistration == address(0)) {
                  revert NotRegistered(subscription);
              }
              if (subscriptionRegistration != subscription) {
                  revert CannotSubscribeToRegistrantWithSubscription(subscription);
              }
              _registrations[registrant] = subscription;
              _subscribers[subscription].add(registrant);
              emit RegistrationUpdated(registrant, true);
              emit SubscriptionUpdated(registrant, subscription, true);
          }
          /**
           * @notice Registers an address with the registry and copies the filtered operators and codeHashes from another
           *         address without subscribing.
           */
          function registerAndCopyEntries(address registrant, address registrantToCopy)
              external
              onlyAddressOrOwner(registrant)
          {
              if (registrantToCopy == registrant) {
                  revert CannotCopyFromSelf();
              }
              address registration = _registrations[registrant];
              if (registration != address(0)) {
                  revert AlreadyRegistered();
              }
              address registrantRegistration = _registrations[registrantToCopy];
              if (registrantRegistration == address(0)) {
                  revert NotRegistered(registrantToCopy);
              }
              _registrations[registrant] = registrant;
              emit RegistrationUpdated(registrant, true);
              _copyEntries(registrant, registrantToCopy);
          }
          /**
           * @notice Update an operator address for a registered address - when filtered is true, the operator is filtered.
           */
          function updateOperator(address registrant, address operator, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.AddressSet storage filteredOperatorsRef = _filteredOperators[registrant];
              if (!filtered) {
                  bool removed = filteredOperatorsRef.remove(operator);
                  if (!removed) {
                      revert AddressNotFiltered(operator);
                  }
              } else {
                  bool added = filteredOperatorsRef.add(operator);
                  if (!added) {
                      revert AddressAlreadyFiltered(operator);
                  }
              }
              emit OperatorUpdated(registrant, operator, filtered);
          }
          /**
           * @notice Update a codeHash for a registered address - when filtered is true, the codeHash is filtered.
           */
          function updateCodeHash(address registrant, bytes32 codeHash, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              if (codeHash == EOA_CODEHASH) {
                  revert CannotFilterEOAs();
              }
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.Bytes32Set storage filteredCodeHashesRef = _filteredCodeHashes[registrant];
              if (!filtered) {
                  bool removed = filteredCodeHashesRef.remove(codeHash);
                  if (!removed) {
                      revert CodeHashNotFiltered(codeHash);
                  }
              } else {
                  bool added = filteredCodeHashesRef.add(codeHash);
                  if (!added) {
                      revert CodeHashAlreadyFiltered(codeHash);
                  }
              }
              emit CodeHashUpdated(registrant, codeHash, filtered);
          }
          /**
           * @notice Update multiple operators for a registered address - when filtered is true, the operators will be filtered. Reverts on duplicates.
           */
          function updateOperators(address registrant, address[] calldata operators, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.AddressSet storage filteredOperatorsRef = _filteredOperators[registrant];
              uint256 operatorsLength = operators.length;
              unchecked {
                  if (!filtered) {
                      for (uint256 i = 0; i < operatorsLength; ++i) {
                          address operator = operators[i];
                          bool removed = filteredOperatorsRef.remove(operator);
                          if (!removed) {
                              revert AddressNotFiltered(operator);
                          }
                      }
                  } else {
                      for (uint256 i = 0; i < operatorsLength; ++i) {
                          address operator = operators[i];
                          bool added = filteredOperatorsRef.add(operator);
                          if (!added) {
                              revert AddressAlreadyFiltered(operator);
                          }
                      }
                  }
              }
              emit OperatorsUpdated(registrant, operators, filtered);
          }
          /**
           * @notice Update multiple codeHashes for a registered address - when filtered is true, the codeHashes will be filtered. Reverts on duplicates.
           */
          function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.Bytes32Set storage filteredCodeHashesRef = _filteredCodeHashes[registrant];
              uint256 codeHashesLength = codeHashes.length;
              unchecked {
                  if (!filtered) {
                      for (uint256 i = 0; i < codeHashesLength; ++i) {
                          bytes32 codeHash = codeHashes[i];
                          bool removed = filteredCodeHashesRef.remove(codeHash);
                          if (!removed) {
                              revert CodeHashNotFiltered(codeHash);
                          }
                      }
                  } else {
                      for (uint256 i = 0; i < codeHashesLength; ++i) {
                          bytes32 codeHash = codeHashes[i];
                          if (codeHash == EOA_CODEHASH) {
                              revert CannotFilterEOAs();
                          }
                          bool added = filteredCodeHashesRef.add(codeHash);
                          if (!added) {
                              revert CodeHashAlreadyFiltered(codeHash);
                          }
                      }
                  }
              }
              emit CodeHashesUpdated(registrant, codeHashes, filtered);
          }
          /**
           * @notice Subscribe an address to another registrant's filtered operators and codeHashes. Will remove previous
           *         subscription if present.
           *         Note that accounts with subscriptions may go on to subscribe to other accounts - in this case,
           *         subscriptions will not be forwarded. Instead the former subscription's existing entries will still be
           *         used.
           */
          function subscribe(address registrant, address newSubscription) external onlyAddressOrOwner(registrant) {
              if (registrant == newSubscription) {
                  revert CannotSubscribeToSelf();
              }
              if (newSubscription == address(0)) {
                  revert CannotSubscribeToZeroAddress();
              }
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration == newSubscription) {
                  revert AlreadySubscribed(newSubscription);
              }
              address newSubscriptionRegistration = _registrations[newSubscription];
              if (newSubscriptionRegistration == address(0)) {
                  revert NotRegistered(newSubscription);
              }
              if (newSubscriptionRegistration != newSubscription) {
                  revert CannotSubscribeToRegistrantWithSubscription(newSubscription);
              }
              if (registration != registrant) {
                  _subscribers[registration].remove(registrant);
                  emit SubscriptionUpdated(registrant, registration, false);
              }
              _registrations[registrant] = newSubscription;
              _subscribers[newSubscription].add(registrant);
              emit SubscriptionUpdated(registrant, newSubscription, true);
          }
          /**
           * @notice Unsubscribe an address from its current subscribed registrant, and optionally copy its filtered operators and codeHashes.
           */
          function unsubscribe(address registrant, bool copyExistingEntries) external onlyAddressOrOwner(registrant) {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration == registrant) {
                  revert NotSubscribed();
              }
              _subscribers[registration].remove(registrant);
              _registrations[registrant] = registrant;
              emit SubscriptionUpdated(registrant, registration, false);
              if (copyExistingEntries) {
                  _copyEntries(registrant, registration);
              }
          }
          /**
           * @notice Copy filtered operators and codeHashes from a different registrantToCopy to addr.
           */
          function copyEntriesOf(address registrant, address registrantToCopy) external onlyAddressOrOwner(registrant) {
              if (registrant == registrantToCopy) {
                  revert CannotCopyFromSelf();
              }
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              address registrantRegistration = _registrations[registrantToCopy];
              if (registrantRegistration == address(0)) {
                  revert NotRegistered(registrantToCopy);
              }
              _copyEntries(registrant, registrantToCopy);
          }
          /// @dev helper to copy entries from registrantToCopy to registrant and emit events
          function _copyEntries(address registrant, address registrantToCopy) private {
              EnumerableSet.AddressSet storage filteredOperatorsRef = _filteredOperators[registrantToCopy];
              EnumerableSet.Bytes32Set storage filteredCodeHashesRef = _filteredCodeHashes[registrantToCopy];
              uint256 filteredOperatorsLength = filteredOperatorsRef.length();
              uint256 filteredCodeHashesLength = filteredCodeHashesRef.length();
              unchecked {
                  for (uint256 i = 0; i < filteredOperatorsLength; ++i) {
                      address operator = filteredOperatorsRef.at(i);
                      bool added = _filteredOperators[registrant].add(operator);
                      if (added) {
                          emit OperatorUpdated(registrant, operator, true);
                      }
                  }
                  for (uint256 i = 0; i < filteredCodeHashesLength; ++i) {
                      bytes32 codehash = filteredCodeHashesRef.at(i);
                      bool added = _filteredCodeHashes[registrant].add(codehash);
                      if (added) {
                          emit CodeHashUpdated(registrant, codehash, true);
                      }
                  }
              }
          }
          //////////////////
          // VIEW METHODS //
          //////////////////
          /**
           * @notice Get the subscription address of a given registrant, if any.
           */
          function subscriptionOf(address registrant) external view returns (address subscription) {
              subscription = _registrations[registrant];
              if (subscription == address(0)) {
                  revert NotRegistered(registrant);
              } else if (subscription == registrant) {
                  subscription = address(0);
              }
          }
          /**
           * @notice Get the set of addresses subscribed to a given registrant.
           *         Note that order is not guaranteed as updates are made.
           */
          function subscribers(address registrant) external view returns (address[] memory) {
              return _subscribers[registrant].values();
          }
          /**
           * @notice Get the subscriber at a given index in the set of addresses subscribed to a given registrant.
           *         Note that order is not guaranteed as updates are made.
           */
          function subscriberAt(address registrant, uint256 index) external view returns (address) {
              return _subscribers[registrant].at(index);
          }
          /**
           * @notice Returns true if operator is filtered by a given address or its subscription.
           */
          function isOperatorFiltered(address registrant, address operator) external view returns (bool) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredOperators[registration].contains(operator);
              }
              return _filteredOperators[registrant].contains(operator);
          }
          /**
           * @notice Returns true if a codeHash is filtered by a given address or its subscription.
           */
          function isCodeHashFiltered(address registrant, bytes32 codeHash) external view returns (bool) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].contains(codeHash);
              }
              return _filteredCodeHashes[registrant].contains(codeHash);
          }
          /**
           * @notice Returns true if the hash of an address's code is filtered by a given address or its subscription.
           */
          function isCodeHashOfFiltered(address registrant, address operatorWithCode) external view returns (bool) {
              bytes32 codeHash = operatorWithCode.codehash;
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].contains(codeHash);
              }
              return _filteredCodeHashes[registrant].contains(codeHash);
          }
          /**
           * @notice Returns true if an address has registered
           */
          function isRegistered(address registrant) external view returns (bool) {
              return _registrations[registrant] != address(0);
          }
          /**
           * @notice Returns a list of filtered operators for a given address or its subscription.
           */
          function filteredOperators(address registrant) external view returns (address[] memory) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredOperators[registration].values();
              }
              return _filteredOperators[registrant].values();
          }
          /**
           * @notice Returns the set of filtered codeHashes for a given address or its subscription.
           *         Note that order is not guaranteed as updates are made.
           */
          function filteredCodeHashes(address registrant) external view returns (bytes32[] memory) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].values();
              }
              return _filteredCodeHashes[registrant].values();
          }
          /**
           * @notice Returns the filtered operator at the given index of the set of filtered operators for a given address or
           *         its subscription.
           *         Note that order is not guaranteed as updates are made.
           */
          function filteredOperatorAt(address registrant, uint256 index) external view returns (address) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredOperators[registration].at(index);
              }
              return _filteredOperators[registrant].at(index);
          }
          /**
           * @notice Returns the filtered codeHash at the given index of the list of filtered codeHashes for a given address or
           *         its subscription.
           *         Note that order is not guaranteed as updates are made.
           */
          function filteredCodeHashAt(address registrant, uint256 index) external view returns (bytes32) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].at(index);
              }
              return _filteredCodeHashes[registrant].at(index);
          }
          /// @dev Convenience method to compute the code hash of an arbitrary contract
          function codeHashOf(address a) external view returns (bytes32) {
              return a.codehash;
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.13;
      contract OperatorFilterRegistryErrorsAndEvents {
          error CannotFilterEOAs();
          error AddressAlreadyFiltered(address operator);
          error AddressNotFiltered(address operator);
          error CodeHashAlreadyFiltered(bytes32 codeHash);
          error CodeHashNotFiltered(bytes32 codeHash);
          error OnlyAddressOrOwner();
          error NotRegistered(address registrant);
          error AlreadyRegistered();
          error AlreadySubscribed(address subscription);
          error NotSubscribed();
          error CannotUpdateWhileSubscribed(address subscription);
          error CannotSubscribeToSelf();
          error CannotSubscribeToZeroAddress();
          error NotOwnable();
          error AddressFiltered(address filtered);
          error CodeHashFiltered(address account, bytes32 codeHash);
          error CannotSubscribeToRegistrantWithSubscription(address registrant);
          error CannotCopyFromSelf();
          event RegistrationUpdated(address indexed registrant, bool indexed registered);
          event OperatorUpdated(address indexed registrant, address indexed operator, bool indexed filtered);
          event OperatorsUpdated(address indexed registrant, address[] operators, bool indexed filtered);
          event CodeHashUpdated(address indexed registrant, bytes32 indexed codeHash, bool indexed filtered);
          event CodeHashesUpdated(address indexed registrant, bytes32[] codeHashes, bool indexed filtered);
          event SubscriptionUpdated(address indexed registrant, address indexed subscription, bool indexed subscribed);
      }