ETH Price: $2,591.18 (-0.59%)

Transaction Decoder

Block:
22833421 at Jul-02-2025 06:47:35 PM +UTC
Transaction Fee:
0.000239949700316666 ETH $0.62
Gas Used:
134,159 Gas / 1.788547174 Gwei

Emitted Events:

323 TransparentUpgradeableProxy.0x4641df4a962071e12719d8c8c8e5ac7fc4d97b927346a3d7a335b1f7517e133c( 0x4641df4a962071e12719d8c8c8e5ac7fc4d97b927346a3d7a335b1f7517e133c, 0x28b90f5fa0248e9699af86cb25c2cdd334dc1b84a94b2c5bf11337089ddfa69d )
324 0x42b35351897f35aeb6c5b2d9eefe84191c6d724a.0x509a412175404a94c1003e6e0f08ba539fc2c450d6376bc6263a2368e141c3da( 0x509a412175404a94c1003e6e0f08ba539fc2c450d6376bc6263a2368e141c3da, 0x00000000000000000000000037b31c7239b6d7c38801bf32831c2bed66e7c1b6, 0x0000000000000000000000006774bcbd5cecef1336b5300fb5186a12ddd8b367 )
325 0x42b35351897f35aeb6c5b2d9eefe84191c6d724a.0x509a412175404a94c1003e6e0f08ba539fc2c450d6376bc6263a2368e141c3da( 0x509a412175404a94c1003e6e0f08ba539fc2c450d6376bc6263a2368e141c3da, 0x00000000000000000000000037b31c7239b6d7c38801bf32831c2bed66e7c1b6, 0x00000000000000000000000037b31c7239b6d7c38801bf32831c2bed66e7c1b6 )

Account State Difference:

  Address   Before After State Difference Code
0x37b31C72...D66E7C1B6
0.140534380516382492 Eth
Nonce: 1373
0.180256871325411826 Eth
Nonce: 1374
0.039722490809029334
0x42B35351...91C6d724a
0 Eth
Nonce: 93
0.000037559490654 Eth
Nonce: 94
0.000037559490654From: 0 To: 22892026638230306060177013438565229744157125598728899639
(Titan Builder)
6.938347168210604314 Eth6.938372767639177896 Eth0.000025599428573582
0x6774Bcbd...2DDD8b367
(Scroll: L1 Scroll Messenger Proxy)
29,702.9004366962711307 Eth29,702.8604366962711307 Eth0.04

Execution Trace

0x42b35351897f35aeb6c5b2d9eefe84191c6d724a.3f707e6b( )
  • TransparentUpgradeableProxy.c311b6fc( )
    • L1ScrollMessenger.relayMessageWithProof( _from=0x42B35351897f35aEB6c5B2d9eefE84191C6d724a, _to=0x42B35351897f35aEB6c5B2d9eefE84191C6d724a, _value=40000000000000000, _nonce=169703, _message=0x, _proof=[{name:batchIndex, type:uint256, order:1, indexed:false, value:311147, valueString:311147}, {name:merkleProof, type:bytes, order:2, indexed:false, value:0xC3328621F60CAD70561DC1D758F24D208D84A0B0FF75331705A4DA74510668B3CA1FBF6023C5A17F970B506B06CDB889709BA6BE68F90941C7D0232FDDA8D45137409E665D581413B086B0F28F9A4EE42EF5D99F58A6612206532CA9D08817172ED4326F0B904CCEE36DE6683F97A89E2F733548BFB08C8FE1FE8B80742E7A6BE58769B32A1BEAF1EA27375A44095A0D1FB664CE2DD358E7FCBFB78C26A19344BB277C8F06C565BFC4A44760EF7C0DF31629A8EEB37DA8FA23ECB16713A5C306781F6E1B34EADD6C82A2D9A5DE6968C5BA9B89562B3F8F06F890E793F78128999E3000E706EBA1F1083AC94E8F748F16F3BB779520BAE3524D6618DF9AACE9749867CC5F7F196B93BAE1E27E6320742445D290F2263827498B54FEC539F756AF69095643DF64007A80F83696447BCF9485BECF7A7869AA19F5162BF9989153FD3747FF28BB86A9BB710A1090118C93D978669C440433E8EC2D5071D0770F7654F8B13A49E282F609C317A833FB8D976D11517C571D1221A265D25AF778ECF8929BFAAECFB97AA9F700B94A55F08CE7EE796B1D982685784FD263DB24E2CCF8E9C1DF82D9C4B87413EAE2EF048F94B4D3554CEA73D92B0F7AF96E0271C691E2BB5C67ADD7C6CAF302256ADEDF7AB114DA0ACFE870D449A3A489F781D659E8BECC88FD29D4629534DDAF0AA9400EFAC1E01E3754ECBA17FC050FB30A9993D4D7992733E50F526EC2FA19A22B31E8ED50F23CD1FDF94C9154ED3A7609A2F1FF981F52E25D1E9CE7D1ACB85CABA116B8EA68633CA77967016B316F606F74D55061E0, valueString:0xC3328621F60CAD70561DC1D758F24D208D84A0B0FF75331705A4DA74510668B3CA1FBF6023C5A17F970B506B06CDB889709BA6BE68F90941C7D0232FDDA8D45137409E665D581413B086B0F28F9A4EE42EF5D99F58A6612206532CA9D08817172ED4326F0B904CCEE36DE6683F97A89E2F733548BFB08C8FE1FE8B80742E7A6BE58769B32A1BEAF1EA27375A44095A0D1FB664CE2DD358E7FCBFB78C26A19344BB277C8F06C565BFC4A44760EF7C0DF31629A8EEB37DA8FA23ECB16713A5C306781F6E1B34EADD6C82A2D9A5DE6968C5BA9B89562B3F8F06F890E793F78128999E3000E706EBA1F1083AC94E8F748F16F3BB779520BAE3524D6618DF9AACE9749867CC5F7F196B93BAE1E27E6320742445D290F2263827498B54FEC539F756AF69095643DF64007A80F83696447BCF9485BECF7A7869AA19F5162BF9989153FD3747FF28BB86A9BB710A1090118C93D978669C440433E8EC2D5071D0770F7654F8B13A49E282F609C317A833FB8D976D11517C571D1221A265D25AF778ECF8929BFAAECFB97AA9F700B94A55F08CE7EE796B1D982685784FD263DB24E2CCF8E9C1DF82D9C4B87413EAE2EF048F94B4D3554CEA73D92B0F7AF96E0271C691E2BB5C67ADD7C6CAF302256ADEDF7AB114DA0ACFE870D449A3A489F781D659E8BECC88FD29D4629534DDAF0AA9400EFAC1E01E3754ECBA17FC050FB30A9993D4D7992733E50F526EC2FA19A22B31E8ED50F23CD1FDF94C9154ED3A7609A2F1FF981F52E25D1E9CE7D1ACB85CABA116B8EA68633CA77967016B316F606F74D55061E0}] )
      • TransparentUpgradeableProxy.116a1f42( )
      • TransparentUpgradeableProxy.ea5f084f( )
        • ScrollChain.withdrawRoots( 311147 ) => ( 2384BC09B76BC5D50370AC23A0D68597BB1BF63144FDE8C9D9DDD7DF380EB0F8 )
        • ETH 0.04 0x42b35351897f35aeb6c5b2d9eefe84191c6d724a.CALL( )
        • ETH 0.039962440509346 0x37b31c7239b6d7c38801bf32831c2bed66e7c1b6.CALL( )
          File 1 of 4: TransparentUpgradeableProxy
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
          pragma solidity ^0.8.0;
          import "../ERC1967/ERC1967Proxy.sol";
          /**
           * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
           * does not implement this interface directly, and some of its functions are implemented by an internal dispatch
           * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
           * include them in the ABI so this interface must be used to interact with it.
           */
          interface ITransparentUpgradeableProxy is IERC1967 {
              function admin() external view returns (address);
              function implementation() external view returns (address);
              function changeAdmin(address) external;
              function upgradeTo(address) external;
              function upgradeToAndCall(address, bytes memory) external payable;
          }
          /**
           * @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.
           *
           * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
           * inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch
           * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
           * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
           * implementation.
           *
           * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler
           * will not check that there are no selector conflicts, due to the note above. A selector clash between any new function
           * and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could
           * render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised.
           */
          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) {
                  _changeAdmin(admin_);
              }
              /**
               * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
               *
               * CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the
               * implementation provides a function with the same selector.
               */
              modifier ifAdmin() {
                  if (msg.sender == _getAdmin()) {
                      _;
                  } else {
                      _fallback();
                  }
              }
              /**
               * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior
               */
              function _fallback() internal virtual override {
                  if (msg.sender == _getAdmin()) {
                      bytes memory ret;
                      bytes4 selector = msg.sig;
                      if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
                          ret = _dispatchUpgradeTo();
                      } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                          ret = _dispatchUpgradeToAndCall();
                      } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {
                          ret = _dispatchChangeAdmin();
                      } else if (selector == ITransparentUpgradeableProxy.admin.selector) {
                          ret = _dispatchAdmin();
                      } else if (selector == ITransparentUpgradeableProxy.implementation.selector) {
                          ret = _dispatchImplementation();
                      } else {
                          revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                      }
                      assembly {
                          return(add(ret, 0x20), mload(ret))
                      }
                  } else {
                      super._fallback();
                  }
              }
              /**
               * @dev Returns the current admin.
               *
               * 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 _dispatchAdmin() private returns (bytes memory) {
                  _requireZeroValue();
                  address admin = _getAdmin();
                  return abi.encode(admin);
              }
              /**
               * @dev Returns the current implementation.
               *
               * 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 _dispatchImplementation() private returns (bytes memory) {
                  _requireZeroValue();
                  address implementation = _implementation();
                  return abi.encode(implementation);
              }
              /**
               * @dev Changes the admin of the proxy.
               *
               * Emits an {AdminChanged} event.
               */
              function _dispatchChangeAdmin() private returns (bytes memory) {
                  _requireZeroValue();
                  address newAdmin = abi.decode(msg.data[4:], (address));
                  _changeAdmin(newAdmin);
                  return "";
              }
              /**
               * @dev Upgrade the implementation of the proxy.
               */
              function _dispatchUpgradeTo() private returns (bytes memory) {
                  _requireZeroValue();
                  address newImplementation = abi.decode(msg.data[4:], (address));
                  _upgradeToAndCall(newImplementation, bytes(""), false);
                  return "";
              }
              /**
               * @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.
               */
              function _dispatchUpgradeToAndCall() private returns (bytes memory) {
                  (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
                  _upgradeToAndCall(newImplementation, data, true);
                  return "";
              }
              /**
               * @dev Returns the current admin.
               *
               * CAUTION: This function is deprecated. Use {ERC1967Upgrade-_getAdmin} instead.
               */
              function _admin() internal view virtual returns (address) {
                  return _getAdmin();
              }
              /**
               * @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
               * emulate some proxy functions being non-payable while still allowing value to pass through.
               */
              function _requireZeroValue() private {
                  require(msg.value == 0);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
          pragma solidity ^0.8.0;
          import "../Proxy.sol";
          import "./ERC1967Upgrade.sol";
          /**
           * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
           * implementation address that can be changed. This address is stored in storage in the location specified by
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
           * implementation behind the proxy.
           */
          contract ERC1967Proxy is Proxy, ERC1967Upgrade {
              /**
               * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
               *
               * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
               * function call, and allows initializing the storage of the proxy like a Solidity constructor.
               */
              constructor(address _logic, bytes memory _data) payable {
                  _upgradeToAndCall(_logic, _data, false);
              }
              /**
               * @dev Returns the current implementation address.
               */
              function _implementation() internal view virtual override returns (address impl) {
                  return ERC1967Upgrade._getImplementation();
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
           * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
           * be specified by overriding the virtual {_implementation} function.
           *
           * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
           * different contract through the {_delegate} function.
           *
           * The success and return data of the delegated call will be returned back to the caller of the proxy.
           */
          abstract contract Proxy {
              /**
               * @dev Delegates the current call to `implementation`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _delegate(address implementation) internal virtual {
                  assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize())
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize())
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 {
                          revert(0, returndatasize())
                      }
                      default {
                          return(0, returndatasize())
                      }
                  }
              }
              /**
               * @dev This is a virtual function that should be overridden 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 internal 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 overridden should call `super._beforeFallback()`.
               */
              function _beforeFallback() internal virtual {}
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
          pragma solidity ^0.8.2;
          import "../beacon/IBeacon.sol";
          import "../../interfaces/IERC1967.sol";
          import "../../interfaces/draft-IERC1822.sol";
          import "../../utils/Address.sol";
          import "../../utils/StorageSlot.sol";
          /**
           * @dev This abstract contract provides getters and event emitting update functions for
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
           *
           * _Available since v4.1._
           */
          abstract contract ERC1967Upgrade is IERC1967 {
              // 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 Returns the current implementation address.
               */
              function _getImplementation() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
              }
              /**
               * @dev Stores a new address in the EIP1967 implementation slot.
               */
              function _setImplementation(address newImplementation) private {
                  require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                  StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
              }
              /**
               * @dev Perform implementation upgrade
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeTo(address newImplementation) internal {
                  _setImplementation(newImplementation);
                  emit Upgraded(newImplementation);
              }
              /**
               * @dev Perform implementation upgrade with additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                  _upgradeTo(newImplementation);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(newImplementation, data);
                  }
              }
              /**
               * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
                  // Upgrades from old implementations will perform a rollback test. This test requires the new
                  // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
                  // this special case will break upgrade paths from old UUPS implementation to new ones.
                  if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
                      _setImplementation(newImplementation);
                  } else {
                      try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                          require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
                      } catch {
                          revert("ERC1967Upgrade: new implementation is not UUPS");
                      }
                      _upgradeToAndCall(newImplementation, data, forceCall);
                  }
              }
              /**
               * @dev Storage slot with the admin of the contract.
               * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
              /**
               * @dev 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 Returns the current beacon.
               */
              function _getBeacon() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
              }
              /**
               * @dev Stores a new beacon in the EIP1967 beacon slot.
               */
              function _setBeacon(address newBeacon) private {
                  require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                  require(
                      Address.isContract(IBeacon(newBeacon).implementation()),
                      "ERC1967: beacon implementation is not a contract"
                  );
                  StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
              }
              /**
               * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
               * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
               *
               * Emits a {BeaconUpgraded} event.
               */
              function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                  _setBeacon(newBeacon);
                  emit BeaconUpgraded(newBeacon);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This is the interface that {BeaconProxy} expects of its beacon.
           */
          interface IBeacon {
              /**
               * @dev Must return an address that can be used as a delegate call target.
               *
               * {BeaconProxy} will check that this address is a contract.
               */
              function implementation() external view returns (address);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
           *
           * _Available since v4.8.3._
           */
          interface IERC1967 {
              /**
               * @dev Emitted when the implementation is upgraded.
               */
              event Upgraded(address indexed implementation);
              /**
               * @dev Emitted when the admin account has changed.
               */
              event AdminChanged(address previousAdmin, address newAdmin);
              /**
               * @dev Emitted when the beacon is changed.
               */
              event BeaconUpgraded(address indexed beacon);
          }
          // 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 IERC1822Proxiable {
              /**
               * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
               * address.
               *
               * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
               * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
               * function revert if invoked through a proxy.
               */
              function proxiableUUID() external view returns (bytes32);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
          // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for reading and writing primitive types to specific storage slots.
           *
           * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
           * This library helps with reading and writing to such slots without the need for inline assembly.
           *
           * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
           *
           * Example usage to set ERC1967 implementation slot:
           * ```solidity
           * contract ERC1967 {
           *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
           *
           *     function _getImplementation() internal view returns (address) {
           *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
           *     }
           *
           *     function _setImplementation(address newImplementation) internal {
           *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
           *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
           *     }
           * }
           * ```
           *
           * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
           * _Available since v4.9 for `string`, `bytes`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
              struct BooleanSlot {
                  bool value;
              }
              struct Bytes32Slot {
                  bytes32 value;
              }
              struct Uint256Slot {
                  uint256 value;
              }
              struct StringSlot {
                  string value;
              }
              struct BytesSlot {
                  bytes value;
              }
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
               */
              function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
               */
              function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
               */
              function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` with member `value` located at `slot`.
               */
              function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
               */
              function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` with member `value` located at `slot`.
               */
              function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
               */
              function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
          }
          

          File 2 of 4: L1ScrollMessenger
          // SPDX-License-Identifier: MIT
          pragma solidity =0.8.24;
          import {IScrollChain} from "./rollup/IScrollChain.sol";
          import {IL1MessageQueueV1} from "./rollup/IL1MessageQueueV1.sol";
          import {IL1MessageQueueV2} from "./rollup/IL1MessageQueueV2.sol";
          import {IL1ScrollMessenger} from "./IL1ScrollMessenger.sol";
          import {ScrollConstants} from "../libraries/constants/ScrollConstants.sol";
          import {IScrollMessenger} from "../libraries/IScrollMessenger.sol";
          import {ScrollMessengerBase} from "../libraries/ScrollMessengerBase.sol";
          import {WithdrawTrieVerifier} from "../libraries/verifier/WithdrawTrieVerifier.sol";
          import {IMessageDropCallback} from "../libraries/callbacks/IMessageDropCallback.sol";
          // solhint-disable avoid-low-level-calls
          // solhint-disable not-rely-on-time
          // solhint-disable reason-string
          /// @title L1ScrollMessenger
          /// @notice The `L1ScrollMessenger` contract can:
          ///
          /// 1. send messages from layer 1 to layer 2;
          /// 2. relay messages from layer 2 layer 1;
          /// 3. replay failed message by replacing the gas limit;
          /// 4. drop expired message due to sequencer problems.
          ///
          /// @dev All deposited Ether (including `WETH` deposited throng `L1WETHGateway`) will locked in
          /// this contract.
          ///
          /// The messages sent through this contract may failed due to out of gas or some contract errors layer 2. In such case,
          /// users can initiate `replayMessage` to retry this message in layer 2. If it is because out of gas, users can provide
          /// a larger `gasLimit`. Users need also to pay the cross domain relay fee again.
          ///
          /// The messages sent through this contract may possibly be skipped in layer 2 due to circuit capacity overflow.
          /// In such case, users can initiate `dropMessage` to claim refunds. But the cross domain relay fee won't be refunded.
          contract L1ScrollMessenger is ScrollMessengerBase, IL1ScrollMessenger {
              /**********
               * Errors *
               **********/
              error ErrorForbidToCallMessageQueue();
              /*************
               * Constants *
               *************/
              /// @notice The address of Rollup contract.
              address public immutable rollup;
              /// @notice The address of L1MessageQueueV1 contract.
              address public immutable messageQueueV1;
              /// @notice The address of L1MessageQueueV2 contract.
              address public immutable messageQueueV2;
              /// @notice The address of `EnforcedTxGateway`.
              address public immutable enforcedTxGateway;
              /***********
               * Structs *
               ***********/
              struct ReplayState {
                  // The number of replayed times.
                  uint128 times;
                  // The queue index of lastest replayed one. If it is zero, it means the message has not been replayed.
                  uint128 lastIndex;
              }
              /*************
               * Variables *
               *************/
              /// @notice Mapping from L1 message hash to the timestamp when the message is sent.
              mapping(bytes32 => uint256) public messageSendTimestamp;
              /// @notice Mapping from L2 message hash to a boolean value indicating if the message has been successfully executed.
              mapping(bytes32 => bool) public isL2MessageExecuted;
              /// @notice Mapping from L1 message hash to drop status.
              mapping(bytes32 => bool) public isL1MessageDropped;
              /// @dev The storage slot used as Rollup contract, which is deprecated now.
              address private __rollup;
              /// @dev The storage slot used as L1MessageQueue contract, which is deprecated now.
              address private __messageQueue;
              /// @notice The maximum number of times each L1 message can be replayed.
              uint256 public maxReplayTimes;
              /// @notice Mapping from L1 message hash to replay state.
              mapping(bytes32 => ReplayState) public replayStates;
              /// @notice Mapping from queue index to previous replay queue index.
              ///
              /// @dev If a message `x` was replayed 3 times with index `q1`, `q2` and `q3`, the
              /// value of `prevReplayIndex` and `replayStates` will be `replayStates[hash(x)].lastIndex = q3`,
              /// `replayStates[hash(x)].times = 3`, `prevReplayIndex[q3] = q2`, `prevReplayIndex[q2] = q1`,
              /// `prevReplayIndex[q1] = x` and `prevReplayIndex[x]=nil`.
              ///
              /// @dev The index `x` that `prevReplayIndex[x]=nil` is used as the termination of the list.
              /// Usually we use `0` to represent `nil`, but we cannot distinguish it with the first message
              /// with index zero. So a nonzero offset `1` is added to the value of `prevReplayIndex[x]` to
              /// avoid such situation.
              mapping(uint256 => uint256) public prevReplayIndex;
              /***************
               * Constructor *
               ***************/
              constructor(
                  address _counterpart,
                  address _rollup,
                  address _messageQueueV1,
                  address _messageQueueV2,
                  address _enforcedTxGateway
              ) ScrollMessengerBase(_counterpart) {
                  _disableInitializers();
                  rollup = _rollup;
                  messageQueueV1 = _messageQueueV1;
                  messageQueueV2 = _messageQueueV2;
                  enforcedTxGateway = _enforcedTxGateway;
              }
              /// @notice Initialize the storage of L1ScrollMessenger.
              ///
              /// @dev The parameters `_counterpart`, `_rollup` and `_messageQueue` are no longer used.
              ///
              /// @param _counterpart The address of L2ScrollMessenger contract in L2.
              /// @param _feeVault The address of fee vault, which will be used to collect relayer fee.
              /// @param _rollup The address of ScrollChain contract.
              /// @param _messageQueue The address of L1MessageQueue contract.
              function initialize(
                  address _counterpart,
                  address _feeVault,
                  address _rollup,
                  address _messageQueue
              ) public initializer {
                  ScrollMessengerBase.__ScrollMessengerBase_init(_counterpart, _feeVault);
                  __rollup = _rollup;
                  __messageQueue = _messageQueue;
                  maxReplayTimes = 3;
                  emit UpdateMaxReplayTimes(0, 3);
              }
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @inheritdoc IScrollMessenger
              function sendMessage(
                  address _to,
                  uint256 _value,
                  bytes memory _message,
                  uint256 _gasLimit
              ) external payable override whenNotPaused {
                  _sendMessage(_to, _value, _message, _gasLimit, _msgSender());
              }
              /// @inheritdoc IScrollMessenger
              function sendMessage(
                  address _to,
                  uint256 _value,
                  bytes calldata _message,
                  uint256 _gasLimit,
                  address _refundAddress
              ) external payable override whenNotPaused {
                  _sendMessage(_to, _value, _message, _gasLimit, _refundAddress);
              }
              /// @inheritdoc IL1ScrollMessenger
              function relayMessageWithProof(
                  address _from,
                  address _to,
                  uint256 _value,
                  uint256 _nonce,
                  bytes memory _message,
                  L2MessageProof memory _proof
              ) external override whenNotPaused notInExecution {
                  bytes32 _xDomainCalldataHash = keccak256(_encodeXDomainCalldata(_from, _to, _value, _nonce, _message));
                  require(!isL2MessageExecuted[_xDomainCalldataHash], "Message was already successfully executed");
                  {
                      require(IScrollChain(rollup).isBatchFinalized(_proof.batchIndex), "Batch is not finalized");
                      bytes32 _messageRoot = IScrollChain(rollup).withdrawRoots(_proof.batchIndex);
                      require(
                          WithdrawTrieVerifier.verifyMerkleProof(_messageRoot, _xDomainCalldataHash, _nonce, _proof.merkleProof),
                          "Invalid proof"
                      );
                  }
                  // @note check more `_to` address to avoid attack in the future when we add more gateways.
                  if (_to == messageQueueV1 || _to == messageQueueV2 || _to == enforcedTxGateway) {
                      revert ErrorForbidToCallMessageQueue();
                  }
                  _validateTargetAddress(_to);
                  // @note This usually will never happen, just in case.
                  require(_from != xDomainMessageSender, "Invalid message sender");
                  xDomainMessageSender = _from;
                  (bool success, ) = _to.call{value: _value}(_message);
                  // reset value to refund gas.
                  xDomainMessageSender = ScrollConstants.DEFAULT_XDOMAIN_MESSAGE_SENDER;
                  if (success) {
                      isL2MessageExecuted[_xDomainCalldataHash] = true;
                      emit RelayedMessage(_xDomainCalldataHash);
                  } else {
                      emit FailedRelayedMessage(_xDomainCalldataHash);
                  }
              }
              /// @inheritdoc IL1ScrollMessenger
              function replayMessage(
                  address _from,
                  address _to,
                  uint256 _value,
                  uint256 _messageNonce,
                  bytes memory _message,
                  uint32 _newGasLimit,
                  address _refundAddress
              ) external payable override whenNotPaused notInExecution {
                  // We will use a different `queueIndex` for the replaced message. However, the original `queueIndex` or `nonce`
                  // is encoded in the `_message`. We will check the `xDomainCalldata` on layer 2 to avoid duplicated execution.
                  // So, only one message will succeed on layer 2. If one of the message is executed successfully, the other one
                  // will revert with "Message was already successfully executed".
                  bytes memory _xDomainCalldata = _encodeXDomainCalldata(_from, _to, _value, _messageNonce, _message);
                  bytes32 _xDomainCalldataHash = keccak256(_xDomainCalldata);
                  require(messageSendTimestamp[_xDomainCalldataHash] > 0, "Provided message has not been enqueued");
                  // cannot replay dropped message
                  require(!isL1MessageDropped[_xDomainCalldataHash], "Message already dropped");
                  // compute and deduct the messaging fee to fee vault.
                  uint256 _fee = IL1MessageQueueV2(messageQueueV2).estimateCrossDomainMessageFee(_newGasLimit);
                  // charge relayer fee
                  require(msg.value >= _fee, "Insufficient msg.value for fee");
                  if (_fee > 0) {
                      (bool _success, ) = feeVault.call{value: _fee}("");
                      require(_success, "Failed to deduct the fee");
                  }
                  // enqueue the new transaction
                  uint256 _nextQueueIndex = IL1MessageQueueV2(messageQueueV2).nextCrossDomainMessageIndex();
                  IL1MessageQueueV2(messageQueueV2).appendCrossDomainMessage(counterpart, _newGasLimit, _xDomainCalldata);
                  ReplayState memory _replayState = replayStates[_xDomainCalldataHash];
                  // update the replayed message chain.
                  unchecked {
                      if (_replayState.lastIndex == 0) {
                          // the message has not been replayed before.
                          prevReplayIndex[_nextQueueIndex] = _messageNonce + 1;
                      } else {
                          prevReplayIndex[_nextQueueIndex] = _replayState.lastIndex + 1;
                      }
                  }
                  _replayState.lastIndex = uint128(_nextQueueIndex);
                  // update replay times
                  require(_replayState.times < maxReplayTimes, "Exceed maximum replay times");
                  unchecked {
                      _replayState.times += 1;
                  }
                  replayStates[_xDomainCalldataHash] = _replayState;
                  // refund fee to `_refundAddress`
                  unchecked {
                      uint256 _refund = msg.value - _fee;
                      if (_refund > 0) {
                          (bool _success, ) = _refundAddress.call{value: _refund}("");
                          require(_success, "Failed to refund the fee");
                      }
                  }
              }
              /// @inheritdoc IL1ScrollMessenger
              /// @dev Since we don't skip any messages in `L1MessageQueueV2`, only messages from `L1MessageQueueV1` can be dropped.
              function dropMessage(
                  address _from,
                  address _to,
                  uint256 _value,
                  uint256 _messageNonce,
                  bytes memory _message
              ) external override whenNotPaused notInExecution {
                  // The criteria for dropping a message:
                  // 1. The message is a L1 message.
                  // 2. The message has not been dropped before.
                  // 3. the message and all of its replacement are finalized in L1.
                  // 4. the message and all of its replacement are skipped.
                  //
                  // Possible denial of service attack:
                  // + replayMessage is called every time someone want to drop the message.
                  // + replayMessage is called so many times for a skipped message, thus results a long list.
                  //
                  // We limit the number of `replayMessage` calls of each message, which may solve the above problem.
                  // check message exists
                  bytes memory _xDomainCalldata = _encodeXDomainCalldata(_from, _to, _value, _messageNonce, _message);
                  bytes32 _xDomainCalldataHash = keccak256(_xDomainCalldata);
                  require(messageSendTimestamp[_xDomainCalldataHash] > 0, "Provided message has not been enqueued");
                  // check message not dropped
                  require(!isL1MessageDropped[_xDomainCalldataHash], "Message already dropped");
                  // check message is finalized
                  uint256 _lastIndex = replayStates[_xDomainCalldataHash].lastIndex;
                  if (_lastIndex == 0) _lastIndex = _messageNonce;
                  // check message is skipped and drop it.
                  // @note If the list is very long, the message may never be dropped.
                  while (true) {
                      // If the `_lastIndex` is from `messageQueueV2`, it will revert in `messageQueueV1.dropCrossDomainMessage`.
                      IL1MessageQueueV1(messageQueueV1).dropCrossDomainMessage(_lastIndex);
                      _lastIndex = prevReplayIndex[_lastIndex];
                      if (_lastIndex == 0) break;
                      unchecked {
                          _lastIndex = _lastIndex - 1;
                      }
                  }
                  isL1MessageDropped[_xDomainCalldataHash] = true;
                  // set execution context
                  xDomainMessageSender = ScrollConstants.DROP_XDOMAIN_MESSAGE_SENDER;
                  IMessageDropCallback(_from).onDropMessage{value: _value}(_message);
                  // clear execution context
                  xDomainMessageSender = ScrollConstants.DEFAULT_XDOMAIN_MESSAGE_SENDER;
              }
              /************************
               * Restricted Functions *
               ************************/
              /// @notice Update max replay times.
              /// @dev This function can only called by contract owner.
              /// @param _newMaxReplayTimes The new max replay times.
              function updateMaxReplayTimes(uint256 _newMaxReplayTimes) external onlyOwner {
                  uint256 _oldMaxReplayTimes = maxReplayTimes;
                  maxReplayTimes = _newMaxReplayTimes;
                  emit UpdateMaxReplayTimes(_oldMaxReplayTimes, _newMaxReplayTimes);
              }
              /**********************
               * Internal Functions *
               **********************/
              function _sendMessage(
                  address _to,
                  uint256 _value,
                  bytes memory _message,
                  uint256 _gasLimit,
                  address _refundAddress
              ) internal nonReentrant {
                  // compute the actual cross domain message calldata.
                  uint256 _messageNonce = IL1MessageQueueV2(messageQueueV2).nextCrossDomainMessageIndex();
                  bytes memory _xDomainCalldata = _encodeXDomainCalldata(_msgSender(), _to, _value, _messageNonce, _message);
                  // compute and deduct the messaging fee to fee vault.
                  uint256 _fee = IL1MessageQueueV2(messageQueueV2).estimateCrossDomainMessageFee(_gasLimit);
                  require(msg.value >= _fee + _value, "Insufficient msg.value");
                  if (_fee > 0) {
                      (bool _success, ) = feeVault.call{value: _fee}("");
                      require(_success, "Failed to deduct the fee");
                  }
                  // append message to L1MessageQueue
                  IL1MessageQueueV2(messageQueueV2).appendCrossDomainMessage(counterpart, _gasLimit, _xDomainCalldata);
                  // record the message hash for future use.
                  bytes32 _xDomainCalldataHash = keccak256(_xDomainCalldata);
                  // normally this won't happen, since each message has different nonce, but just in case.
                  require(messageSendTimestamp[_xDomainCalldataHash] == 0, "Duplicated message");
                  messageSendTimestamp[_xDomainCalldataHash] = block.timestamp;
                  emit SentMessage(_msgSender(), _to, _value, _messageNonce, _gasLimit, _message);
                  // refund fee to `_refundAddress`
                  unchecked {
                      uint256 _refund = msg.value - _fee - _value;
                      if (_refund > 0) {
                          (bool _success, ) = _refundAddress.call{value: _refund}("");
                          require(_success, "Failed to refund the fee");
                      }
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          /// @title IScrollChain
          /// @notice The interface for ScrollChain.
          interface IScrollChain {
              /**********
               * Events *
               **********/
              /// @notice Emitted when a new batch is committed.
              /// @param batchIndex The index of the batch.
              /// @param batchHash The hash of the batch.
              event CommitBatch(uint256 indexed batchIndex, bytes32 indexed batchHash);
              /// @notice revert a pending batch.
              /// @param batchIndex The index of the batch.
              /// @param batchHash The hash of the batch
              event RevertBatch(uint256 indexed batchIndex, bytes32 indexed batchHash);
              /// @notice revert a range of batches.
              /// @param startBatchIndex The start batch index of the range (inclusive).
              /// @param finishBatchIndex The finish batch index of the range (inclusive).
              event RevertBatch(uint256 indexed startBatchIndex, uint256 indexed finishBatchIndex);
              /// @notice Emitted when a batch is finalized.
              /// @param batchIndex The index of the batch.
              /// @param batchHash The hash of the batch
              /// @param stateRoot The state root on layer 2 after this batch.
              /// @param withdrawRoot The merkle root on layer2 after this batch.
              event FinalizeBatch(uint256 indexed batchIndex, bytes32 indexed batchHash, bytes32 stateRoot, bytes32 withdrawRoot);
              /// @notice Emitted when owner updates the status of sequencer.
              /// @param account The address of account updated.
              /// @param status The status of the account updated.
              event UpdateSequencer(address indexed account, bool status);
              /// @notice Emitted when owner updates the status of prover.
              /// @param account The address of account updated.
              /// @param status The status of the account updated.
              event UpdateProver(address indexed account, bool status);
              /// @notice Emitted when the value of `maxNumTxInChunk` is updated.
              /// @param oldMaxNumTxInChunk The old value of `maxNumTxInChunk`.
              /// @param newMaxNumTxInChunk The new value of `maxNumTxInChunk`.
              event UpdateMaxNumTxInChunk(uint256 oldMaxNumTxInChunk, uint256 newMaxNumTxInChunk);
              /// @notice Emitted when we enter or exit enforced batch mode.
              /// @param enabled True if we are entering enforced batch mode, false otherwise.
              /// @param lastCommittedBatchIndex The index of the last committed batch.
              event UpdateEnforcedBatchMode(bool enabled, uint256 lastCommittedBatchIndex);
              /*************************
               * Public View Functions *
               *************************/
              /// @return The latest finalized batch index.
              function lastFinalizedBatchIndex() external view returns (uint256);
              /// @param batchIndex The index of the batch.
              /// @return The batch hash of a committed batch.
              function committedBatches(uint256 batchIndex) external view returns (bytes32);
              /// @param batchIndex The index of the batch.
              /// @return The state root of a committed batch.
              function finalizedStateRoots(uint256 batchIndex) external view returns (bytes32);
              /// @param batchIndex The index of the batch.
              /// @return The message root of a committed batch.
              function withdrawRoots(uint256 batchIndex) external view returns (bytes32);
              /// @param batchIndex The index of the batch.
              /// @return Whether the batch is finalized by batch index.
              function isBatchFinalized(uint256 batchIndex) external view returns (bool);
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Commit a batch of transactions on layer 1 with blob data proof.
              ///
              /// @dev Memory layout of `blobDataProof`:
              /// |    z    |    y    | kzg_commitment | kzg_proof |
              /// |---------|---------|----------------|-----------|
              /// | bytes32 | bytes32 |    bytes48     |  bytes48  |
              ///
              /// @param version The version of current batch.
              /// @param parentBatchHeader The header of parent batch.
              /// @param chunks The list of encoded chunks, see the comments of `ChunkCodec`.
              /// @param skippedL1MessageBitmap The bitmap indicates whether each L1 message is skipped or not.
              /// @param blobDataProof The proof for blob data.
              function commitBatchWithBlobProof(
                  uint8 version,
                  bytes calldata parentBatchHeader,
                  bytes[] memory chunks,
                  bytes calldata skippedL1MessageBitmap,
                  bytes calldata blobDataProof
              ) external;
              /// @notice Commit one or more batches after the EuclidV2 upgrade.
              /// @param version The version of the committed batches.
              /// @param parentBatchHash The hash of parent batch.
              /// @param lastBatchHash The hash of the last committed batch after this call.
              /// @dev The batch payload is stored in the blobs.
              function commitBatches(
                  uint8 version,
                  bytes32 parentBatchHash,
                  bytes32 lastBatchHash
              ) external;
              /// @notice Revert pending batches.
              /// @dev one can only revert unfinalized batches.
              /// @param batchHeader The header of the last batch we want to keep.
              function revertBatch(bytes calldata batchHeader) external;
              /// @notice Finalize a list of committed batches (i.e. bundle) on layer 1.
              /// @param batchHeader The header of last batch in current bundle, see the encoding in comments of `commitBatch.
              /// @param postStateRoot The state root after current bundle.
              /// @param withdrawRoot The withdraw trie root after current batch.
              /// @param aggrProof The aggregation proof for current bundle.
              function finalizeBundleWithProof(
                  bytes calldata batchHeader,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bytes calldata aggrProof
              ) external;
              /// @notice Finalize a list of committed batches (i.e. bundle) on layer 1 after the EuclidV2 upgrade.
              /// @param batchHeader The header of the last batch in this bundle.
              /// @param totalL1MessagesPoppedOverall The number of messages processed after this bundle.
              /// @param postStateRoot The state root after this bundle.
              /// @param withdrawRoot The withdraw trie root after this bundle.
              /// @param aggrProof The bundle proof for this bundle.
              /// @dev See `BatchHeaderV7Codec` for the batch header encoding.
              function finalizeBundlePostEuclidV2(
                  bytes calldata batchHeader,
                  uint256 totalL1MessagesPoppedOverall,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bytes calldata aggrProof
              ) external;
              /// @notice The struct for permissionless batch finalization.
              /// @param batchHeader The header of this batch.
              /// @param totalL1MessagesPoppedOverall The number of messages processed after this bundle.
              /// @param postStateRoot The state root after this batch.
              /// @param withdrawRoot The withdraw trie root after this batch.
              /// @param zkProof The bundle proof for this batch (single-batch bundle).
              /// @dev See `BatchHeaderV7Codec` for the batch header encoding.
              struct FinalizeStruct {
                  bytes batchHeader;
                  uint256 totalL1MessagesPoppedOverall;
                  bytes32 postStateRoot;
                  bytes32 withdrawRoot;
                  bytes zkProof;
              }
              /// @notice Commit and finalize a batch in permissionless mode.
              /// @param version The version of current batch.
              /// @param parentBatchHash The hash of parent batch.
              /// @param finalizeStruct The data needed to finalize this batch.
              /// @dev The batch payload is stored in the blob.
              function commitAndFinalizeBatch(
                  uint8 version,
                  bytes32 parentBatchHash,
                  FinalizeStruct calldata finalizeStruct
              ) external;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          interface IL1MessageQueueV1 {
              /**********
               * Events *
               **********/
              /// @notice Emitted when a new L1 => L2 transaction is appended to the queue.
              /// @param sender The address of account who initiates the transaction.
              /// @param target The address of account who will receive the transaction.
              /// @param value The value passed with the transaction.
              /// @param queueIndex The index of this transaction in the queue.
              /// @param gasLimit Gas limit required to complete the message relay on L2.
              /// @param data The calldata of the transaction.
              event QueueTransaction(
                  address indexed sender,
                  address indexed target,
                  uint256 value,
                  uint64 queueIndex,
                  uint256 gasLimit,
                  bytes data
              );
              /// @notice Emitted when some L1 => L2 transactions are included in L1.
              /// @param startIndex The start index of messages popped.
              /// @param count The number of messages popped.
              /// @param skippedBitmap A bitmap indicates whether a message is skipped.
              event DequeueTransaction(uint256 startIndex, uint256 count, uint256 skippedBitmap);
              /// @notice Emitted when dequeued transactions are reset.
              /// @param startIndex The start index of messages.
              event ResetDequeuedTransaction(uint256 startIndex);
              /// @notice Emitted when some L1 => L2 transactions are finalized in L1.
              /// @param finalizedIndex The last index of messages finalized.
              event FinalizedDequeuedTransaction(uint256 finalizedIndex);
              /// @notice Emitted when a message is dropped from L1.
              /// @param index The index of message dropped.
              event DropTransaction(uint256 index);
              /// @notice Emitted when owner updates gas oracle contract.
              /// @param _oldGasOracle The address of old gas oracle contract.
              /// @param _newGasOracle The address of new gas oracle contract.
              event UpdateGasOracle(address indexed _oldGasOracle, address indexed _newGasOracle);
              /// @notice Emitted when owner updates max gas limit.
              /// @param _oldMaxGasLimit The old max gas limit.
              /// @param _newMaxGasLimit The new max gas limit.
              event UpdateMaxGasLimit(uint256 _oldMaxGasLimit, uint256 _newMaxGasLimit);
              /**********
               * Errors *
               **********/
              /// @dev Thrown when the given address is `address(0)`.
              error ErrorZeroAddress();
              /*************************
               * Public View Functions *
               *************************/
              /// @notice The start index of all pending inclusion messages.
              function pendingQueueIndex() external view returns (uint256);
              /// @notice The start index of all unfinalized messages.
              /// @dev All messages from `nextUnfinalizedQueueIndex` to `pendingQueueIndex-1` are committed but not finalized.
              function nextUnfinalizedQueueIndex() external view returns (uint256);
              /// @notice Return the index of next appended message.
              /// @dev Also the total number of appended messages.
              function nextCrossDomainMessageIndex() external view returns (uint256);
              /// @notice Return the message of in `queueIndex`.
              /// @param queueIndex The index to query.
              function getCrossDomainMessage(uint256 queueIndex) external view returns (bytes32);
              /// @notice Return the amount of ETH should pay for cross domain message.
              /// @param gasLimit Gas limit required to complete the message relay on L2.
              function estimateCrossDomainMessageFee(uint256 gasLimit) external view returns (uint256);
              /// @notice Return the amount of intrinsic gas fee should pay for cross domain message.
              /// @param _calldata The calldata of L1-initiated transaction.
              function calculateIntrinsicGasFee(bytes calldata _calldata) external view returns (uint256);
              /// @notice Return the hash of a L1 message.
              /// @param sender The address of sender.
              /// @param queueIndex The queue index of this message.
              /// @param value The amount of Ether transfer to target.
              /// @param target The address of target.
              /// @param gasLimit The gas limit provided.
              /// @param data The calldata passed to target address.
              function computeTransactionHash(
                  address sender,
                  uint256 queueIndex,
                  uint256 value,
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external view returns (bytes32);
              /// @notice Return whether the message is skipped.
              /// @param queueIndex The queue index of the message to check.
              function isMessageSkipped(uint256 queueIndex) external view returns (bool);
              /// @notice Return whether the message is dropped.
              /// @param queueIndex The queue index of the message to check.
              function isMessageDropped(uint256 queueIndex) external view returns (bool);
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Append a L1 to L2 message into this contract.
              /// @param target The address of target contract to call in L2.
              /// @param gasLimit The maximum gas should be used for relay this message in L2.
              /// @param data The calldata passed to target contract.
              function appendCrossDomainMessage(
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Append an enforced transaction to this contract.
              /// @dev The address of sender should be an EOA.
              /// @param sender The address of sender who will initiate this transaction in L2.
              /// @param target The address of target contract to call in L2.
              /// @param value The value passed
              /// @param gasLimit The maximum gas should be used for this transaction in L2.
              /// @param data The calldata passed to target contract.
              function appendEnforcedTransaction(
                  address sender,
                  address target,
                  uint256 value,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Pop messages from queue.
              ///
              /// @dev We can pop at most 256 messages each time. And if the message is not skipped,
              ///      the corresponding entry will be cleared.
              ///
              /// @param startIndex The start index to pop.
              /// @param count The number of messages to pop.
              /// @param skippedBitmap A bitmap indicates whether a message is skipped.
              function popCrossDomainMessage(
                  uint256 startIndex,
                  uint256 count,
                  uint256 skippedBitmap
              ) external;
              /// @notice Reset status of popped messages.
              ///
              /// @dev We can only reset unfinalized popped messages.
              ///
              /// @param startIndex The start index to reset.
              function resetPoppedCrossDomainMessage(uint256 startIndex) external;
              /// @notice Finalize status of popped messages.
              /// @param newFinalizedQueueIndexPlusOne The index of message to finalize plus one.
              function finalizePoppedCrossDomainMessage(uint256 newFinalizedQueueIndexPlusOne) external;
              /// @notice Drop a skipped message from the queue.
              function dropCrossDomainMessage(uint256 index) external;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          interface IL1MessageQueueV2 {
              /**********
               * Events *
               **********/
              /// @notice Emitted when a new L1 => L2 transaction is appended to the queue.
              /// @param sender The address of the sender account on L2.
              /// @param target The address of the target account on L2.
              /// @param value The ETH value transferred to the target account on L2.
              /// @param queueIndex The index of this transaction in the message queue.
              /// @param gasLimit The gas limit used on L2.
              /// @param data The calldata passed to the target account on L2.
              event QueueTransaction(
                  address indexed sender,
                  address indexed target,
                  uint256 value,
                  uint64 queueIndex,
                  uint256 gasLimit,
                  bytes data
              );
              /// @notice Emitted when some L1 => L2 transactions are finalized on L1.
              /// @param finalizedIndex The index of the last message finalized.
              event FinalizedDequeuedTransaction(uint256 finalizedIndex);
              /*************************
               * Public View Functions *
               *************************/
              /// @notice Return the start index of all messages in this contract.
              function firstCrossDomainMessageIndex() external view returns (uint256);
              /// @notice Return the start index of all unfinalized messages.
              function nextUnfinalizedQueueIndex() external view returns (uint256);
              /// @notice Return the index to be used for the next message.
              /// @dev Also the total number of appended messages, including messages in `L1MessageQueueV1`.
              function nextCrossDomainMessageIndex() external view returns (uint256);
              /// @notice Return the message rolling hash of `queueIndex`.
              /// @param queueIndex The index to query.
              function getMessageRollingHash(uint256 queueIndex) external view returns (bytes32);
              /// @notice Return the message enqueue timestamp of `queueIndex`.
              /// @param queueIndex The index to query.
              function getMessageEnqueueTimestamp(uint256 queueIndex) external view returns (uint256);
              /// @notice Return the first unfinalized message enqueue timestamp.
              function getFirstUnfinalizedMessageEnqueueTime() external view returns (uint256);
              /// @notice Return the amount of ETH that should be paid for a cross-domain message.
              /// @param gasLimit The gas limit required to complete the message relay on L2.
              function estimateCrossDomainMessageFee(uint256 gasLimit) external view returns (uint256);
              /// @notice Return the estimated base fee on L2.
              function estimateL2BaseFee() external view returns (uint256);
              /// @notice Return the intrinsic gas required by the provided cross-domain message.
              /// @param data The calldata of the cross-domain message.
              function calculateIntrinsicGasFee(bytes calldata data) external view returns (uint256);
              /// @notice Compute the transaction hash of an L1 message.
              /// @param sender The address of the sender account.
              /// @param queueIndex The index of this transaction in the message queue.
              /// @param value The ETH value transferred to the target account.
              /// @param target The address of the target account.
              /// @param gasLimit The gas limit provided.
              /// @param data The calldata passed to the target account.
              function computeTransactionHash(
                  address sender,
                  uint256 queueIndex,
                  uint256 value,
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external view returns (bytes32);
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Append a L1 => L2 cross-domain message to the message queue.
              /// @param target The address of the target account on L2.
              /// @param gasLimit The gas limit used on L2.
              /// @param data The calldata passed to the target account on L2.
              /// @dev This function can only be called by `L1ScrollMessenger`.
              function appendCrossDomainMessage(
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Append an enforced transaction to the message queue.
              /// @param sender The address of the sender account on L2.
              /// @param target The address of the target account on L2.
              /// @param value The ETH value transferred to the target account on L2.
              /// @param gasLimit The gas limit used on L2.
              /// @param data The calldata passed to the target account on L2.
              /// @dev This function can only be called by `EnforcedTxGateway`.
              function appendEnforcedTransaction(
                  address sender,
                  address target,
                  uint256 value,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Mark cross-domain messages as finalized.
              /// @param nextUnfinalizedQueueIndex The index of the first unfinalized message after this call.
              /// @dev This function can only be called by `ScrollChain`.
              function finalizePoppedCrossDomainMessage(uint256 nextUnfinalizedQueueIndex) external;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          import {IScrollMessenger} from "../libraries/IScrollMessenger.sol";
          interface IL1ScrollMessenger is IScrollMessenger {
              /**********
               * Events *
               **********/
              /// @notice Emitted when the maximum number of times each message can be replayed is updated.
              /// @param oldMaxReplayTimes The old maximum number of times each message can be replayed.
              /// @param newMaxReplayTimes The new maximum number of times each message can be replayed.
              event UpdateMaxReplayTimes(uint256 oldMaxReplayTimes, uint256 newMaxReplayTimes);
              /***********
               * Structs *
               ***********/
              struct L2MessageProof {
                  // The index of the batch where the message belongs to.
                  uint256 batchIndex;
                  // Concatenation of merkle proof for withdraw merkle trie.
                  bytes merkleProof;
              }
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Relay a L2 => L1 message with message proof.
              /// @param from The address of the sender of the message.
              /// @param to The address of the recipient of the message.
              /// @param value The msg.value passed to the message call.
              /// @param nonce The nonce of the message to avoid replay attack.
              /// @param message The content of the message.
              /// @param proof The proof used to verify the correctness of the transaction.
              function relayMessageWithProof(
                  address from,
                  address to,
                  uint256 value,
                  uint256 nonce,
                  bytes memory message,
                  L2MessageProof memory proof
              ) external;
              /// @notice Replay an existing message.
              /// @param from The address of the sender of the message.
              /// @param to The address of the recipient of the message.
              /// @param value The msg.value passed to the message call.
              /// @param messageNonce The nonce for the message to replay.
              /// @param message The content of the message.
              /// @param newGasLimit New gas limit to be used for this message.
              /// @param refundAddress The address of account who will receive the refunded fee.
              function replayMessage(
                  address from,
                  address to,
                  uint256 value,
                  uint256 messageNonce,
                  bytes memory message,
                  uint32 newGasLimit,
                  address refundAddress
              ) external payable;
              /// @notice Drop a skipped message.
              /// @param from The address of the sender of the message.
              /// @param to The address of the recipient of the message.
              /// @param value The msg.value passed to the message call.
              /// @param messageNonce The nonce for the message to drop.
              /// @param message The content of the message.
              function dropMessage(
                  address from,
                  address to,
                  uint256 value,
                  uint256 messageNonce,
                  bytes memory message
              ) external;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          library ScrollConstants {
              /// @notice The address of default cross chain message sender.
              address internal constant DEFAULT_XDOMAIN_MESSAGE_SENDER = address(1);
              /// @notice The address for dropping message.
              /// @dev The first 20 bytes of keccak("drop")
              address internal constant DROP_XDOMAIN_MESSAGE_SENDER = 0x6f297C61B5C92eF107fFD30CD56AFFE5A273e841;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          interface IScrollMessenger {
              /**********
               * Events *
               **********/
              /// @notice Emitted when a cross domain message is sent.
              /// @param sender The address of the sender who initiates the message.
              /// @param target The address of target contract to call.
              /// @param value The amount of value passed to the target contract.
              /// @param messageNonce The nonce of the message.
              /// @param gasLimit The optional gas limit passed to L1 or L2.
              /// @param message The calldata passed to the target contract.
              event SentMessage(
                  address indexed sender,
                  address indexed target,
                  uint256 value,
                  uint256 messageNonce,
                  uint256 gasLimit,
                  bytes message
              );
              /// @notice Emitted when a cross domain message is relayed successfully.
              /// @param messageHash The hash of the message.
              event RelayedMessage(bytes32 indexed messageHash);
              /// @notice Emitted when a cross domain message is failed to relay.
              /// @param messageHash The hash of the message.
              event FailedRelayedMessage(bytes32 indexed messageHash);
              /**********
               * Errors *
               **********/
              /// @dev Thrown when the given address is `address(0)`.
              error ErrorZeroAddress();
              /*************************
               * Public View Functions *
               *************************/
              /// @notice Return the sender of a cross domain message.
              function xDomainMessageSender() external view returns (address);
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Send cross chain message from L1 to L2 or L2 to L1.
              /// @param target The address of account who receive the message.
              /// @param value The amount of ether passed when call target contract.
              /// @param message The content of the message.
              /// @param gasLimit Gas limit required to complete the message relay on corresponding chain.
              function sendMessage(
                  address target,
                  uint256 value,
                  bytes calldata message,
                  uint256 gasLimit
              ) external payable;
              /// @notice Send cross chain message from L1 to L2 or L2 to L1.
              /// @param target The address of account who receive the message.
              /// @param value The amount of ether passed when call target contract.
              /// @param message The content of the message.
              /// @param gasLimit Gas limit required to complete the message relay on corresponding chain.
              /// @param refundAddress The address of account who will receive the refunded fee.
              function sendMessage(
                  address target,
                  uint256 value,
                  bytes calldata message,
                  uint256 gasLimit,
                  address refundAddress
              ) external payable;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
          import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
          import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
          import {ScrollConstants} from "./constants/ScrollConstants.sol";
          import {IScrollMessenger} from "./IScrollMessenger.sol";
          // solhint-disable var-name-mixedcase
          abstract contract ScrollMessengerBase is
              OwnableUpgradeable,
              PausableUpgradeable,
              ReentrancyGuardUpgradeable,
              IScrollMessenger
          {
              /**********
               * Events *
               **********/
              /// @notice Emitted when owner updates fee vault contract.
              /// @param _oldFeeVault The address of old fee vault contract.
              /// @param _newFeeVault The address of new fee vault contract.
              event UpdateFeeVault(address _oldFeeVault, address _newFeeVault);
              /*************
               * Constants *
               *************/
              /// @notice The address of counterpart ScrollMessenger contract in L1/L2.
              address public immutable counterpart;
              /*************
               * Variables *
               *************/
              /// @notice See {IScrollMessenger-xDomainMessageSender}
              address public override xDomainMessageSender;
              /// @dev The storage slot used as counterpart ScrollMessenger contract, which is deprecated now.
              address private __counterpart;
              /// @notice The address of fee vault, collecting cross domain messaging fee.
              address public feeVault;
              /// @dev The storage slot used as ETH rate limiter contract, which is deprecated now.
              address private __rateLimiter;
              /// @dev The storage slots for future usage.
              uint256[46] private __gap;
              /**********************
               * Function Modifiers *
               **********************/
              modifier notInExecution() {
                  require(
                      xDomainMessageSender == ScrollConstants.DEFAULT_XDOMAIN_MESSAGE_SENDER,
                      "Message is already in execution"
                  );
                  _;
              }
              /***************
               * Constructor *
               ***************/
              constructor(address _counterpart) {
                  if (_counterpart == address(0)) {
                      revert ErrorZeroAddress();
                  }
                  counterpart = _counterpart;
              }
              function __ScrollMessengerBase_init(address, address _feeVault) internal onlyInitializing {
                  OwnableUpgradeable.__Ownable_init();
                  PausableUpgradeable.__Pausable_init();
                  ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
                  // initialize to a nonzero value
                  xDomainMessageSender = ScrollConstants.DEFAULT_XDOMAIN_MESSAGE_SENDER;
                  if (_feeVault != address(0)) {
                      feeVault = _feeVault;
                  }
              }
              // make sure only owner can send ether to messenger to avoid possible user fund loss.
              receive() external payable onlyOwner {}
              /************************
               * Restricted Functions *
               ************************/
              /// @notice Update fee vault contract.
              /// @dev This function can only called by contract owner.
              /// @param _newFeeVault The address of new fee vault contract.
              function updateFeeVault(address _newFeeVault) external onlyOwner {
                  address _oldFeeVault = feeVault;
                  feeVault = _newFeeVault;
                  emit UpdateFeeVault(_oldFeeVault, _newFeeVault);
              }
              /// @notice Pause the contract
              /// @dev This function can only called by contract owner.
              /// @param _status The pause status to update.
              function setPause(bool _status) external onlyOwner {
                  if (_status) {
                      _pause();
                  } else {
                      _unpause();
                  }
              }
              /**********************
               * Internal Functions *
               **********************/
              /// @dev Internal function to generate the correct cross domain calldata for a message.
              /// @param _sender Message sender address.
              /// @param _target Target contract address.
              /// @param _value The amount of ETH pass to the target.
              /// @param _messageNonce Nonce for the provided message.
              /// @param _message Message to send to the target.
              /// @return ABI encoded cross domain calldata.
              function _encodeXDomainCalldata(
                  address _sender,
                  address _target,
                  uint256 _value,
                  uint256 _messageNonce,
                  bytes memory _message
              ) internal pure returns (bytes memory) {
                  return
                      abi.encodeWithSignature(
                          "relayMessage(address,address,uint256,uint256,bytes)",
                          _sender,
                          _target,
                          _value,
                          _messageNonce,
                          _message
                      );
              }
              /// @dev Internal function to check whether the `_target` address is allowed to avoid attack.
              /// @param _target The address of target address to check.
              function _validateTargetAddress(address _target) internal view {
                  // @note check more `_target` address to avoid attack in the future when we add more external contracts.
                  require(_target != address(this), "Forbid to call self");
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          // solhint-disable no-inline-assembly
          library WithdrawTrieVerifier {
              /// @dev Verify the merkle proof given root, leaf node and proof.
              ///
              /// Vulnerability:
              ///   The initially provided message hash can be hashed with the first hash of the proof,
              ///   thereby giving an intermediate node of the trie. This can then be used with a shortened
              ///   proof to pass the verification, which may lead to replayability.
              ///
              ///   However, it is designed to verify the withdraw trie in `L2MessageQueue`. The `_hash` given
              ///   in the parameter is always a leaf node. So we assume the length of proof is correct and
              ///   cannot be shortened.
              /// @param _root The expected root node hash of the withdraw trie.
              /// @param _hash The leaf node hash of the withdraw trie.
              /// @param _nonce The index of the leaf node from left to right, starting from 0.
              /// @param _proof The concatenated merkle proof verified the leaf node.
              function verifyMerkleProof(
                  bytes32 _root,
                  bytes32 _hash,
                  uint256 _nonce,
                  bytes memory _proof
              ) internal pure returns (bool) {
                  require(_proof.length % 32 == 0, "Invalid proof");
                  uint256 _length = _proof.length / 32;
                  for (uint256 i = 0; i < _length; i++) {
                      bytes32 item;
                      assembly {
                          item := mload(add(add(_proof, 0x20), mul(i, 0x20)))
                      }
                      if (_nonce % 2 == 0) {
                          _hash = _efficientHash(_hash, item);
                      } else {
                          _hash = _efficientHash(item, _hash);
                      }
                      _nonce /= 2;
                  }
                  return _hash == _root;
              }
              function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
                  // solhint-disable-next-line no-inline-assembly
                  assembly {
                      mstore(0x00, a)
                      mstore(0x20, b)
                      value := keccak256(0x00, 0x40)
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          interface IMessageDropCallback {
              function onDropMessage(bytes memory message) external payable;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby disabling any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                  _transferOwnership(newOwner);
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Internal function without access restriction.
               */
              function _transferOwnership(address newOwner) internal virtual {
                  address oldOwner = _owner;
                  _owner = newOwner;
                  emit OwnershipTransferred(oldOwner, newOwner);
              }
              /**
               * @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) (security/Pausable.sol)
          pragma solidity ^0.8.0;
          import "../utils/ContextUpgradeable.sol";
          import "../proxy/utils/Initializable.sol";
          /**
           * @dev Contract module which allows children to implement an emergency stop
           * mechanism that can be triggered by an authorized account.
           *
           * This module is used through inheritance. It will make available the
           * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
           * the functions of your contract. Note that they will not be pausable by
           * simply including this module, only once the modifiers are put in place.
           */
          abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
              /**
               * @dev Emitted when the pause is triggered by `account`.
               */
              event Paused(address account);
              /**
               * @dev Emitted when the pause is lifted by `account`.
               */
              event Unpaused(address account);
              bool private _paused;
              /**
               * @dev Initializes the contract in unpaused state.
               */
              function __Pausable_init() internal onlyInitializing {
                  __Pausable_init_unchained();
              }
              function __Pausable_init_unchained() internal onlyInitializing {
                  _paused = false;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is not paused.
               *
               * Requirements:
               *
               * - The contract must not be paused.
               */
              modifier whenNotPaused() {
                  _requireNotPaused();
                  _;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is paused.
               *
               * Requirements:
               *
               * - The contract must be paused.
               */
              modifier whenPaused() {
                  _requirePaused();
                  _;
              }
              /**
               * @dev Returns true if the contract is paused, and false otherwise.
               */
              function paused() public view virtual returns (bool) {
                  return _paused;
              }
              /**
               * @dev Throws if the contract is paused.
               */
              function _requireNotPaused() internal view virtual {
                  require(!paused(), "Pausable: paused");
              }
              /**
               * @dev Throws if the contract is not paused.
               */
              function _requirePaused() internal view virtual {
                  require(paused(), "Pausable: not paused");
              }
              /**
               * @dev Triggers stopped state.
               *
               * Requirements:
               *
               * - The contract must not be paused.
               */
              function _pause() internal virtual whenNotPaused {
                  _paused = true;
                  emit Paused(_msgSender());
              }
              /**
               * @dev Returns to normal state.
               *
               * Requirements:
               *
               * - The contract must be paused.
               */
              function _unpause() internal virtual whenPaused {
                  _paused = false;
                  emit Unpaused(_msgSender());
              }
              /**
               * @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.9.0) (security/ReentrancyGuard.sol)
          pragma solidity ^0.8.0;
          import "../proxy/utils/Initializable.sol";
          /**
           * @dev Contract module that helps prevent reentrant calls to a function.
           *
           * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
           * available, which can be applied to functions to make sure there are no nested
           * (reentrant) calls to them.
           *
           * Note that because there is a single `nonReentrant` guard, functions marked as
           * `nonReentrant` may not call one another. This can be worked around by making
           * those functions `private`, and then adding `external` `nonReentrant` entry
           * points to them.
           *
           * TIP: If you would like to learn more about reentrancy and alternative ways
           * to protect against it, check out our blog post
           * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
           */
          abstract contract ReentrancyGuardUpgradeable is Initializable {
              // Booleans are more expensive than uint256 or any type that takes up a full
              // word because each write operation emits an extra SLOAD to first read the
              // slot's contents, replace the bits taken up by the boolean, and then write
              // back. This is the compiler's defense against contract upgrades and
              // pointer aliasing, and it cannot be disabled.
              // The values being non-zero value makes deployment a bit more expensive,
              // but in exchange the refund on every call to nonReentrant will be lower in
              // amount. Since refunds are capped to a percentage of the total
              // transaction's gas, it is best to keep them low in cases like this one, to
              // increase the likelihood of the full refund coming into effect.
              uint256 private constant _NOT_ENTERED = 1;
              uint256 private constant _ENTERED = 2;
              uint256 private _status;
              function __ReentrancyGuard_init() internal onlyInitializing {
                  __ReentrancyGuard_init_unchained();
              }
              function __ReentrancyGuard_init_unchained() internal onlyInitializing {
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev Prevents a contract from calling itself, directly or indirectly.
               * Calling a `nonReentrant` function from another `nonReentrant`
               * function is not supported. It is possible to prevent this from happening
               * by making the `nonReentrant` function external, and making it call a
               * `private` function that does the actual work.
               */
              modifier nonReentrant() {
                  _nonReentrantBefore();
                  _;
                  _nonReentrantAfter();
              }
              function _nonReentrantBefore() private {
                  // On the first call to nonReentrant, _status will be _NOT_ENTERED
                  require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                  // Any calls to nonReentrant after this point will fail
                  _status = _ENTERED;
              }
              function _nonReentrantAfter() private {
                  // By storing the original value once again, a refund is triggered (see
                  // https://eips.ethereum.org/EIPS/eip-2200)
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
               * `nonReentrant` function in the call stack.
               */
              function _reentrancyGuardEntered() internal view returns (bool) {
                  return _status == _ENTERED;
              }
              /**
               * @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 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.9.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]
           * ```solidity
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           *
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
               * constructor.
               *
               * Emits an {Initialized} event.
               */
              modifier initializer() {
                  bool isTopLevelCall = !_initializing;
                  require(
                      (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                      "Initializable: contract is already initialized"
                  );
                  _initialized = 1;
                  if (isTopLevelCall) {
                      _initializing = true;
                  }
                  _;
                  if (isTopLevelCall) {
                      _initializing = false;
                      emit Initialized(1);
                  }
              }
              /**
               * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
               * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
               * used to initialize parent contracts.
               *
               * A reinitializer may be used after the original initialization step. This is essential to configure modules that
               * are added through upgrades and that require initialization.
               *
               * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
               * cannot be nested. If one is invoked in the context of another, execution will revert.
               *
               * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
               * a contract, executing them in the right order is up to the developer or operator.
               *
               * WARNING: setting the version to 255 will prevent any future reinitialization.
               *
               * Emits an {Initialized} event.
               */
              modifier reinitializer(uint8 version) {
                  require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                  _initialized = version;
                  _initializing = true;
                  _;
                  _initializing = false;
                  emit Initialized(version);
              }
              /**
               * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
               * {initializer} and {reinitializer} modifiers, directly or indirectly.
               */
              modifier onlyInitializing() {
                  require(_initializing, "Initializable: contract is not initializing");
                  _;
              }
              /**
               * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
               * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
               * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
               * through proxies.
               *
               * Emits an {Initialized} event the first time it is successfully executed.
               */
              function _disableInitializers() internal virtual {
                  require(!_initializing, "Initializable: contract is initializing");
                  if (_initialized != type(uint8).max) {
                      _initialized = type(uint8).max;
                      emit Initialized(type(uint8).max);
                  }
              }
              /**
               * @dev Returns the highest version that has been initialized. See {reinitializer}.
               */
              function _getInitializedVersion() internal view returns (uint8) {
                  return _initialized;
              }
              /**
               * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
               */
              function _isInitializing() internal view returns (bool) {
                  return _initializing;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/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
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          

          File 3 of 4: TransparentUpgradeableProxy
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
          pragma solidity ^0.8.0;
          import "../ERC1967/ERC1967Proxy.sol";
          /**
           * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
           * does not implement this interface directly, and some of its functions are implemented by an internal dispatch
           * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
           * include them in the ABI so this interface must be used to interact with it.
           */
          interface ITransparentUpgradeableProxy is IERC1967 {
              function admin() external view returns (address);
              function implementation() external view returns (address);
              function changeAdmin(address) external;
              function upgradeTo(address) external;
              function upgradeToAndCall(address, bytes memory) external payable;
          }
          /**
           * @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.
           *
           * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
           * inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch
           * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
           * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
           * implementation.
           *
           * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler
           * will not check that there are no selector conflicts, due to the note above. A selector clash between any new function
           * and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could
           * render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised.
           */
          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) {
                  _changeAdmin(admin_);
              }
              /**
               * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
               *
               * CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the
               * implementation provides a function with the same selector.
               */
              modifier ifAdmin() {
                  if (msg.sender == _getAdmin()) {
                      _;
                  } else {
                      _fallback();
                  }
              }
              /**
               * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior
               */
              function _fallback() internal virtual override {
                  if (msg.sender == _getAdmin()) {
                      bytes memory ret;
                      bytes4 selector = msg.sig;
                      if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {
                          ret = _dispatchUpgradeTo();
                      } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                          ret = _dispatchUpgradeToAndCall();
                      } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {
                          ret = _dispatchChangeAdmin();
                      } else if (selector == ITransparentUpgradeableProxy.admin.selector) {
                          ret = _dispatchAdmin();
                      } else if (selector == ITransparentUpgradeableProxy.implementation.selector) {
                          ret = _dispatchImplementation();
                      } else {
                          revert("TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                      }
                      assembly {
                          return(add(ret, 0x20), mload(ret))
                      }
                  } else {
                      super._fallback();
                  }
              }
              /**
               * @dev Returns the current admin.
               *
               * 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 _dispatchAdmin() private returns (bytes memory) {
                  _requireZeroValue();
                  address admin = _getAdmin();
                  return abi.encode(admin);
              }
              /**
               * @dev Returns the current implementation.
               *
               * 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 _dispatchImplementation() private returns (bytes memory) {
                  _requireZeroValue();
                  address implementation = _implementation();
                  return abi.encode(implementation);
              }
              /**
               * @dev Changes the admin of the proxy.
               *
               * Emits an {AdminChanged} event.
               */
              function _dispatchChangeAdmin() private returns (bytes memory) {
                  _requireZeroValue();
                  address newAdmin = abi.decode(msg.data[4:], (address));
                  _changeAdmin(newAdmin);
                  return "";
              }
              /**
               * @dev Upgrade the implementation of the proxy.
               */
              function _dispatchUpgradeTo() private returns (bytes memory) {
                  _requireZeroValue();
                  address newImplementation = abi.decode(msg.data[4:], (address));
                  _upgradeToAndCall(newImplementation, bytes(""), false);
                  return "";
              }
              /**
               * @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.
               */
              function _dispatchUpgradeToAndCall() private returns (bytes memory) {
                  (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
                  _upgradeToAndCall(newImplementation, data, true);
                  return "";
              }
              /**
               * @dev Returns the current admin.
               *
               * CAUTION: This function is deprecated. Use {ERC1967Upgrade-_getAdmin} instead.
               */
              function _admin() internal view virtual returns (address) {
                  return _getAdmin();
              }
              /**
               * @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to
               * emulate some proxy functions being non-payable while still allowing value to pass through.
               */
              function _requireZeroValue() private {
                  require(msg.value == 0);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
          pragma solidity ^0.8.0;
          import "../Proxy.sol";
          import "./ERC1967Upgrade.sol";
          /**
           * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
           * implementation address that can be changed. This address is stored in storage in the location specified by
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
           * implementation behind the proxy.
           */
          contract ERC1967Proxy is Proxy, ERC1967Upgrade {
              /**
               * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
               *
               * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
               * function call, and allows initializing the storage of the proxy like a Solidity constructor.
               */
              constructor(address _logic, bytes memory _data) payable {
                  _upgradeToAndCall(_logic, _data, false);
              }
              /**
               * @dev Returns the current implementation address.
               */
              function _implementation() internal view virtual override returns (address impl) {
                  return ERC1967Upgrade._getImplementation();
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
           * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
           * be specified by overriding the virtual {_implementation} function.
           *
           * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
           * different contract through the {_delegate} function.
           *
           * The success and return data of the delegated call will be returned back to the caller of the proxy.
           */
          abstract contract Proxy {
              /**
               * @dev Delegates the current call to `implementation`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _delegate(address implementation) internal virtual {
                  assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize())
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize())
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 {
                          revert(0, returndatasize())
                      }
                      default {
                          return(0, returndatasize())
                      }
                  }
              }
              /**
               * @dev This is a virtual function that should be overridden 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 internal 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 overridden should call `super._beforeFallback()`.
               */
              function _beforeFallback() internal virtual {}
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
          pragma solidity ^0.8.2;
          import "../beacon/IBeacon.sol";
          import "../../interfaces/IERC1967.sol";
          import "../../interfaces/draft-IERC1822.sol";
          import "../../utils/Address.sol";
          import "../../utils/StorageSlot.sol";
          /**
           * @dev This abstract contract provides getters and event emitting update functions for
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
           *
           * _Available since v4.1._
           */
          abstract contract ERC1967Upgrade is IERC1967 {
              // 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 Returns the current implementation address.
               */
              function _getImplementation() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
              }
              /**
               * @dev Stores a new address in the EIP1967 implementation slot.
               */
              function _setImplementation(address newImplementation) private {
                  require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                  StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
              }
              /**
               * @dev Perform implementation upgrade
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeTo(address newImplementation) internal {
                  _setImplementation(newImplementation);
                  emit Upgraded(newImplementation);
              }
              /**
               * @dev Perform implementation upgrade with additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                  _upgradeTo(newImplementation);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(newImplementation, data);
                  }
              }
              /**
               * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
                  // Upgrades from old implementations will perform a rollback test. This test requires the new
                  // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
                  // this special case will break upgrade paths from old UUPS implementation to new ones.
                  if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
                      _setImplementation(newImplementation);
                  } else {
                      try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                          require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
                      } catch {
                          revert("ERC1967Upgrade: new implementation is not UUPS");
                      }
                      _upgradeToAndCall(newImplementation, data, forceCall);
                  }
              }
              /**
               * @dev Storage slot with the admin of the contract.
               * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
              /**
               * @dev 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 Returns the current beacon.
               */
              function _getBeacon() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
              }
              /**
               * @dev Stores a new beacon in the EIP1967 beacon slot.
               */
              function _setBeacon(address newBeacon) private {
                  require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                  require(
                      Address.isContract(IBeacon(newBeacon).implementation()),
                      "ERC1967: beacon implementation is not a contract"
                  );
                  StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
              }
              /**
               * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
               * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
               *
               * Emits a {BeaconUpgraded} event.
               */
              function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                  _setBeacon(newBeacon);
                  emit BeaconUpgraded(newBeacon);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This is the interface that {BeaconProxy} expects of its beacon.
           */
          interface IBeacon {
              /**
               * @dev Must return an address that can be used as a delegate call target.
               *
               * {BeaconProxy} will check that this address is a contract.
               */
              function implementation() external view returns (address);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
           *
           * _Available since v4.8.3._
           */
          interface IERC1967 {
              /**
               * @dev Emitted when the implementation is upgraded.
               */
              event Upgraded(address indexed implementation);
              /**
               * @dev Emitted when the admin account has changed.
               */
              event AdminChanged(address previousAdmin, address newAdmin);
              /**
               * @dev Emitted when the beacon is changed.
               */
              event BeaconUpgraded(address indexed beacon);
          }
          // 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 IERC1822Proxiable {
              /**
               * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
               * address.
               *
               * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
               * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
               * function revert if invoked through a proxy.
               */
              function proxiableUUID() external view returns (bytes32);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
          // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for reading and writing primitive types to specific storage slots.
           *
           * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
           * This library helps with reading and writing to such slots without the need for inline assembly.
           *
           * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
           *
           * Example usage to set ERC1967 implementation slot:
           * ```solidity
           * contract ERC1967 {
           *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
           *
           *     function _getImplementation() internal view returns (address) {
           *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
           *     }
           *
           *     function _setImplementation(address newImplementation) internal {
           *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
           *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
           *     }
           * }
           * ```
           *
           * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
           * _Available since v4.9 for `string`, `bytes`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
              struct BooleanSlot {
                  bool value;
              }
              struct Bytes32Slot {
                  bytes32 value;
              }
              struct Uint256Slot {
                  uint256 value;
              }
              struct StringSlot {
                  string value;
              }
              struct BytesSlot {
                  bytes value;
              }
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
               */
              function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
               */
              function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
               */
              function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` with member `value` located at `slot`.
               */
              function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
               */
              function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` with member `value` located at `slot`.
               */
              function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
               */
              function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
          }
          

          File 4 of 4: ScrollChain
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby disabling any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                  _transferOwnership(newOwner);
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Internal function without access restriction.
               */
              function _transferOwnership(address newOwner) internal virtual {
                  address oldOwner = _owner;
                  _owner = newOwner;
                  emit OwnershipTransferred(oldOwner, newOwner);
              }
              /**
               * @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.9.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]
           * ```solidity
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           *
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
               * constructor.
               *
               * Emits an {Initialized} event.
               */
              modifier initializer() {
                  bool isTopLevelCall = !_initializing;
                  require(
                      (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                      "Initializable: contract is already initialized"
                  );
                  _initialized = 1;
                  if (isTopLevelCall) {
                      _initializing = true;
                  }
                  _;
                  if (isTopLevelCall) {
                      _initializing = false;
                      emit Initialized(1);
                  }
              }
              /**
               * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
               * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
               * used to initialize parent contracts.
               *
               * A reinitializer may be used after the original initialization step. This is essential to configure modules that
               * are added through upgrades and that require initialization.
               *
               * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
               * cannot be nested. If one is invoked in the context of another, execution will revert.
               *
               * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
               * a contract, executing them in the right order is up to the developer or operator.
               *
               * WARNING: setting the version to 255 will prevent any future reinitialization.
               *
               * Emits an {Initialized} event.
               */
              modifier reinitializer(uint8 version) {
                  require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                  _initialized = version;
                  _initializing = true;
                  _;
                  _initializing = false;
                  emit Initialized(version);
              }
              /**
               * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
               * {initializer} and {reinitializer} modifiers, directly or indirectly.
               */
              modifier onlyInitializing() {
                  require(_initializing, "Initializable: contract is not initializing");
                  _;
              }
              /**
               * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
               * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
               * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
               * through proxies.
               *
               * Emits an {Initialized} event the first time it is successfully executed.
               */
              function _disableInitializers() internal virtual {
                  require(!_initializing, "Initializable: contract is initializing");
                  if (_initialized != type(uint8).max) {
                      _initialized = type(uint8).max;
                      emit Initialized(type(uint8).max);
                  }
              }
              /**
               * @dev Returns the highest version that has been initialized. See {reinitializer}.
               */
              function _getInitializedVersion() internal view returns (uint8) {
                  return _initialized;
              }
              /**
               * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
               */
              function _isInitializing() internal view returns (bool) {
                  return _initializing;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
          pragma solidity ^0.8.0;
          import "../utils/ContextUpgradeable.sol";
          import "../proxy/utils/Initializable.sol";
          /**
           * @dev Contract module which allows children to implement an emergency stop
           * mechanism that can be triggered by an authorized account.
           *
           * This module is used through inheritance. It will make available the
           * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
           * the functions of your contract. Note that they will not be pausable by
           * simply including this module, only once the modifiers are put in place.
           */
          abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
              /**
               * @dev Emitted when the pause is triggered by `account`.
               */
              event Paused(address account);
              /**
               * @dev Emitted when the pause is lifted by `account`.
               */
              event Unpaused(address account);
              bool private _paused;
              /**
               * @dev Initializes the contract in unpaused state.
               */
              function __Pausable_init() internal onlyInitializing {
                  __Pausable_init_unchained();
              }
              function __Pausable_init_unchained() internal onlyInitializing {
                  _paused = false;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is not paused.
               *
               * Requirements:
               *
               * - The contract must not be paused.
               */
              modifier whenNotPaused() {
                  _requireNotPaused();
                  _;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is paused.
               *
               * Requirements:
               *
               * - The contract must be paused.
               */
              modifier whenPaused() {
                  _requirePaused();
                  _;
              }
              /**
               * @dev Returns true if the contract is paused, and false otherwise.
               */
              function paused() public view virtual returns (bool) {
                  return _paused;
              }
              /**
               * @dev Throws if the contract is paused.
               */
              function _requireNotPaused() internal view virtual {
                  require(!paused(), "Pausable: paused");
              }
              /**
               * @dev Throws if the contract is not paused.
               */
              function _requirePaused() internal view virtual {
                  require(paused(), "Pausable: not paused");
              }
              /**
               * @dev Triggers stopped state.
               *
               * Requirements:
               *
               * - The contract must not be paused.
               */
              function _pause() internal virtual whenNotPaused {
                  _paused = true;
                  emit Paused(_msgSender());
              }
              /**
               * @dev Returns to normal state.
               *
               * Requirements:
               *
               * - The contract must be paused.
               */
              function _unpause() internal virtual whenPaused {
                  _paused = false;
                  emit Unpaused(_msgSender());
              }
              /**
               * @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.9.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
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts 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
          pragma solidity ^0.8.24;
          interface IL1MessageQueueV1 {
              /**********
               * Events *
               **********/
              /// @notice Emitted when a new L1 => L2 transaction is appended to the queue.
              /// @param sender The address of account who initiates the transaction.
              /// @param target The address of account who will receive the transaction.
              /// @param value The value passed with the transaction.
              /// @param queueIndex The index of this transaction in the queue.
              /// @param gasLimit Gas limit required to complete the message relay on L2.
              /// @param data The calldata of the transaction.
              event QueueTransaction(
                  address indexed sender,
                  address indexed target,
                  uint256 value,
                  uint64 queueIndex,
                  uint256 gasLimit,
                  bytes data
              );
              /// @notice Emitted when some L1 => L2 transactions are included in L1.
              /// @param startIndex The start index of messages popped.
              /// @param count The number of messages popped.
              /// @param skippedBitmap A bitmap indicates whether a message is skipped.
              event DequeueTransaction(uint256 startIndex, uint256 count, uint256 skippedBitmap);
              /// @notice Emitted when dequeued transactions are reset.
              /// @param startIndex The start index of messages.
              event ResetDequeuedTransaction(uint256 startIndex);
              /// @notice Emitted when some L1 => L2 transactions are finalized in L1.
              /// @param finalizedIndex The last index of messages finalized.
              event FinalizedDequeuedTransaction(uint256 finalizedIndex);
              /// @notice Emitted when a message is dropped from L1.
              /// @param index The index of message dropped.
              event DropTransaction(uint256 index);
              /// @notice Emitted when owner updates gas oracle contract.
              /// @param _oldGasOracle The address of old gas oracle contract.
              /// @param _newGasOracle The address of new gas oracle contract.
              event UpdateGasOracle(address indexed _oldGasOracle, address indexed _newGasOracle);
              /// @notice Emitted when owner updates max gas limit.
              /// @param _oldMaxGasLimit The old max gas limit.
              /// @param _newMaxGasLimit The new max gas limit.
              event UpdateMaxGasLimit(uint256 _oldMaxGasLimit, uint256 _newMaxGasLimit);
              /**********
               * Errors *
               **********/
              /// @dev Thrown when the given address is `address(0)`.
              error ErrorZeroAddress();
              /*************************
               * Public View Functions *
               *************************/
              /// @notice The start index of all pending inclusion messages.
              function pendingQueueIndex() external view returns (uint256);
              /// @notice The start index of all unfinalized messages.
              /// @dev All messages from `nextUnfinalizedQueueIndex` to `pendingQueueIndex-1` are committed but not finalized.
              function nextUnfinalizedQueueIndex() external view returns (uint256);
              /// @notice Return the index of next appended message.
              /// @dev Also the total number of appended messages.
              function nextCrossDomainMessageIndex() external view returns (uint256);
              /// @notice Return the message of in `queueIndex`.
              /// @param queueIndex The index to query.
              function getCrossDomainMessage(uint256 queueIndex) external view returns (bytes32);
              /// @notice Return the amount of ETH should pay for cross domain message.
              /// @param gasLimit Gas limit required to complete the message relay on L2.
              function estimateCrossDomainMessageFee(uint256 gasLimit) external view returns (uint256);
              /// @notice Return the amount of intrinsic gas fee should pay for cross domain message.
              /// @param _calldata The calldata of L1-initiated transaction.
              function calculateIntrinsicGasFee(bytes calldata _calldata) external view returns (uint256);
              /// @notice Return the hash of a L1 message.
              /// @param sender The address of sender.
              /// @param queueIndex The queue index of this message.
              /// @param value The amount of Ether transfer to target.
              /// @param target The address of target.
              /// @param gasLimit The gas limit provided.
              /// @param data The calldata passed to target address.
              function computeTransactionHash(
                  address sender,
                  uint256 queueIndex,
                  uint256 value,
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external view returns (bytes32);
              /// @notice Return whether the message is skipped.
              /// @param queueIndex The queue index of the message to check.
              function isMessageSkipped(uint256 queueIndex) external view returns (bool);
              /// @notice Return whether the message is dropped.
              /// @param queueIndex The queue index of the message to check.
              function isMessageDropped(uint256 queueIndex) external view returns (bool);
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Append a L1 to L2 message into this contract.
              /// @param target The address of target contract to call in L2.
              /// @param gasLimit The maximum gas should be used for relay this message in L2.
              /// @param data The calldata passed to target contract.
              function appendCrossDomainMessage(
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Append an enforced transaction to this contract.
              /// @dev The address of sender should be an EOA.
              /// @param sender The address of sender who will initiate this transaction in L2.
              /// @param target The address of target contract to call in L2.
              /// @param value The value passed
              /// @param gasLimit The maximum gas should be used for this transaction in L2.
              /// @param data The calldata passed to target contract.
              function appendEnforcedTransaction(
                  address sender,
                  address target,
                  uint256 value,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Pop messages from queue.
              ///
              /// @dev We can pop at most 256 messages each time. And if the message is not skipped,
              ///      the corresponding entry will be cleared.
              ///
              /// @param startIndex The start index to pop.
              /// @param count The number of messages to pop.
              /// @param skippedBitmap A bitmap indicates whether a message is skipped.
              function popCrossDomainMessage(
                  uint256 startIndex,
                  uint256 count,
                  uint256 skippedBitmap
              ) external;
              /// @notice Reset status of popped messages.
              ///
              /// @dev We can only reset unfinalized popped messages.
              ///
              /// @param startIndex The start index to reset.
              function resetPoppedCrossDomainMessage(uint256 startIndex) external;
              /// @notice Finalize status of popped messages.
              /// @param newFinalizedQueueIndexPlusOne The index of message to finalize plus one.
              function finalizePoppedCrossDomainMessage(uint256 newFinalizedQueueIndexPlusOne) external;
              /// @notice Drop a skipped message from the queue.
              function dropCrossDomainMessage(uint256 index) external;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          interface IL1MessageQueueV2 {
              /**********
               * Events *
               **********/
              /// @notice Emitted when a new L1 => L2 transaction is appended to the queue.
              /// @param sender The address of the sender account on L2.
              /// @param target The address of the target account on L2.
              /// @param value The ETH value transferred to the target account on L2.
              /// @param queueIndex The index of this transaction in the message queue.
              /// @param gasLimit The gas limit used on L2.
              /// @param data The calldata passed to the target account on L2.
              event QueueTransaction(
                  address indexed sender,
                  address indexed target,
                  uint256 value,
                  uint64 queueIndex,
                  uint256 gasLimit,
                  bytes data
              );
              /// @notice Emitted when some L1 => L2 transactions are finalized on L1.
              /// @param finalizedIndex The index of the last message finalized.
              event FinalizedDequeuedTransaction(uint256 finalizedIndex);
              /*************************
               * Public View Functions *
               *************************/
              /// @notice Return the start index of all messages in this contract.
              function firstCrossDomainMessageIndex() external view returns (uint256);
              /// @notice Return the start index of all unfinalized messages.
              function nextUnfinalizedQueueIndex() external view returns (uint256);
              /// @notice Return the index to be used for the next message.
              /// @dev Also the total number of appended messages, including messages in `L1MessageQueueV1`.
              function nextCrossDomainMessageIndex() external view returns (uint256);
              /// @notice Return the message rolling hash of `queueIndex`.
              /// @param queueIndex The index to query.
              function getMessageRollingHash(uint256 queueIndex) external view returns (bytes32);
              /// @notice Return the message enqueue timestamp of `queueIndex`.
              /// @param queueIndex The index to query.
              function getMessageEnqueueTimestamp(uint256 queueIndex) external view returns (uint256);
              /// @notice Return the first unfinalized message enqueue timestamp.
              function getFirstUnfinalizedMessageEnqueueTime() external view returns (uint256);
              /// @notice Return the amount of ETH that should be paid for a cross-domain message.
              /// @param gasLimit The gas limit required to complete the message relay on L2.
              function estimateCrossDomainMessageFee(uint256 gasLimit) external view returns (uint256);
              /// @notice Return the estimated base fee on L2.
              function estimateL2BaseFee() external view returns (uint256);
              /// @notice Return the intrinsic gas required by the provided cross-domain message.
              /// @param data The calldata of the cross-domain message.
              function calculateIntrinsicGasFee(bytes calldata data) external view returns (uint256);
              /// @notice Compute the transaction hash of an L1 message.
              /// @param sender The address of the sender account.
              /// @param queueIndex The index of this transaction in the message queue.
              /// @param value The ETH value transferred to the target account.
              /// @param target The address of the target account.
              /// @param gasLimit The gas limit provided.
              /// @param data The calldata passed to the target account.
              function computeTransactionHash(
                  address sender,
                  uint256 queueIndex,
                  uint256 value,
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external view returns (bytes32);
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Append a L1 => L2 cross-domain message to the message queue.
              /// @param target The address of the target account on L2.
              /// @param gasLimit The gas limit used on L2.
              /// @param data The calldata passed to the target account on L2.
              /// @dev This function can only be called by `L1ScrollMessenger`.
              function appendCrossDomainMessage(
                  address target,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Append an enforced transaction to the message queue.
              /// @param sender The address of the sender account on L2.
              /// @param target The address of the target account on L2.
              /// @param value The ETH value transferred to the target account on L2.
              /// @param gasLimit The gas limit used on L2.
              /// @param data The calldata passed to the target account on L2.
              /// @dev This function can only be called by `EnforcedTxGateway`.
              function appendEnforcedTransaction(
                  address sender,
                  address target,
                  uint256 value,
                  uint256 gasLimit,
                  bytes calldata data
              ) external;
              /// @notice Mark cross-domain messages as finalized.
              /// @param nextUnfinalizedQueueIndex The index of the first unfinalized message after this call.
              /// @dev This function can only be called by `ScrollChain`.
              function finalizePoppedCrossDomainMessage(uint256 nextUnfinalizedQueueIndex) external;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          /// @title IScrollChain
          /// @notice The interface for ScrollChain.
          interface IScrollChain {
              /**********
               * Events *
               **********/
              /// @notice Emitted when a new batch is committed.
              /// @param batchIndex The index of the batch.
              /// @param batchHash The hash of the batch.
              event CommitBatch(uint256 indexed batchIndex, bytes32 indexed batchHash);
              /// @notice revert a pending batch.
              /// @param batchIndex The index of the batch.
              /// @param batchHash The hash of the batch
              event RevertBatch(uint256 indexed batchIndex, bytes32 indexed batchHash);
              /// @notice revert a range of batches.
              /// @param startBatchIndex The start batch index of the range (inclusive).
              /// @param finishBatchIndex The finish batch index of the range (inclusive).
              event RevertBatch(uint256 indexed startBatchIndex, uint256 indexed finishBatchIndex);
              /// @notice Emitted when a batch is finalized.
              /// @param batchIndex The index of the batch.
              /// @param batchHash The hash of the batch
              /// @param stateRoot The state root on layer 2 after this batch.
              /// @param withdrawRoot The merkle root on layer2 after this batch.
              event FinalizeBatch(uint256 indexed batchIndex, bytes32 indexed batchHash, bytes32 stateRoot, bytes32 withdrawRoot);
              /// @notice Emitted when owner updates the status of sequencer.
              /// @param account The address of account updated.
              /// @param status The status of the account updated.
              event UpdateSequencer(address indexed account, bool status);
              /// @notice Emitted when owner updates the status of prover.
              /// @param account The address of account updated.
              /// @param status The status of the account updated.
              event UpdateProver(address indexed account, bool status);
              /// @notice Emitted when the value of `maxNumTxInChunk` is updated.
              /// @param oldMaxNumTxInChunk The old value of `maxNumTxInChunk`.
              /// @param newMaxNumTxInChunk The new value of `maxNumTxInChunk`.
              event UpdateMaxNumTxInChunk(uint256 oldMaxNumTxInChunk, uint256 newMaxNumTxInChunk);
              /// @notice Emitted when we enter or exit enforced batch mode.
              /// @param enabled True if we are entering enforced batch mode, false otherwise.
              /// @param lastCommittedBatchIndex The index of the last committed batch.
              event UpdateEnforcedBatchMode(bool enabled, uint256 lastCommittedBatchIndex);
              /*************************
               * Public View Functions *
               *************************/
              /// @return The latest finalized batch index.
              function lastFinalizedBatchIndex() external view returns (uint256);
              /// @param batchIndex The index of the batch.
              /// @return The batch hash of a committed batch.
              function committedBatches(uint256 batchIndex) external view returns (bytes32);
              /// @param batchIndex The index of the batch.
              /// @return The state root of a committed batch.
              function finalizedStateRoots(uint256 batchIndex) external view returns (bytes32);
              /// @param batchIndex The index of the batch.
              /// @return The message root of a committed batch.
              function withdrawRoots(uint256 batchIndex) external view returns (bytes32);
              /// @param batchIndex The index of the batch.
              /// @return Whether the batch is finalized by batch index.
              function isBatchFinalized(uint256 batchIndex) external view returns (bool);
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Commit a batch of transactions on layer 1 with blob data proof.
              ///
              /// @dev Memory layout of `blobDataProof`:
              /// |    z    |    y    | kzg_commitment | kzg_proof |
              /// |---------|---------|----------------|-----------|
              /// | bytes32 | bytes32 |    bytes48     |  bytes48  |
              ///
              /// @param version The version of current batch.
              /// @param parentBatchHeader The header of parent batch.
              /// @param chunks The list of encoded chunks, see the comments of `ChunkCodec`.
              /// @param skippedL1MessageBitmap The bitmap indicates whether each L1 message is skipped or not.
              /// @param blobDataProof The proof for blob data.
              function commitBatchWithBlobProof(
                  uint8 version,
                  bytes calldata parentBatchHeader,
                  bytes[] memory chunks,
                  bytes calldata skippedL1MessageBitmap,
                  bytes calldata blobDataProof
              ) external;
              /// @notice Commit one or more batches after the EuclidV2 upgrade.
              /// @param version The version of the committed batches.
              /// @param parentBatchHash The hash of parent batch.
              /// @param lastBatchHash The hash of the last committed batch after this call.
              /// @dev The batch payload is stored in the blobs.
              function commitBatches(
                  uint8 version,
                  bytes32 parentBatchHash,
                  bytes32 lastBatchHash
              ) external;
              /// @notice Revert pending batches.
              /// @dev one can only revert unfinalized batches.
              /// @param batchHeader The header of the last batch we want to keep.
              function revertBatch(bytes calldata batchHeader) external;
              /// @notice Finalize a list of committed batches (i.e. bundle) on layer 1.
              /// @param batchHeader The header of last batch in current bundle, see the encoding in comments of `commitBatch.
              /// @param postStateRoot The state root after current bundle.
              /// @param withdrawRoot The withdraw trie root after current batch.
              /// @param aggrProof The aggregation proof for current bundle.
              function finalizeBundleWithProof(
                  bytes calldata batchHeader,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bytes calldata aggrProof
              ) external;
              /// @notice Finalize a list of committed batches (i.e. bundle) on layer 1 after the EuclidV2 upgrade.
              /// @param batchHeader The header of the last batch in this bundle.
              /// @param totalL1MessagesPoppedOverall The number of messages processed after this bundle.
              /// @param postStateRoot The state root after this bundle.
              /// @param withdrawRoot The withdraw trie root after this bundle.
              /// @param aggrProof The bundle proof for this bundle.
              /// @dev See `BatchHeaderV7Codec` for the batch header encoding.
              function finalizeBundlePostEuclidV2(
                  bytes calldata batchHeader,
                  uint256 totalL1MessagesPoppedOverall,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bytes calldata aggrProof
              ) external;
              /// @notice The struct for permissionless batch finalization.
              /// @param batchHeader The header of this batch.
              /// @param totalL1MessagesPoppedOverall The number of messages processed after this bundle.
              /// @param postStateRoot The state root after this batch.
              /// @param withdrawRoot The withdraw trie root after this batch.
              /// @param zkProof The bundle proof for this batch (single-batch bundle).
              /// @dev See `BatchHeaderV7Codec` for the batch header encoding.
              struct FinalizeStruct {
                  bytes batchHeader;
                  uint256 totalL1MessagesPoppedOverall;
                  bytes32 postStateRoot;
                  bytes32 withdrawRoot;
                  bytes zkProof;
              }
              /// @notice Commit and finalize a batch in permissionless mode.
              /// @param version The version of current batch.
              /// @param parentBatchHash The hash of parent batch.
              /// @param finalizeStruct The data needed to finalize this batch.
              /// @dev The batch payload is stored in the blob.
              function commitAndFinalizeBatch(
                  uint8 version,
                  bytes32 parentBatchHash,
                  FinalizeStruct calldata finalizeStruct
              ) external;
          }
          // SPDX-License-Identifier: MIT
          pragma solidity =0.8.24;
          import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
          import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
          import {IL1MessageQueueV1} from "./IL1MessageQueueV1.sol";
          import {IL1MessageQueueV2} from "./IL1MessageQueueV2.sol";
          import {IScrollChain} from "./IScrollChain.sol";
          import {BatchHeaderV0Codec} from "../../libraries/codec/BatchHeaderV0Codec.sol";
          import {BatchHeaderV1Codec} from "../../libraries/codec/BatchHeaderV1Codec.sol";
          import {BatchHeaderV3Codec} from "../../libraries/codec/BatchHeaderV3Codec.sol";
          import {BatchHeaderV7Codec} from "../../libraries/codec/BatchHeaderV7Codec.sol";
          import {ChunkCodecV0} from "../../libraries/codec/ChunkCodecV0.sol";
          import {ChunkCodecV1} from "../../libraries/codec/ChunkCodecV1.sol";
          import {IRollupVerifier} from "../../libraries/verifier/IRollupVerifier.sol";
          import {SystemConfig} from "../system-contract/SystemConfig.sol";
          // solhint-disable no-inline-assembly
          // solhint-disable reason-string
          /// @title ScrollChain
          /// @notice This contract maintains data for the Scroll rollup.
          contract ScrollChain is OwnableUpgradeable, PausableUpgradeable, IScrollChain {
              /**********
               * Errors *
               **********/
              /// @dev Thrown when the given account is not EOA account.
              error ErrorAccountIsNotEOA();
              /// @dev Thrown when committing a committed batch.
              error ErrorBatchIsAlreadyCommitted();
              /// @dev Thrown when finalizing a verified batch.
              error ErrorBatchIsAlreadyVerified();
              /// @dev Thrown when committing empty batch (batch without chunks)
              error ErrorBatchIsEmpty();
              /// @dev Thrown when call precompile failed.
              error ErrorCallPointEvaluationPrecompileFailed();
              /// @dev Thrown when the caller is not prover.
              error ErrorCallerIsNotProver();
              /// @dev Thrown when the caller is not sequencer.
              error ErrorCallerIsNotSequencer();
              /// @dev Thrown when the transaction has multiple blobs.
              error ErrorFoundMultipleBlobs();
              /// @dev Thrown when some fields are not zero in genesis batch.
              error ErrorGenesisBatchHasNonZeroField();
              /// @dev Thrown when importing genesis batch twice.
              error ErrorGenesisBatchImported();
              /// @dev Thrown when data hash in genesis batch is zero.
              error ErrorGenesisDataHashIsZero();
              /// @dev Thrown when the parent batch hash in genesis batch is zero.
              error ErrorGenesisParentBatchHashIsNonZero();
              /// @dev Thrown when the batch hash is incorrect.
              error ErrorIncorrectBatchHash();
              /// @dev Thrown when the batch version is incorrect.
              error ErrorIncorrectBatchVersion();
              /// @dev Thrown when the bitmap length is incorrect.
              error ErrorIncorrectBitmapLength();
              /// @dev Thrown when the last message is skipped.
              error ErrorLastL1MessageSkipped();
              /// @dev Thrown when no blob found in the transaction.
              error ErrorNoBlobFound();
              /// @dev Thrown when the number of transactions is less than number of L1 message in one block.
              error ErrorNumTxsLessThanNumL1Msgs();
              /// @dev Thrown when reverting a finalized batch.
              error ErrorRevertFinalizedBatch();
              /// @dev Thrown when the given state root is zero.
              error ErrorStateRootIsZero();
              /// @dev Thrown when a chunk contains too many transactions.
              error ErrorTooManyTxsInOneChunk();
              /// @dev Thrown when the precompile output is incorrect.
              error ErrorUnexpectedPointEvaluationPrecompileOutput();
              /// @dev Thrown when the given address is `address(0)`.
              error ErrorZeroAddress();
              /// @dev Thrown when commit batch with lower version.
              error ErrorCannotDowngradeVersion();
              /// @dev Thrown when we try to commit or finalize normal batch in enforced batch mode.
              error ErrorInEnforcedBatchMode();
              /// @dev Thrown when we try to commit enforced batch while not in enforced batch mode.
              error ErrorNotInEnforcedBatchMode();
              /// @dev Thrown when commit old batch after Euclid fork is enabled.
              error ErrorEuclidForkEnabled();
              /// @dev Thrown when the committed v5 batch doesn't contain only one chunk.
              error ErrorV5BatchNotContainsOnlyOneChunk();
              /// @dev Thrown when the committed v5 batch doesn't contain only one block.
              error ErrorV5BatchNotContainsOnlyOneBlock();
              /// @dev Thrown when the committed v5 batch contains some transactions (L1 or L2).
              error ErrorV5BatchContainsTransactions();
              /// @dev Thrown when finalize v4/v5, v5/v6, v4/v5/v6 batches in the same bundle.
              error ErrorFinalizePreAndPostEuclidBatchInOneBundle();
              /// @dev Thrown when finalize v7 batches while some v1 messages still unfinalized.
              error ErrorNotAllV1MessagesAreFinalized();
              /// @dev Thrown when the committed batch hash doesn't match off-chain computed one.
              error InconsistentBatchHash(uint256 batchIndex, bytes32 expected, bytes32 actual);
              /// @dev Thrown when given batch is not committed before.
              error ErrorBatchNotCommitted();
              /*************
               * Constants *
               *************/
              /// @dev Address of the point evaluation precompile used for EIP-4844 blob verification.
              address internal constant POINT_EVALUATION_PRECOMPILE_ADDR = address(0x0A);
              /// @dev BLS Modulus value defined in EIP-4844 and the magic value returned from a successful call to the
              /// point evaluation precompile
              uint256 internal constant BLS_MODULUS =
                  52435875175126190479447740508185965837690552500527637822603658699938581184513;
              /// @dev offsets in miscData.flags
              uint256 private constant V1_MESSAGES_FINALIZED_OFFSET = 0;
              uint256 private constant ENFORCED_MODE_OFFSET = 1;
              /// @notice The chain id of the corresponding layer 2 chain.
              uint64 public immutable layer2ChainId;
              /// @notice The address of `L1MessageQueueV1`.
              address public immutable messageQueueV1;
              /// @notice The address of `L1MessageQueueV2`.
              address public immutable messageQueueV2;
              /// @notice The address of `MultipleVersionRollupVerifier`.
              address public immutable verifier;
              /// @notice The address of `SystemConfig`.
              address public immutable systemConfig;
              /***********
               * Structs *
               ***********/
              /// @param lastCommittedBatchIndex The index of the last committed batch.
              /// @param lastFinalizedBatchIndex The index of the last finalized batch.
              /// @param lastFinalizeTimestamp The timestamp of the last finalize transaction.
              /// @param flags Various flags for saving gas. It has 8 bits.
              ///        + bit 0 indicates whether all v1 messages are finalized, 1 means finalized and 0 means not.
              ///        + bit 1 indicates whether the enforced batch mode is enabled, 1 means enabled and 0 means disabled.
              /// @dev We use `32` bits for the timestamp, which works until `Feb 07 2106 06:28:15 GMT+0000`.
              struct ScrollChainMiscData {
                  uint64 lastCommittedBatchIndex;
                  uint64 lastFinalizedBatchIndex;
                  uint32 lastFinalizeTimestamp;
                  uint8 flags;
                  uint88 reserved;
              }
              /*************
               * Variables *
               *************/
              /// @notice The maximum number of transactions allowed in each chunk.
              uint256 public maxNumTxInChunk;
              /// @dev The storage slot used as L1MessageQueue contract, which is deprecated now.
              address private __messageQueue;
              /// @dev The storage slot used as RollupVerifier contract, which is deprecated now.
              address private __verifier;
              /// @notice Whether an account is a sequencer.
              mapping(address => bool) public isSequencer;
              /// @notice Whether an account is a prover.
              mapping(address => bool) public isProver;
              /// @dev The storage slot used as `lastFinalizedBatchIndex`, which is deprecated now.
              uint256 private __lastFinalizedBatchIndex;
              /// @inheritdoc IScrollChain
              /// @dev Starting from EuclidV2, this array is sparse: it only contains
              /// the last batch hash per commit transaction, and not intermediate ones.
              mapping(uint256 => bytes32) public override committedBatches;
              /// @inheritdoc IScrollChain
              /// @dev Starting from Darwin, this array is sparse: it only contains
              /// the last state root per finalized bundle, and not intermediate ones.
              mapping(uint256 => bytes32) public override finalizedStateRoots;
              /// @inheritdoc IScrollChain
              /// @dev Starting from Darwin, this array is sparse: it only contains
              /// the last withdraw root per finalized bundle, and not intermediate ones.
              mapping(uint256 => bytes32) public override withdrawRoots;
              /// @notice The index of first Euclid batch.
              uint256 public initialEuclidBatchIndex;
              ScrollChainMiscData public miscData;
              /**********************
               * Function Modifiers *
               **********************/
              modifier OnlySequencer() {
                  // @note In the decentralized mode, it should be only called by a list of validator.
                  if (!isSequencer[_msgSender()]) revert ErrorCallerIsNotSequencer();
                  _;
              }
              modifier OnlyProver() {
                  if (!isProver[_msgSender()]) revert ErrorCallerIsNotProver();
                  _;
              }
              modifier whenEnforcedBatchNotEnabled() {
                  if (isEnforcedModeEnabled()) revert ErrorInEnforcedBatchMode();
                  _;
              }
              /***************
               * Constructor *
               ***************/
              /// @notice Constructor for `ScrollChain` implementation contract.
              ///
              /// @param _chainId The chain id of L2.
              /// @param _messageQueueV1 The address of `L1MessageQueueV1`.
              /// @param _messageQueueV2 The address of `L1MessageQueueV2`.
              /// @param _verifier The address of `MultipleVersionRollupVerifier`.
              /// @param _systemConfig The address of `SystemConfig`.
              constructor(
                  uint64 _chainId,
                  address _messageQueueV1,
                  address _messageQueueV2,
                  address _verifier,
                  address _systemConfig
              ) {
                  if (
                      _messageQueueV1 == address(0) ||
                      _messageQueueV2 == address(0) ||
                      _verifier == address(0) ||
                      _systemConfig == address(0)
                  ) {
                      revert ErrorZeroAddress();
                  }
                  _disableInitializers();
                  layer2ChainId = _chainId;
                  messageQueueV1 = _messageQueueV1;
                  messageQueueV2 = _messageQueueV2;
                  verifier = _verifier;
                  systemConfig = _systemConfig;
              }
              /// @notice Initialize the storage of ScrollChain.
              ///
              /// @dev The parameters `_messageQueue` and `_verifier` are no longer used.
              ///
              /// @param _messageQueue The address of `L1MessageQueue` contract.
              /// @param _verifier The address of zkevm verifier contract.
              /// @param _maxNumTxInChunk The maximum number of transactions allowed in each chunk.
              function initialize(
                  address _messageQueue,
                  address _verifier,
                  uint256 _maxNumTxInChunk
              ) external initializer {
                  OwnableUpgradeable.__Ownable_init();
                  maxNumTxInChunk = _maxNumTxInChunk;
                  __verifier = _verifier;
                  __messageQueue = _messageQueue;
                  emit UpdateMaxNumTxInChunk(0, _maxNumTxInChunk);
              }
              function initializeV2() external reinitializer(2) {
                  // binary search on lastCommittedBatchIndex
                  uint256 index = __lastFinalizedBatchIndex;
                  uint256 step = 1;
                  unchecked {
                      while (committedBatches[index + step] != bytes32(0)) {
                          step <<= 1;
                      }
                      step >>= 1;
                      while (step > 0) {
                          if (committedBatches[index + step] != bytes32(0)) {
                              index += step;
                          }
                          step >>= 1;
                      }
                  }
                  miscData = ScrollChainMiscData({
                      lastCommittedBatchIndex: uint64(index),
                      lastFinalizedBatchIndex: uint64(__lastFinalizedBatchIndex),
                      lastFinalizeTimestamp: uint32(block.timestamp),
                      flags: 0,
                      reserved: 0
                  });
              }
              /*************************
               * Public View Functions *
               *************************/
              /// @inheritdoc IScrollChain
              function isBatchFinalized(uint256 _batchIndex) external view override returns (bool) {
                  return _batchIndex <= miscData.lastFinalizedBatchIndex;
              }
              /// @inheritdoc IScrollChain
              function lastFinalizedBatchIndex() external view returns (uint256) {
                  return miscData.lastFinalizedBatchIndex;
              }
              /// @notice Return whether we are in enforced batch mode.
              function isEnforcedModeEnabled() public view returns (bool) {
                  return _decodeBoolFromFlag(miscData.flags, ENFORCED_MODE_OFFSET);
              }
              /*****************************
               * Public Mutating Functions *
               *****************************/
              /// @notice Import layer 2 genesis block
              /// @param _batchHeader The header of the genesis batch.
              /// @param _stateRoot The state root of the genesis block.
              function importGenesisBatch(bytes calldata _batchHeader, bytes32 _stateRoot) external {
                  // check genesis batch header length
                  if (_stateRoot == bytes32(0)) revert ErrorStateRootIsZero();
                  // check whether the genesis batch is imported
                  if (finalizedStateRoots[0] != bytes32(0)) revert ErrorGenesisBatchImported();
                  (uint256 memPtr, bytes32 _batchHash, , ) = _loadBatchHeader(_batchHeader, 0);
                  // check all fields except `dataHash` and `lastBlockHash` are zero
                  unchecked {
                      uint256 sum = BatchHeaderV0Codec.getVersion(memPtr) +
                          BatchHeaderV0Codec.getBatchIndex(memPtr) +
                          BatchHeaderV0Codec.getL1MessagePopped(memPtr) +
                          BatchHeaderV0Codec.getTotalL1MessagePopped(memPtr);
                      if (sum != 0) revert ErrorGenesisBatchHasNonZeroField();
                  }
                  if (BatchHeaderV0Codec.getDataHash(memPtr) == bytes32(0)) revert ErrorGenesisDataHashIsZero();
                  if (BatchHeaderV0Codec.getParentBatchHash(memPtr) != bytes32(0)) revert ErrorGenesisParentBatchHashIsNonZero();
                  committedBatches[0] = _batchHash;
                  finalizedStateRoots[0] = _stateRoot;
                  emit CommitBatch(0, _batchHash);
                  emit FinalizeBatch(0, _batchHash, _stateRoot, bytes32(0));
              }
              /// @inheritdoc IScrollChain
              ///
              /// @dev This function will revert unless all V0/V1/V2 batches are finalized. This is because we start to
              /// pop L1 messages in `commitBatchWithBlobProof` but not in `commitBatch`. We also introduce `finalizedQueueIndex`
              /// in `L1MessageQueue`. If one of V0/V1/V2 batches not finalized, `L1MessageQueue.pendingQueueIndex` will not
              /// match `parentBatchHeader.totalL1MessagePopped` and thus revert.
              ///
              /// @dev This function now only accept batches with 4 <= version <= 6. And for `_version=5`, we should make sure this
              /// batch contains only one empty block, since it is the Euclid initial batch for zkt/mpt transition.
              function commitBatchWithBlobProof(
                  uint8 _version,
                  bytes calldata _parentBatchHeader,
                  bytes[] memory _chunks,
                  bytes calldata _skippedL1MessageBitmap,
                  bytes calldata _blobDataProof
              ) external override OnlySequencer whenNotPaused whenEnforcedBatchNotEnabled {
                  // only accept 4 <= version <= 6
                  if (_version < 4) {
                      revert ErrorIncorrectBatchVersion();
                  } else if (_version == 5) {
                      // only commit once for Euclid initial batch
                      if (initialEuclidBatchIndex != 0) revert ErrorBatchIsAlreadyCommitted();
                  } else if (_version > 6) {
                      revert ErrorIncorrectBatchVersion();
                  }
                  // @note We suppose to check v6 batches cannot be committed without initial Euclid Batch.
                  // However it will introduce extra sload (2000 gas), we let the sequencer to do this check offchain.
                  // Even if the sequencer commits v6 batches without v5 batch, the security council can still revert it.
                  uint256 batchIndex = _commitBatchFromV2ToV6(
                      _version,
                      _parentBatchHeader,
                      _chunks,
                      _skippedL1MessageBitmap,
                      _blobDataProof
                  );
                  // Don't allow to commit version 4 after Euclid upgrade.
                  // This check is to avoid sequencer committing wrong batch due to human error.
                  // And This check won't introduce much gas overhead (likely less than 100).
                  if (_version == 4) {
                      uint256 euclidForkBatchIndex = initialEuclidBatchIndex;
                      if (euclidForkBatchIndex > 0 && batchIndex > euclidForkBatchIndex) revert ErrorEuclidForkEnabled();
                  } else if (_version == 5) {
                      initialEuclidBatchIndex = batchIndex;
                  }
              }
              /// @inheritdoc IScrollChain
              function commitBatches(
                  uint8 version,
                  bytes32 parentBatchHash,
                  bytes32 lastBatchHash
              ) external override OnlySequencer whenNotPaused whenEnforcedBatchNotEnabled {
                  _commitBatchesFromV7(version, parentBatchHash, lastBatchHash, false);
              }
              /// @inheritdoc IScrollChain
              /// @dev This function cannot revert V6 and V7 batches at the same time, so we will assume all batches are V7.
              /// If we need to revert V6 batches, we can downgrade the contract to the previous version and call this function.
              /// @dev During commit batch we only store the last batch hash into storage. As a result, we cannot revert intermediate batches.
              function revertBatch(bytes calldata batchHeader) external onlyOwner {
                  uint256 lastBatchIndex = miscData.lastCommittedBatchIndex;
                  (uint256 batchPtr, , uint256 startBatchIndex, ) = _loadBatchHeader(batchHeader, lastBatchIndex);
                  // only revert v7 batches
                  if (BatchHeaderV0Codec.getVersion(batchPtr) < 7) revert ErrorIncorrectBatchVersion();
                  // check finalization
                  if (startBatchIndex < miscData.lastFinalizedBatchIndex) revert ErrorRevertFinalizedBatch();
                  // actual revert
                  for (uint256 i = lastBatchIndex; i > startBatchIndex; --i) {
                      bytes32 hash = committedBatches[i];
                      if (hash != bytes32(0)) delete committedBatches[i];
                  }
                  emit RevertBatch(startBatchIndex + 1, lastBatchIndex);
                  // update `lastCommittedBatchIndex`
                  miscData.lastCommittedBatchIndex = uint64(startBatchIndex);
              }
              /// @inheritdoc IScrollChain
              /// @dev All batches in the given bundle should have the same version and version <= 4 or version >= 6.
              function finalizeBundleWithProof(
                  bytes calldata batchHeader,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bytes calldata aggrProof
              ) external override OnlyProver whenNotPaused whenEnforcedBatchNotEnabled {
                  // actions before verification
                  (
                      uint256 version,
                      bytes32 batchHash,
                      uint256 batchIndex,
                      uint256 totalL1MessagesPoppedOverall,
                      uint256 prevBatchIndex
                  ) = _beforeFinalizeBatch(batchHeader, postStateRoot);
                  uint256 euclidForkBatchIndex = initialEuclidBatchIndex;
                  // Make sure we don't finalize v4, v5 and v6 batches in the same bundle, that
                  // means `batchIndex < euclidForkBatchIndex` or `prevBatchIndex >= euclidForkBatchIndex`.
                  if (prevBatchIndex < euclidForkBatchIndex && euclidForkBatchIndex <= batchIndex) {
                      revert ErrorFinalizePreAndPostEuclidBatchInOneBundle();
                  }
                  bytes memory publicInputs = abi.encodePacked(
                      layer2ChainId,
                      uint32(batchIndex - prevBatchIndex), // numBatches
                      finalizedStateRoots[prevBatchIndex], // _prevStateRoot
                      committedBatches[prevBatchIndex], // _prevBatchHash
                      postStateRoot,
                      batchHash,
                      withdrawRoot
                  );
                  // verify bundle, choose the correct verifier based on the last batch
                  // our off-chain service will make sure all unfinalized batches have the same batch version.
                  IRollupVerifier(verifier).verifyBundleProof(version, batchIndex, aggrProof, publicInputs);
                  // actions after verification
                  _afterFinalizeBatch(batchIndex, batchHash, totalL1MessagesPoppedOverall, postStateRoot, withdrawRoot, true);
              }
              /// @inheritdoc IScrollChain
              function finalizeBundlePostEuclidV2(
                  bytes calldata batchHeader,
                  uint256 totalL1MessagesPoppedOverall,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bytes calldata aggrProof
              ) external override OnlyProver whenNotPaused whenEnforcedBatchNotEnabled {
                  uint256 flags = miscData.flags;
                  bool isV1MessageFinalized = _decodeBoolFromFlag(flags, V1_MESSAGES_FINALIZED_OFFSET);
                  if (!isV1MessageFinalized) {
                      if (
                          IL1MessageQueueV1(messageQueueV1).nextUnfinalizedQueueIndex() !=
                          IL1MessageQueueV2(messageQueueV2).firstCrossDomainMessageIndex()
                      ) {
                          revert ErrorNotAllV1MessagesAreFinalized();
                      }
                      miscData.flags = uint8(_insertBoolToFlag(flags, V1_MESSAGES_FINALIZED_OFFSET, true));
                  }
                  _finalizeBundlePostEuclidV2(batchHeader, totalL1MessagesPoppedOverall, postStateRoot, withdrawRoot, aggrProof);
              }
              /// @inheritdoc IScrollChain
              /// @dev We only consider batch version >= 7 here.
              function commitAndFinalizeBatch(
                  uint8 version,
                  bytes32 parentBatchHash,
                  FinalizeStruct calldata finalizeStruct
              ) external {
                  ScrollChainMiscData memory cachedMiscData = miscData;
                  if (!isEnforcedModeEnabled()) {
                      (uint256 maxDelayEnterEnforcedMode, uint256 maxDelayMessageQueue) = SystemConfig(systemConfig)
                          .enforcedBatchParameters();
                      uint256 firstUnfinalizedMessageTime = IL1MessageQueueV2(messageQueueV2)
                          .getFirstUnfinalizedMessageEnqueueTime();
                      if (
                          firstUnfinalizedMessageTime + maxDelayMessageQueue < block.timestamp ||
                          cachedMiscData.lastFinalizeTimestamp + maxDelayEnterEnforcedMode < block.timestamp
                      ) {
                          if (cachedMiscData.lastFinalizedBatchIndex < cachedMiscData.lastCommittedBatchIndex) {
                              // be careful with the gas costs, maybe should call revertBatch first.
                              for (
                                  uint256 i = cachedMiscData.lastCommittedBatchIndex;
                                  i > cachedMiscData.lastFinalizedBatchIndex;
                                  --i
                              ) {
                                  bytes32 hash = committedBatches[i];
                                  if (hash != bytes32(0)) delete committedBatches[i];
                              }
                              emit RevertBatch(
                                  cachedMiscData.lastFinalizedBatchIndex + 1,
                                  cachedMiscData.lastCommittedBatchIndex
                              );
                          }
                          // explicitly enable enforced batch mode
                          cachedMiscData.flags = uint8(_insertBoolToFlag(cachedMiscData.flags, ENFORCED_MODE_OFFSET, true));
                          // reset `lastCommittedBatchIndex`
                          cachedMiscData.lastCommittedBatchIndex = uint64(cachedMiscData.lastFinalizedBatchIndex);
                          miscData = cachedMiscData;
                          emit UpdateEnforcedBatchMode(true, cachedMiscData.lastCommittedBatchIndex);
                      } else {
                          revert ErrorNotInEnforcedBatchMode();
                      }
                  }
                  bytes32 batchHash = keccak256(finalizeStruct.batchHeader);
                  _commitBatchesFromV7(version, parentBatchHash, batchHash, true);
                  // finalize with zk proof
                  _finalizeBundlePostEuclidV2(
                      finalizeStruct.batchHeader,
                      finalizeStruct.totalL1MessagesPoppedOverall,
                      finalizeStruct.postStateRoot,
                      finalizeStruct.withdrawRoot,
                      finalizeStruct.zkProof
                  );
              }
              /************************
               * Restricted Functions *
               ************************/
              /// @notice Add an account to the sequencer list.
              /// @param _account The address of account to add.
              function addSequencer(address _account) external onlyOwner {
                  // @note Currently many external services rely on EOA sequencer to decode metadata directly from tx.calldata.
                  // So we explicitly make sure the account is EOA.
                  if (_account.code.length > 0) revert ErrorAccountIsNotEOA();
                  isSequencer[_account] = true;
                  emit UpdateSequencer(_account, true);
              }
              /// @notice Remove an account from the sequencer list.
              /// @param _account The address of account to remove.
              function removeSequencer(address _account) external onlyOwner {
                  isSequencer[_account] = false;
                  emit UpdateSequencer(_account, false);
              }
              /// @notice Add an account to the prover list.
              /// @param _account The address of account to add.
              function addProver(address _account) external onlyOwner {
                  // @note Currently many external services rely on EOA prover to decode metadata directly from tx.calldata.
                  // So we explicitly make sure the account is EOA.
                  if (_account.code.length > 0) revert ErrorAccountIsNotEOA();
                  isProver[_account] = true;
                  emit UpdateProver(_account, true);
              }
              /// @notice Add an account from the prover list.
              /// @param _account The address of account to remove.
              function removeProver(address _account) external onlyOwner {
                  isProver[_account] = false;
                  emit UpdateProver(_account, false);
              }
              /// @notice Update the value of `maxNumTxInChunk`.
              /// @param _maxNumTxInChunk The new value of `maxNumTxInChunk`.
              function updateMaxNumTxInChunk(uint256 _maxNumTxInChunk) external onlyOwner {
                  uint256 _oldMaxNumTxInChunk = maxNumTxInChunk;
                  maxNumTxInChunk = _maxNumTxInChunk;
                  emit UpdateMaxNumTxInChunk(_oldMaxNumTxInChunk, _maxNumTxInChunk);
              }
              /// @notice Pause the contract
              /// @param _status The pause status to update.
              function setPause(bool _status) external onlyOwner {
                  if (_status) {
                      _pause();
                  } else {
                      _unpause();
                  }
              }
              /// @notice Exit from enforced batch mode.
              function disableEnforcedBatchMode() external onlyOwner {
                  miscData.flags = uint8(_insertBoolToFlag(miscData.flags, ENFORCED_MODE_OFFSET, false));
                  emit UpdateEnforcedBatchMode(false, miscData.lastCommittedBatchIndex);
              }
              /**********************
               * Internal Functions *
               **********************/
              /// @dev Caller should make sure bit is smaller than 256.
              function _decodeBoolFromFlag(uint256 flag, uint256 bit) internal pure returns (bool) {
                  return (flag >> bit) & 1 == 1;
              }
              /// @dev Caller should make sure bit is smaller than 256.
              function _insertBoolToFlag(
                  uint256 flag,
                  uint256 bit,
                  bool value
              ) internal pure returns (uint256) {
                  flag = flag ^ (flag & (1 << bit)); // reset value at bit
                  if (value) {
                      flag |= (1 << bit);
                  }
                  return flag;
              }
              /// @dev Internal function to do common checks before actual batch committing.
              /// @param _version The version of the batch to commit.
              /// @param _parentBatchHeader The parent batch header in calldata.
              /// @param _chunks The list of chunks in memory.
              /// @param _lastCommittedBatchIndex The index of the last committed batch.
              /// @return _parentBatchHash The batch hash of parent batch header.
              /// @return _batchIndex The index of current batch.
              /// @return _totalL1MessagesPoppedOverall The total number of L1 messages popped before current batch.
              function _beforeCommitBatch(
                  uint8 _version,
                  bytes calldata _parentBatchHeader,
                  bytes[] memory _chunks,
                  uint256 _lastCommittedBatchIndex
              )
                  private
                  view
                  returns (
                      bytes32 _parentBatchHash,
                      uint256 _batchIndex,
                      uint256 _totalL1MessagesPoppedOverall
                  )
              {
                  // check whether the batch is empty
                  if (_chunks.length == 0) revert ErrorBatchIsEmpty();
                  uint256 batchPtr;
                  (batchPtr, _parentBatchHash, _batchIndex, _totalL1MessagesPoppedOverall) = _loadBatchHeader(
                      _parentBatchHeader,
                      _lastCommittedBatchIndex
                  );
                  // version should non-decreasing
                  if (BatchHeaderV0Codec.getVersion(batchPtr) > _version) revert ErrorCannotDowngradeVersion();
                  if (_batchIndex != _lastCommittedBatchIndex) revert ErrorBatchIsAlreadyCommitted();
                  unchecked {
                      _batchIndex += 1;
                  }
              }
              /// @dev Internal function to do common actions after actual batch committing.
              /// @param _batchIndex The index of current batch.
              /// @param _batchHash The hash of current batch.
              function _afterCommitBatch(uint256 _batchIndex, bytes32 _batchHash) private {
                  miscData.lastCommittedBatchIndex = uint64(_batchIndex);
                  committedBatches[_batchIndex] = _batchHash;
                  emit CommitBatch(_batchIndex, _batchHash);
              }
              /// @dev Internal function to do common actions before actual batch finalization.
              function _beforeFinalizeBatch(bytes calldata batchHeader, bytes32 postStateRoot)
                  internal
                  view
                  returns (
                      uint256 version,
                      bytes32 batchHash,
                      uint256 batchIndex,
                      uint256 totalL1MessagesPoppedOverall,
                      uint256 prevBatchIndex
                  )
              {
                  if (postStateRoot == bytes32(0)) revert ErrorStateRootIsZero();
                  ScrollChainMiscData memory cachedMiscData = miscData;
                  uint256 batchPtr;
                  // compute pending batch hash and verify
                  (batchPtr, batchHash, batchIndex, totalL1MessagesPoppedOverall) = _loadBatchHeader(
                      batchHeader,
                      cachedMiscData.lastCommittedBatchIndex
                  );
                  // make sure don't finalize batch multiple times
                  prevBatchIndex = cachedMiscData.lastFinalizedBatchIndex;
                  if (batchIndex <= prevBatchIndex) revert ErrorBatchIsAlreadyVerified();
                  version = BatchHeaderV0Codec.getVersion(batchPtr);
              }
              /// @dev Internal function to do common actions after actual batch finalization.
              function _afterFinalizeBatch(
                  uint256 batchIndex,
                  bytes32 batchHash,
                  uint256 totalL1MessagesPoppedOverall,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bool isV1
              ) internal {
                  ScrollChainMiscData memory cachedMiscData = miscData;
                  cachedMiscData.lastFinalizedBatchIndex = uint64(batchIndex);
                  cachedMiscData.lastFinalizeTimestamp = uint32(block.timestamp);
                  miscData = cachedMiscData;
                  // @note we do not store intermediate finalized roots
                  finalizedStateRoots[batchIndex] = postStateRoot;
                  withdrawRoots[batchIndex] = withdrawRoot;
                  // Pop finalized and non-skipped message from L1MessageQueue.
                  _finalizePoppedL1Messages(totalL1MessagesPoppedOverall, isV1);
                  emit FinalizeBatch(batchIndex, batchHash, postStateRoot, withdrawRoot);
              }
              /// @dev Internal function to check the `SkippedL1MessageBitmap`.
              /// @param _totalL1MessagesPoppedOverall The total number of L1 messages popped after current batch.
              /// @param _totalL1MessagesPoppedInBatch The total number of L1 messages popped in current batch.
              /// @param _skippedL1MessageBitmap The skipped L1 message bitmap in calldata.
              /// @param _doPopMessage Whether we actually pop the messages from message queue.
              function _checkSkippedL1MessageBitmap(
                  uint256 _totalL1MessagesPoppedOverall,
                  uint256 _totalL1MessagesPoppedInBatch,
                  bytes calldata _skippedL1MessageBitmap,
                  bool _doPopMessage
              ) private {
                  // check the length of bitmap
                  unchecked {
                      if (((_totalL1MessagesPoppedInBatch + 255) / 256) * 32 != _skippedL1MessageBitmap.length) {
                          revert ErrorIncorrectBitmapLength();
                      }
                  }
                  if (_doPopMessage) {
                      _popL1MessagesCalldata(
                          _skippedL1MessageBitmap,
                          _totalL1MessagesPoppedOverall,
                          _totalL1MessagesPoppedInBatch
                      );
                  }
              }
              /// @dev Internal function to get and check the blob versioned hash.
              /// @param _blobDataProof The blob data proof passing to point evaluation precompile.
              /// @return _blobVersionedHash The retrieved blob versioned hash.
              function _getAndCheckBlobVersionedHash(bytes calldata _blobDataProof)
                  internal
                  returns (bytes32 _blobVersionedHash)
              {
                  _blobVersionedHash = _getBlobVersionedHash();
                  // Calls the point evaluation precompile and verifies the output
                  (bool success, bytes memory data) = POINT_EVALUATION_PRECOMPILE_ADDR.staticcall(
                      abi.encodePacked(_blobVersionedHash, _blobDataProof)
                  );
                  // We verify that the point evaluation precompile call was successful by testing the latter 32 bytes of the
                  // response is equal to BLS_MODULUS as defined in https://eips.ethereum.org/EIPS/eip-4844#point-evaluation-precompile
                  if (!success) revert ErrorCallPointEvaluationPrecompileFailed();
                  (, uint256 result) = abi.decode(data, (uint256, uint256));
                  if (result != BLS_MODULUS) revert ErrorUnexpectedPointEvaluationPrecompileOutput();
              }
              /// @dev Internal function to get the blob versioned hash.
              /// @return _blobVersionedHash The retrieved blob versioned hash.
              function _getBlobVersionedHash() internal virtual returns (bytes32 _blobVersionedHash) {
                  bytes32 _secondBlob;
                  // Get blob's versioned hash
                  assembly {
                      _blobVersionedHash := blobhash(0)
                      _secondBlob := blobhash(1)
                  }
                  if (_blobVersionedHash == bytes32(0)) revert ErrorNoBlobFound();
                  if (_secondBlob != bytes32(0)) revert ErrorFoundMultipleBlobs();
              }
              /// @dev Internal function to get the blob versioned hash.
              /// @return _blobVersionedHash The retrieved blob versioned hash.
              function _getBlobVersionedHash(uint256 index) internal virtual returns (bytes32 _blobVersionedHash) {
                  // Get blob's versioned hash
                  assembly {
                      _blobVersionedHash := blobhash(index)
                  }
              }
              /// @dev We make sure v5 batch only contains one empty block here.
              function _validateV5Batch(bytes[] memory chunks) internal pure {
                  if (chunks.length != 1) revert ErrorV5BatchNotContainsOnlyOneChunk();
                  bytes memory chunk = chunks[0];
                  uint256 chunkPtr;
                  uint256 blockPtr;
                  assembly {
                      chunkPtr := add(chunk, 0x20) // skip chunkLength
                      blockPtr := add(chunkPtr, 1)
                  }
                  uint256 numBlocks = ChunkCodecV1.validateChunkLength(chunkPtr, chunk.length);
                  if (numBlocks != 1) revert ErrorV5BatchNotContainsOnlyOneBlock();
                  uint256 numTransactions = ChunkCodecV1.getNumTransactions(blockPtr);
                  if (numTransactions != 0) revert ErrorV5BatchContainsTransactions();
              }
              /// @dev Internal function to commit one ore more batches after the EuclidV2 upgrade.
              /// @param version The version of the batches (version >= 7).
              /// @param parentBatchHash The hash of parent batch.
              /// @param lastBatchHash The hash of the last committed batch after this call.
              /// @param onlyOne If true, we will only process the first blob.
              function _commitBatchesFromV7(
                  uint8 version,
                  bytes32 parentBatchHash,
                  bytes32 lastBatchHash,
                  bool onlyOne
              ) internal {
                  if (version < 7) {
                      // only accept version >= 7
                      revert ErrorIncorrectBatchVersion();
                  }
                  uint256 lastCommittedBatchIndex = miscData.lastCommittedBatchIndex;
                  if (parentBatchHash != committedBatches[lastCommittedBatchIndex]) revert ErrorIncorrectBatchHash();
                  for (uint256 i = 0; ; i++) {
                      bytes32 blobVersionedHash = _getBlobVersionedHash(i);
                      if (blobVersionedHash == bytes32(0)) {
                          if (i == 0) revert ErrorBatchIsEmpty();
                          break;
                      }
                      lastCommittedBatchIndex += 1;
                      // see comments in `src/libraries/codec/BatchHeaderV7Codec.sol` for encodings
                      uint256 batchPtr = BatchHeaderV7Codec.allocate();
                      BatchHeaderV0Codec.storeVersion(batchPtr, version);
                      BatchHeaderV0Codec.storeBatchIndex(batchPtr, lastCommittedBatchIndex);
                      BatchHeaderV7Codec.storeParentBatchHash(batchPtr, parentBatchHash);
                      BatchHeaderV7Codec.storeBlobVersionedHash(batchPtr, blobVersionedHash);
                      bytes32 batchHash = BatchHeaderV0Codec.computeBatchHash(
                          batchPtr,
                          BatchHeaderV7Codec.BATCH_HEADER_FIXED_LENGTH
                      );
                      emit CommitBatch(lastCommittedBatchIndex, batchHash);
                      parentBatchHash = batchHash;
                      if (onlyOne) break;
                  }
                  // Make sure that the batch hash matches the one computed by the batch committer off-chain.
                  // This check can fail if:
                  // 1. faulty batch producers commit a wrong batch or the local computation is wrong.
                  // 2. unexpected `parentBatch` in case commit transactions get reordered
                  // 3. two batch producers commit at the same time with the same `parentBatch`.
                  if (parentBatchHash != lastBatchHash) {
                      revert InconsistentBatchHash(lastCommittedBatchIndex, lastBatchHash, parentBatchHash);
                  }
                  // only store last batch hash in storage
                  committedBatches[lastCommittedBatchIndex] = parentBatchHash;
                  miscData.lastCommittedBatchIndex = uint64(lastCommittedBatchIndex);
              }
              /// @dev Internal function to finalize a bundle after the EuclidV2 upgrade.
              /// @param batchHeader The header of the last batch in this bundle.
              /// @param totalL1MessagesPoppedOverall The number of messages processed after this bundle.
              /// @param postStateRoot The state root after this bundle.
              /// @param withdrawRoot The withdraw trie root after this bundle.
              /// @param aggrProof The bundle proof for this bundle.
              function _finalizeBundlePostEuclidV2(
                  bytes calldata batchHeader,
                  uint256 totalL1MessagesPoppedOverall,
                  bytes32 postStateRoot,
                  bytes32 withdrawRoot,
                  bytes calldata aggrProof
              ) internal {
                  // actions before verification
                  (uint256 version, bytes32 batchHash, uint256 batchIndex, , uint256 prevBatchIndex) = _beforeFinalizeBatch(
                      batchHeader,
                      postStateRoot
                  );
                  // L1 message hashes are chained,
                  // this hash commits to the whole queue up to and including `totalL1MessagesPoppedOverall-1`
                  bytes32 messageQueueHash = totalL1MessagesPoppedOverall == 0
                      ? bytes32(0)
                      : IL1MessageQueueV2(messageQueueV2).getMessageRollingHash(totalL1MessagesPoppedOverall - 1);
                  bytes memory publicInputs = abi.encodePacked(
                      layer2ChainId,
                      messageQueueHash,
                      uint32(batchIndex - prevBatchIndex), // numBatches
                      finalizedStateRoots[prevBatchIndex], // _prevStateRoot
                      committedBatches[prevBatchIndex], // _prevBatchHash
                      postStateRoot,
                      batchHash,
                      withdrawRoot
                  );
                  // verify bundle, choose the correct verifier based on the last batch
                  // our off-chain service will make sure all unfinalized batches have the same batch version.
                  IRollupVerifier(verifier).verifyBundleProof(version, batchIndex, aggrProof, publicInputs);
                  // actions after verification
                  _afterFinalizeBatch(batchIndex, batchHash, totalL1MessagesPoppedOverall, postStateRoot, withdrawRoot, false);
              }
              /// @dev Internal function to commit batches from V2 to V6 (except V5, since it is Euclid initial batch)
              function _commitBatchFromV2ToV6(
                  uint8 _version,
                  bytes calldata _parentBatchHeader,
                  bytes[] memory _chunks,
                  bytes calldata _skippedL1MessageBitmap,
                  bytes calldata _blobDataProof
              ) internal returns (uint256) {
                  // do extra checks for batch v5.
                  if (_version == 5) {
                      _validateV5Batch(_chunks);
                  }
                  // allocate memory of batch header and store entries if necessary, the order matters
                  // @note why store entries if necessary, to avoid stack overflow problem.
                  // The codes for `version`, `batchIndex`, `l1MessagePopped`, `totalL1MessagePopped` and `dataHash`
                  // are the same as `BatchHeaderV0Codec`.
                  // The codes for `blobVersionedHash`, and `parentBatchHash` are the same as `BatchHeaderV1Codec`.
                  uint256 batchPtr = BatchHeaderV3Codec.allocate();
                  BatchHeaderV0Codec.storeVersion(batchPtr, _version);
                  (bytes32 _parentBatchHash, uint256 _batchIndex, uint256 _totalL1MessagesPoppedOverall) = _beforeCommitBatch(
                      _version,
                      _parentBatchHeader,
                      _chunks,
                      miscData.lastCommittedBatchIndex
                  );
                  BatchHeaderV0Codec.storeBatchIndex(batchPtr, _batchIndex);
                  // versions 2 to 6 both use ChunkCodecV1
                  (bytes32 _dataHash, uint256 _totalL1MessagesPoppedInBatch) = _commitChunksV1(
                      _totalL1MessagesPoppedOverall,
                      _chunks,
                      _skippedL1MessageBitmap
                  );
                  unchecked {
                      _totalL1MessagesPoppedOverall += _totalL1MessagesPoppedInBatch;
                  }
                  // verify skippedL1MessageBitmap
                  _checkSkippedL1MessageBitmap(
                      _totalL1MessagesPoppedOverall,
                      _totalL1MessagesPoppedInBatch,
                      _skippedL1MessageBitmap,
                      true
                  );
                  BatchHeaderV0Codec.storeL1MessagePopped(batchPtr, _totalL1MessagesPoppedInBatch);
                  BatchHeaderV0Codec.storeTotalL1MessagePopped(batchPtr, _totalL1MessagesPoppedOverall);
                  BatchHeaderV0Codec.storeDataHash(batchPtr, _dataHash);
                  // verify blob versioned hash
                  BatchHeaderV1Codec.storeBlobVersionedHash(batchPtr, _getAndCheckBlobVersionedHash(_blobDataProof));
                  BatchHeaderV1Codec.storeParentBatchHash(batchPtr, _parentBatchHash);
                  uint256 lastBlockTimestamp;
                  {
                      bytes memory lastChunk = _chunks[_chunks.length - 1];
                      lastBlockTimestamp = ChunkCodecV1.getLastBlockTimestamp(lastChunk);
                  }
                  BatchHeaderV3Codec.storeLastBlockTimestamp(batchPtr, lastBlockTimestamp);
                  BatchHeaderV3Codec.storeBlobDataProof(batchPtr, _blobDataProof);
                  // compute batch hash, V2~V6 has same code as V0
                  bytes32 _batchHash = BatchHeaderV0Codec.computeBatchHash(
                      batchPtr,
                      BatchHeaderV3Codec.BATCH_HEADER_FIXED_LENGTH
                  );
                  _afterCommitBatch(_batchIndex, _batchHash);
                  return _batchIndex;
              }
              /// @dev Internal function to commit chunks with version 1
              /// @param _totalL1MessagesPoppedOverall The number of L1 messages popped before the list of chunks.
              /// @param _chunks The list of chunks to commit.
              /// @param _skippedL1MessageBitmap The bitmap indicates whether each L1 message is skipped or not.
              /// @return _batchDataHash The computed data hash for the list of chunks.
              /// @return _totalL1MessagesPoppedInBatch The total number of L1 messages popped in this batch, including skipped one.
              function _commitChunksV1(
                  uint256 _totalL1MessagesPoppedOverall,
                  bytes[] memory _chunks,
                  bytes calldata _skippedL1MessageBitmap
              ) internal view returns (bytes32 _batchDataHash, uint256 _totalL1MessagesPoppedInBatch) {
                  uint256 _chunksLength = _chunks.length;
                  // load `batchDataHashPtr` and reserve the memory region for chunk data hashes
                  uint256 batchDataHashPtr;
                  assembly {
                      batchDataHashPtr := mload(0x40)
                      mstore(0x40, add(batchDataHashPtr, mul(_chunksLength, 32)))
                  }
                  // compute the data hash for each chunk
                  for (uint256 i = 0; i < _chunksLength; i++) {
                      uint256 _totalNumL1MessagesInChunk;
                      bytes32 _chunkDataHash;
                      (_chunkDataHash, _totalNumL1MessagesInChunk) = _commitChunkV1(
                          _chunks[i],
                          _totalL1MessagesPoppedInBatch,
                          _totalL1MessagesPoppedOverall,
                          _skippedL1MessageBitmap
                      );
                      unchecked {
                          _totalL1MessagesPoppedInBatch += _totalNumL1MessagesInChunk;
                          _totalL1MessagesPoppedOverall += _totalNumL1MessagesInChunk;
                      }
                      assembly {
                          mstore(batchDataHashPtr, _chunkDataHash)
                          batchDataHashPtr := add(batchDataHashPtr, 0x20)
                      }
                  }
                  // compute the data hash for current batch
                  assembly {
                      let dataLen := mul(_chunksLength, 0x20)
                      _batchDataHash := keccak256(sub(batchDataHashPtr, dataLen), dataLen)
                  }
              }
              /// @dev Internal function to load batch header from calldata to memory.
              /// @param _batchHeader The batch header in calldata.
              /// @param _lastCommittedBatchIndex The index of the last committed batch.
              /// @return batchPtr The start memory offset of loaded batch header.
              /// @return _batchHash The hash of the loaded batch header.
              /// @return _batchIndex The index of this batch.
              /// @return _totalL1MessagesPoppedOverall The number of L1 messages popped after this batch.
              /// @dev This function only works with batches whose hashes are stored in `committedBatches`.
              function _loadBatchHeader(bytes calldata _batchHeader, uint256 _lastCommittedBatchIndex)
                  internal
                  view
                  virtual
                  returns (
                      uint256 batchPtr,
                      bytes32 _batchHash,
                      uint256 _batchIndex,
                      uint256 _totalL1MessagesPoppedOverall
                  )
              {
                  // load version from batch header, it is always the first byte.
                  uint256 version;
                  assembly {
                      version := shr(248, calldataload(_batchHeader.offset))
                  }
                  uint256 _length;
                  if (version == 0) {
                      (batchPtr, _length) = BatchHeaderV0Codec.loadAndValidate(_batchHeader);
                  } else if (version <= 2) {
                      (batchPtr, _length) = BatchHeaderV1Codec.loadAndValidate(_batchHeader);
                  } else if (version <= 6) {
                      (batchPtr, _length) = BatchHeaderV3Codec.loadAndValidate(_batchHeader);
                  } else {
                      (batchPtr, _length) = BatchHeaderV7Codec.loadAndValidate(_batchHeader);
                  }
                  // the code for compute batch hash is the same for V0~V6
                  // also the `_batchIndex` and `_totalL1MessagesPoppedOverall`.
                  _batchHash = BatchHeaderV0Codec.computeBatchHash(batchPtr, _length);
                  _batchIndex = BatchHeaderV0Codec.getBatchIndex(batchPtr);
                  // we don't have totalL1MessagesPoppedOverall in V7~
                  if (version <= 6) {
                      _totalL1MessagesPoppedOverall = BatchHeaderV0Codec.getTotalL1MessagePopped(batchPtr);
                  }
                  if (_batchIndex > _lastCommittedBatchIndex) revert ErrorBatchNotCommitted();
                  // only check when genesis is imported
                  if (committedBatches[_batchIndex] != _batchHash && finalizedStateRoots[0] != bytes32(0)) {
                      revert ErrorIncorrectBatchHash();
                  }
              }
              /// @dev Internal function to commit a chunk with version 1.
              /// @param _chunk The encoded chunk to commit.
              /// @param _totalL1MessagesPoppedInBatch The total number of L1 messages popped in current batch.
              /// @param _totalL1MessagesPoppedOverall The total number of L1 messages popped in all batches including current batch.
              /// @param _skippedL1MessageBitmap The bitmap indicates whether each L1 message is skipped or not.
              /// @return _dataHash The computed data hash for this chunk.
              /// @return _totalNumL1MessagesInChunk The total number of L1 message popped in current chunk
              function _commitChunkV1(
                  bytes memory _chunk,
                  uint256 _totalL1MessagesPoppedInBatch,
                  uint256 _totalL1MessagesPoppedOverall,
                  bytes calldata _skippedL1MessageBitmap
              ) internal view returns (bytes32 _dataHash, uint256 _totalNumL1MessagesInChunk) {
                  uint256 chunkPtr;
                  uint256 startDataPtr;
                  uint256 dataPtr;
                  assembly {
                      dataPtr := mload(0x40)
                      startDataPtr := dataPtr
                      chunkPtr := add(_chunk, 0x20) // skip chunkLength
                  }
                  uint256 _numBlocks = ChunkCodecV1.validateChunkLength(chunkPtr, _chunk.length);
                  // concatenate block contexts, use scope to avoid stack too deep
                  for (uint256 i = 0; i < _numBlocks; i++) {
                      dataPtr = ChunkCodecV1.copyBlockContext(chunkPtr, dataPtr, i);
                      uint256 blockPtr = chunkPtr + 1 + i * ChunkCodecV1.BLOCK_CONTEXT_LENGTH;
                      uint256 _numL1MessagesInBlock = ChunkCodecV1.getNumL1Messages(blockPtr);
                      unchecked {
                          _totalNumL1MessagesInChunk += _numL1MessagesInBlock;
                      }
                  }
                  assembly {
                      mstore(0x40, add(dataPtr, mul(_totalNumL1MessagesInChunk, 0x20))) // reserve memory for l1 message hashes
                      chunkPtr := add(chunkPtr, 1)
                  }
                  // the number of actual transactions in one chunk: non-skipped l1 messages + l2 txs
                  uint256 _totalTransactionsInChunk;
                  // concatenate tx hashes
                  while (_numBlocks > 0) {
                      // concatenate l1 message hashes
                      uint256 _numL1MessagesInBlock = ChunkCodecV1.getNumL1Messages(chunkPtr);
                      uint256 startPtr = dataPtr;
                      dataPtr = _loadL1MessageHashes(
                          dataPtr,
                          _numL1MessagesInBlock,
                          _totalL1MessagesPoppedInBatch,
                          _totalL1MessagesPoppedOverall,
                          _skippedL1MessageBitmap
                      );
                      uint256 _numTransactionsInBlock = ChunkCodecV1.getNumTransactions(chunkPtr);
                      if (_numTransactionsInBlock < _numL1MessagesInBlock) revert ErrorNumTxsLessThanNumL1Msgs();
                      unchecked {
                          _totalTransactionsInChunk += (dataPtr - startPtr) / 32; // number of non-skipped l1 messages
                          _totalTransactionsInChunk += _numTransactionsInBlock - _numL1MessagesInBlock; // number of l2 txs
                          _totalL1MessagesPoppedInBatch += _numL1MessagesInBlock;
                          _totalL1MessagesPoppedOverall += _numL1MessagesInBlock;
                          _numBlocks -= 1;
                          chunkPtr += ChunkCodecV1.BLOCK_CONTEXT_LENGTH;
                      }
                  }
                  // check the actual number of transactions in the chunk
                  if (_totalTransactionsInChunk > maxNumTxInChunk) {
                      revert ErrorTooManyTxsInOneChunk();
                  }
                  // compute data hash and store to memory
                  assembly {
                      _dataHash := keccak256(startDataPtr, sub(dataPtr, startDataPtr))
                  }
              }
              /// @dev Internal function to load L1 message hashes from the message queue.
              /// @param _ptr The memory offset to store the transaction hash.
              /// @param _numL1Messages The number of L1 messages to load.
              /// @param _totalL1MessagesPoppedInBatch The total number of L1 messages popped in current batch.
              /// @param _totalL1MessagesPoppedOverall The total number of L1 messages popped in all batches including current batch.
              /// @param _skippedL1MessageBitmap The bitmap indicates whether each L1 message is skipped or not.
              /// @return uint256 The new memory offset after loading.
              function _loadL1MessageHashes(
                  uint256 _ptr,
                  uint256 _numL1Messages,
                  uint256 _totalL1MessagesPoppedInBatch,
                  uint256 _totalL1MessagesPoppedOverall,
                  bytes calldata _skippedL1MessageBitmap
              ) internal view returns (uint256) {
                  if (_numL1Messages == 0) return _ptr;
                  IL1MessageQueueV1 _messageQueue = IL1MessageQueueV1(messageQueueV1);
                  unchecked {
                      uint256 _bitmap;
                      uint256 rem;
                      for (uint256 i = 0; i < _numL1Messages; i++) {
                          uint256 quo = _totalL1MessagesPoppedInBatch >> 8;
                          rem = _totalL1MessagesPoppedInBatch & 0xff;
                          // load bitmap every 256 bits
                          if (i == 0 || rem == 0) {
                              assembly {
                                  _bitmap := calldataload(add(_skippedL1MessageBitmap.offset, mul(0x20, quo)))
                              }
                          }
                          if (((_bitmap >> rem) & 1) == 0) {
                              // message not skipped
                              bytes32 _hash = _messageQueue.getCrossDomainMessage(_totalL1MessagesPoppedOverall);
                              assembly {
                                  mstore(_ptr, _hash)
                                  _ptr := add(_ptr, 0x20)
                              }
                          }
                          _totalL1MessagesPoppedInBatch += 1;
                          _totalL1MessagesPoppedOverall += 1;
                      }
                      // check last L1 message is not skipped, _totalL1MessagesPoppedInBatch must > 0
                      rem = (_totalL1MessagesPoppedInBatch - 1) & 0xff;
                      if (((_bitmap >> rem) & 1) > 0) revert ErrorLastL1MessageSkipped();
                  }
                  return _ptr;
              }
              /// @param totalL1MessagesPoppedOverall The total number of L1 messages popped in all batches including current batch.
              function _finalizePoppedL1Messages(uint256 totalL1MessagesPoppedOverall, bool isV1) internal {
                  if (totalL1MessagesPoppedOverall > 0) {
                      if (isV1) {
                          IL1MessageQueueV1(messageQueueV1).finalizePoppedCrossDomainMessage(totalL1MessagesPoppedOverall);
                      } else {
                          IL1MessageQueueV2(messageQueueV2).finalizePoppedCrossDomainMessage(totalL1MessagesPoppedOverall);
                      }
                  }
              }
              /// @dev Internal function to pop l1 messages from `skippedL1MessageBitmap` in calldata.
              /// @param skippedL1MessageBitmap The `skippedL1MessageBitmap` in calldata.
              /// @param totalL1MessagesPoppedOverall The total number of L1 messages popped in all batches including current batch.
              /// @param totalL1MessagesPoppedInBatch The number of L1 messages popped in current batch.
              function _popL1MessagesCalldata(
                  bytes calldata skippedL1MessageBitmap,
                  uint256 totalL1MessagesPoppedOverall,
                  uint256 totalL1MessagesPoppedInBatch
              ) internal {
                  if (totalL1MessagesPoppedInBatch == 0) return;
                  uint256 bitmapPtr;
                  assembly {
                      bitmapPtr := skippedL1MessageBitmap.offset
                  }
                  _popL1Messages(true, bitmapPtr, totalL1MessagesPoppedOverall, totalL1MessagesPoppedInBatch);
              }
              /// @dev Internal function to pop l1 messages from `skippedL1MessageBitmap` in calldata or memory.
              /// @param isCalldata Whether the `skippedL1MessageBitmap` is in calldata or memory.
              /// @param bitmapPtr The offset of `skippedL1MessageBitmap` in calldata or memory.
              /// @param totalL1MessagesPoppedOverall The total number of L1 messages popped in all batches including current batch.
              /// @param totalL1MessagesPoppedInBatch The number of L1 messages popped in current batch.
              function _popL1Messages(
                  bool isCalldata,
                  uint256 bitmapPtr,
                  uint256 totalL1MessagesPoppedOverall,
                  uint256 totalL1MessagesPoppedInBatch
              ) internal {
                  if (totalL1MessagesPoppedInBatch == 0) return;
                  unchecked {
                      uint256 startIndex = totalL1MessagesPoppedOverall - totalL1MessagesPoppedInBatch;
                      uint256 bitmap;
                      for (uint256 i = 0; i < totalL1MessagesPoppedInBatch; i += 256) {
                          uint256 _count = 256;
                          if (totalL1MessagesPoppedInBatch - i < _count) {
                              _count = totalL1MessagesPoppedInBatch - i;
                          }
                          assembly {
                              switch isCalldata
                              case 1 {
                                  bitmap := calldataload(bitmapPtr)
                              }
                              default {
                                  bitmap := mload(bitmapPtr)
                              }
                              bitmapPtr := add(bitmapPtr, 0x20)
                          }
                          IL1MessageQueueV1(messageQueueV1).popCrossDomainMessage(startIndex, _count, bitmap);
                          startIndex += 256;
                      }
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity =0.8.24;
          import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
          contract SystemConfig is OwnableUpgradeable {
              /***********
               * Structs *
               ***********/
              /// @notice Parameters for the message queue.
              /// @param maxGasLimit The maximum gas limit allowed for each L1 message.
              /// @param baseFeeOverhead The overhead used to calculate l2 base fee.
              /// @param baseFeeScalar The scalar used to calculate l2 base fee.
              /// @dev The compiler will pack this struct into single `bytes32`.
              struct MessageQueueParameters {
                  uint32 maxGasLimit;
                  uint112 baseFeeOverhead;
                  uint112 baseFeeScalar;
              }
              /// @notice Parameters for the enforced batch mode.
              /// @param maxDelayEnterEnforcedMode If no batch has been finalized for `maxDelayEnterEnforcedMode`,
              ///        batch submission becomes permissionless. Anyone can submit a batch together with a proof.
              /// @param maxDelayMessageQueue If no message is included/finalized for `maxDelayMessageQueue`,
              ///        batch submission becomes permissionless. Anyone can submit a batch together with a proof.
              /// @dev The compiler will pack this struct into single `bytes32`.
              struct EnforcedBatchParameters {
                  uint24 maxDelayEnterEnforcedMode;
                  uint24 maxDelayMessageQueue;
              }
              /*********************
               * Storage Variables *
               *********************/
              /// @notice The parameters for the message queue.
              MessageQueueParameters public messageQueueParameters;
              /// @notice The parameters for the enforced batch mode.
              EnforcedBatchParameters public enforcedBatchParameters;
              /// @dev The address of the current authorized signer.
              address private currentSigner;
              /***************
               * Constructor *
               ***************/
              constructor() {
                  _disableInitializers();
              }
              function initialize(
                  address _owner,
                  address _signer,
                  MessageQueueParameters memory _messageQueueParameters,
                  EnforcedBatchParameters memory _enforcedBatchParameters
              ) external initializer {
                  __Ownable_init();
                  transferOwnership(_owner);
                  currentSigner = _signer;
                  messageQueueParameters = _messageQueueParameters;
                  enforcedBatchParameters = _enforcedBatchParameters;
              }
              /*************************
               * Public View Functions *
               *************************/
              /// @notice Return the current authorized signer.
              /// @return The authorized signer address.
              function getSigner() external view returns (address) {
                  return currentSigner;
              }
              /************************
               * Restricted Functions *
               ************************/
              /// @notice Update the message queue parameters.
              /// @param _params The new message queue parameters.
              /// @dev Only the owner can call this function.
              function updateMessageQueueParameters(MessageQueueParameters memory _params) external onlyOwner {
                  messageQueueParameters = _params;
              }
              /// @notice Update the enforced batch parameters.
              /// @param _params The new enforced batch parameters.
              /// @dev Only the owner can call this function.
              function updateEnforcedBatchParameters(EnforcedBatchParameters memory _params) external onlyOwner {
                  enforcedBatchParameters = _params;
              }
              /// @notice Update the current signer.
              /// @param _newSigner The address of the new authorized signer.
              /// @dev Only the owner can call this function.
              function updateSigner(address _newSigner) external onlyOwner {
                  currentSigner = _newSigner;
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          // solhint-disable no-inline-assembly
          /// @dev Below is the encoding for `BatchHeader` V0, total 89 + ceil(l1MessagePopped / 256) * 32 bytes.
          /// ```text
          ///   * Field                   Bytes       Type        Index   Comments
          ///   * version                 1           uint8       0       The batch version
          ///   * batchIndex              8           uint64      1       The index of the batch
          ///   * l1MessagePopped         8           uint64      9       Number of L1 messages popped in the batch
          ///   * totalL1MessagePopped    8           uint64      17      Number of total L1 messages popped after the batch
          ///   * dataHash                32          bytes32     25      The data hash of the batch
          ///   * parentBatchHash         32          bytes32     57      The parent batch hash
          ///   * skippedL1MessageBitmap  dynamic     uint256[]   89      A bitmap to indicate which L1 messages are skipped in the batch
          /// ```
          library BatchHeaderV0Codec {
              /// @dev Thrown when the length of batch header is smaller than 89
              error ErrorBatchHeaderV0LengthTooSmall();
              /// @dev Thrown when the length of skippedL1MessageBitmap is incorrect.
              error ErrorIncorrectBitmapLengthV0();
              /// @dev The length of fixed parts of the batch header.
              uint256 internal constant BATCH_HEADER_FIXED_LENGTH = 89;
              /// @notice Load batch header in calldata to memory.
              /// @param _batchHeader The encoded batch header bytes in calldata.
              /// @return batchPtr The start memory offset of the batch header in memory.
              /// @return length The length in bytes of the batch header.
              function loadAndValidate(bytes calldata _batchHeader) internal pure returns (uint256 batchPtr, uint256 length) {
                  length = _batchHeader.length;
                  if (length < BATCH_HEADER_FIXED_LENGTH) revert ErrorBatchHeaderV0LengthTooSmall();
                  // copy batch header to memory.
                  assembly {
                      batchPtr := mload(0x40)
                      calldatacopy(batchPtr, _batchHeader.offset, length)
                      mstore(0x40, add(batchPtr, length))
                  }
                  // check batch header length
                  uint256 _l1MessagePopped = getL1MessagePopped(batchPtr);
                  unchecked {
                      if (length != BATCH_HEADER_FIXED_LENGTH + ((_l1MessagePopped + 255) / 256) * 32) {
                          revert ErrorIncorrectBitmapLengthV0();
                      }
                  }
              }
              /// @notice Get the version of the batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _version The version of the batch header.
              function getVersion(uint256 batchPtr) internal pure returns (uint256 _version) {
                  assembly {
                      _version := shr(248, mload(batchPtr))
                  }
              }
              /// @notice Get the batch index of the batch.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _batchIndex The batch index of the batch.
              function getBatchIndex(uint256 batchPtr) internal pure returns (uint256 _batchIndex) {
                  assembly {
                      _batchIndex := shr(192, mload(add(batchPtr, 1)))
                  }
              }
              /// @notice Get the number of L1 messages of the batch.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _l1MessagePopped The number of L1 messages of the batch.
              function getL1MessagePopped(uint256 batchPtr) internal pure returns (uint256 _l1MessagePopped) {
                  assembly {
                      _l1MessagePopped := shr(192, mload(add(batchPtr, 9)))
                  }
              }
              /// @notice Get the number of L1 messages popped before this batch.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _totalL1MessagePopped The number of L1 messages popped before this batch.
              function getTotalL1MessagePopped(uint256 batchPtr) internal pure returns (uint256 _totalL1MessagePopped) {
                  assembly {
                      _totalL1MessagePopped := shr(192, mload(add(batchPtr, 17)))
                  }
              }
              /// @notice Get the data hash of the batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _dataHash The data hash of the batch header.
              function getDataHash(uint256 batchPtr) internal pure returns (bytes32 _dataHash) {
                  assembly {
                      _dataHash := mload(add(batchPtr, 25))
                  }
              }
              /// @notice Get the parent batch hash of the batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _parentBatchHash The parent batch hash of the batch header.
              function getParentBatchHash(uint256 batchPtr) internal pure returns (bytes32 _parentBatchHash) {
                  assembly {
                      _parentBatchHash := mload(add(batchPtr, 57))
                  }
              }
              /// @notice Get the start memory offset for skipped L1 messages bitmap.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _bitmapPtr the start memory offset for skipped L1 messages bitmap.
              function getSkippedBitmapPtr(uint256 batchPtr) internal pure returns (uint256 _bitmapPtr) {
                  assembly {
                      _bitmapPtr := add(batchPtr, BATCH_HEADER_FIXED_LENGTH)
                  }
              }
              /// @notice Get the skipped L1 messages bitmap.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param index The index of bitmap to load.
              /// @return _bitmap The bitmap from bits `index * 256` to `index * 256 + 255`.
              function getSkippedBitmap(uint256 batchPtr, uint256 index) internal pure returns (uint256 _bitmap) {
                  assembly {
                      batchPtr := add(batchPtr, BATCH_HEADER_FIXED_LENGTH)
                      _bitmap := mload(add(batchPtr, mul(index, 32)))
                  }
              }
              /// @notice Store the version of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _version The version of batch header.
              function storeVersion(uint256 batchPtr, uint256 _version) internal pure {
                  assembly {
                      mstore8(batchPtr, _version)
                  }
              }
              /// @notice Store the batch index of batch header.
              /// @dev Because this function can overwrite the subsequent fields, it must be called before
              /// `storeL1MessagePopped`, `storeTotalL1MessagePopped`, and `storeDataHash`.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _batchIndex The batch index.
              function storeBatchIndex(uint256 batchPtr, uint256 _batchIndex) internal pure {
                  assembly {
                      mstore(add(batchPtr, 1), shl(192, _batchIndex))
                  }
              }
              /// @notice Store the number of L1 messages popped in current batch to batch header.
              /// @dev Because this function can overwrite the subsequent fields, it must be called before
              /// `storeTotalL1MessagePopped` and `storeDataHash`.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _l1MessagePopped The number of L1 messages popped in current batch.
              function storeL1MessagePopped(uint256 batchPtr, uint256 _l1MessagePopped) internal pure {
                  assembly {
                      mstore(add(batchPtr, 9), shl(192, _l1MessagePopped))
                  }
              }
              /// @notice Store the total number of L1 messages popped after current batch to batch header.
              /// @dev Because this function can overwrite the subsequent fields, it must be called before
              /// `storeDataHash`.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _totalL1MessagePopped The total number of L1 messages popped after current batch.
              function storeTotalL1MessagePopped(uint256 batchPtr, uint256 _totalL1MessagePopped) internal pure {
                  assembly {
                      mstore(add(batchPtr, 17), shl(192, _totalL1MessagePopped))
                  }
              }
              /// @notice Store the data hash of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _dataHash The data hash.
              function storeDataHash(uint256 batchPtr, bytes32 _dataHash) internal pure {
                  assembly {
                      mstore(add(batchPtr, 25), _dataHash)
                  }
              }
              /// @notice Store the parent batch hash of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _parentBatchHash The parent batch hash.
              function storeParentBatchHash(uint256 batchPtr, bytes32 _parentBatchHash) internal pure {
                  assembly {
                      mstore(add(batchPtr, 57), _parentBatchHash)
                  }
              }
              /// @notice Store the skipped L1 message bitmap of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _skippedL1MessageBitmap The skipped L1 message bitmap.
              function storeSkippedBitmap(uint256 batchPtr, bytes calldata _skippedL1MessageBitmap) internal pure {
                  assembly {
                      calldatacopy(
                          add(batchPtr, BATCH_HEADER_FIXED_LENGTH),
                          _skippedL1MessageBitmap.offset,
                          _skippedL1MessageBitmap.length
                      )
                  }
              }
              /// @notice Compute the batch hash.
              /// @dev Caller should make sure that the encoded batch header is correct.
              ///
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param length The length of the batch.
              /// @return _batchHash The hash of the corresponding batch.
              function computeBatchHash(uint256 batchPtr, uint256 length) internal pure returns (bytes32 _batchHash) {
                  // in the current version, the hash is: keccak(BatchHeader without timestamp)
                  assembly {
                      _batchHash := keccak256(batchPtr, length)
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          import {BatchHeaderV0Codec} from "./BatchHeaderV0Codec.sol";
          // solhint-disable no-inline-assembly
          /// @dev Below is the encoding for `BatchHeader` V1, total 121 + ceil(l1MessagePopped / 256) * 32 bytes.
          /// ```text
          ///   * Field                   Bytes       Type        Index   Comments
          ///   * version                 1           uint8       0       The batch version
          ///   * batchIndex              8           uint64      1       The index of the batch
          ///   * l1MessagePopped         8           uint64      9       Number of L1 messages popped in the batch
          ///   * totalL1MessagePopped    8           uint64      17      Number of total L1 messages popped after the batch
          ///   * dataHash                32          bytes32     25      The data hash of the batch
          ///   * blobVersionedHash       32          bytes32     57      The versioned hash of the blob with this batch’s data
          ///   * parentBatchHash         32          bytes32     89      The parent batch hash
          ///   * skippedL1MessageBitmap  dynamic     uint256[]   121     A bitmap to indicate which L1 messages are skipped in the batch
          /// ```
          ///
          /// The codes for `version`, `batchIndex`, `l1MessagePopped`, `totalL1MessagePopped`, `dataHash` and `computeBatchHash`
          /// are the same as `BatchHeaderV0Codec`. However, we won't reuse the codes in this library since they are very simple.
          /// Reusing the codes will introduce extra code jump in solidity, which increase gas costs.
          library BatchHeaderV1Codec {
              /// @dev Thrown when the length of batch header is smaller than 121.
              error ErrorBatchHeaderV1LengthTooSmall();
              /// @dev Thrown when the length of skippedL1MessageBitmap is incorrect.
              error ErrorIncorrectBitmapLengthV1();
              /// @dev The length of fixed parts of the batch header.
              uint256 internal constant BATCH_HEADER_FIXED_LENGTH = 121;
              /// @notice Load batch header in calldata to memory.
              /// @param _batchHeader The encoded batch header bytes in calldata.
              /// @return batchPtr The start memory offset of the batch header in memory.
              /// @return length The length in bytes of the batch header.
              function loadAndValidate(bytes calldata _batchHeader) internal pure returns (uint256 batchPtr, uint256 length) {
                  length = _batchHeader.length;
                  if (length < BATCH_HEADER_FIXED_LENGTH) revert ErrorBatchHeaderV1LengthTooSmall();
                  // copy batch header to memory.
                  assembly {
                      batchPtr := mload(0x40)
                      calldatacopy(batchPtr, _batchHeader.offset, length)
                      mstore(0x40, add(batchPtr, length))
                  }
                  // check batch header length
                  uint256 _l1MessagePopped = BatchHeaderV0Codec.getL1MessagePopped(batchPtr);
                  unchecked {
                      if (length != BATCH_HEADER_FIXED_LENGTH + ((_l1MessagePopped + 255) / 256) * 32)
                          revert ErrorIncorrectBitmapLengthV1();
                  }
              }
              /// @notice Get the blob versioned hash of the batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _blobVersionedHash The blob versioned hash of the batch header.
              function getBlobVersionedHash(uint256 batchPtr) internal pure returns (bytes32 _blobVersionedHash) {
                  assembly {
                      _blobVersionedHash := mload(add(batchPtr, 57))
                  }
              }
              /// @notice Get the parent batch hash of the batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _parentBatchHash The parent batch hash of the batch header.
              function getParentBatchHash(uint256 batchPtr) internal pure returns (bytes32 _parentBatchHash) {
                  assembly {
                      _parentBatchHash := mload(add(batchPtr, 89))
                  }
              }
              /// @notice Get the start memory offset for skipped L1 messages bitmap.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _bitmapPtr the start memory offset for skipped L1 messages bitmap.
              function getSkippedBitmapPtr(uint256 batchPtr) internal pure returns (uint256 _bitmapPtr) {
                  assembly {
                      _bitmapPtr := add(batchPtr, BATCH_HEADER_FIXED_LENGTH)
                  }
              }
              /// @notice Get the skipped L1 messages bitmap.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param index The index of bitmap to load.
              /// @return _bitmap The bitmap from bits `index * 256` to `index * 256 + 255`.
              function getSkippedBitmap(uint256 batchPtr, uint256 index) internal pure returns (uint256 _bitmap) {
                  assembly {
                      batchPtr := add(batchPtr, BATCH_HEADER_FIXED_LENGTH)
                      _bitmap := mload(add(batchPtr, mul(index, 32)))
                  }
              }
              /// @notice Store the parent batch hash of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _blobVersionedHash The versioned hash of the blob with this batch’s data.
              function storeBlobVersionedHash(uint256 batchPtr, bytes32 _blobVersionedHash) internal pure {
                  assembly {
                      mstore(add(batchPtr, 57), _blobVersionedHash)
                  }
              }
              /// @notice Store the parent batch hash of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _parentBatchHash The parent batch hash.
              function storeParentBatchHash(uint256 batchPtr, bytes32 _parentBatchHash) internal pure {
                  assembly {
                      mstore(add(batchPtr, 89), _parentBatchHash)
                  }
              }
              /// @notice Store the skipped L1 message bitmap of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _skippedL1MessageBitmap The skipped L1 message bitmap.
              function storeSkippedBitmap(uint256 batchPtr, bytes calldata _skippedL1MessageBitmap) internal pure {
                  assembly {
                      calldatacopy(
                          add(batchPtr, BATCH_HEADER_FIXED_LENGTH),
                          _skippedL1MessageBitmap.offset,
                          _skippedL1MessageBitmap.length
                      )
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          // solhint-disable no-inline-assembly
          /// @dev Below is the encoding for `BatchHeader` V3, total 193 bytes.
          /// ```text
          ///   * Field                   Bytes       Type        Index   Comments
          ///   * version                 1           uint8       0       The batch version
          ///   * batchIndex              8           uint64      1       The index of the batch
          ///   * l1MessagePopped         8           uint64      9       Number of L1 messages popped in the batch
          ///   * totalL1MessagePopped    8           uint64      17      Number of total L1 messages popped after the batch
          ///   * dataHash                32          bytes32     25      The data hash of the batch
          ///   * blobVersionedHash       32          bytes32     57      The versioned hash of the blob with this batch’s data
          ///   * parentBatchHash         32          bytes32     89      The parent batch hash
          ///   * lastBlockTimestamp      8           uint64      121     A bitmap to indicate which L1 messages are skipped in the batch
          ///   * blobDataProof           64          bytes64     129     The blob data proof: z (32), y (32)
          /// ```
          /// The codes for `version`, `batchIndex`, `l1MessagePopped`, `totalL1MessagePopped`, `dataHash` and `computeBatchHash`
          /// are the same as `BatchHeaderV0Codec`. The codes for `blobVersionedHash` and `parentBatchHash` are the same as
          /// `BatchHeaderV1Codec`. However, we won't reuse the codes since they are very simple. Reusing the codes will introduce
          /// extra code jump in solidity, which increase gas costs.
          library BatchHeaderV3Codec {
              /// @dev Thrown when the length of batch header is not equal to 193.
              error ErrorBatchHeaderV3LengthMismatch();
              /// @dev The length of fixed parts of the batch header.
              uint256 internal constant BATCH_HEADER_FIXED_LENGTH = 193;
              /// @notice Allocate memory for batch header.
              function allocate() internal pure returns (uint256 batchPtr) {
                  assembly {
                      batchPtr := mload(0x40)
                      // This is `BatchHeaderV3Codec.BATCH_HEADER_FIXED_LENGTH`, use `193` here to reduce code complexity.
                      mstore(0x40, add(batchPtr, 193))
                  }
              }
              /// @notice Load batch header in calldata to memory.
              /// @param _batchHeader The encoded batch header bytes in calldata.
              /// @return batchPtr The start memory offset of the batch header in memory.
              /// @return length The length in bytes of the batch header.
              function loadAndValidate(bytes calldata _batchHeader) internal pure returns (uint256 batchPtr, uint256 length) {
                  length = _batchHeader.length;
                  if (length != BATCH_HEADER_FIXED_LENGTH) {
                      revert ErrorBatchHeaderV3LengthMismatch();
                  }
                  // copy batch header to memory.
                  batchPtr = allocate();
                  assembly {
                      calldatacopy(batchPtr, _batchHeader.offset, length)
                  }
              }
              /// @notice Store the last block timestamp of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _lastBlockTimestamp The timestamp of the last block in this batch.
              function storeLastBlockTimestamp(uint256 batchPtr, uint256 _lastBlockTimestamp) internal pure {
                  assembly {
                      mstore(add(batchPtr, 121), shl(192, _lastBlockTimestamp))
                  }
              }
              /// @notice Store the last block timestamp of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param blobDataProof The blob data proof: z (32), y (32)
              function storeBlobDataProof(uint256 batchPtr, bytes calldata blobDataProof) internal pure {
                  assembly {
                      // z and y is in the first 64 bytes of `blobDataProof`
                      calldatacopy(add(batchPtr, 129), blobDataProof.offset, 64)
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          // solhint-disable no-inline-assembly
          /// @dev Below is the encoding for `BatchHeader` V7, total 73 bytes.
          /// ```text
          ///   * Field                   Bytes       Type        Index   Comments
          ///   * version                 1           uint8       0       The batch version
          ///   * batchIndex              8           uint64      1       The index of the batch
          ///   * blobVersionedHash       32          bytes32     9       The versioned hash of the blob with this batch’s data
          ///   * parentBatchHash         32          bytes32     41      The parent batch hash
          /// ```
          /// The codes for `version`, `batchIndex` and `computeBatchHash` are the same as `BatchHeaderV0Codec`.
          /// However, we won't reuse the codes since they are very simple. Reusing the codes will introduce
          /// extra code jump in solidity, which increase gas costs.
          library BatchHeaderV7Codec {
              /// @dev Thrown when the length of batch header is not equal to 73.
              error ErrorBatchHeaderV7LengthMismatch();
              /// @dev The length of fixed parts of the batch header.
              uint256 internal constant BATCH_HEADER_FIXED_LENGTH = 73;
              /// @notice Allocate memory for batch header.
              function allocate() internal pure returns (uint256 batchPtr) {
                  assembly {
                      batchPtr := mload(0x40)
                      // This is `BatchHeaderV7Codec.BATCH_HEADER_FIXED_LENGTH`, use `73` here to reduce code complexity.
                      mstore(0x40, add(batchPtr, 73))
                  }
              }
              /// @notice Load batch header in calldata to memory.
              /// @param _batchHeader The encoded batch header bytes in calldata.
              /// @return batchPtr The start memory offset of the batch header in memory.
              /// @return length The length in bytes of the batch header.
              function loadAndValidate(bytes calldata _batchHeader) internal pure returns (uint256 batchPtr, uint256 length) {
                  length = _batchHeader.length;
                  if (length != BATCH_HEADER_FIXED_LENGTH) {
                      revert ErrorBatchHeaderV7LengthMismatch();
                  }
                  // copy batch header to memory.
                  batchPtr = allocate();
                  assembly {
                      calldatacopy(batchPtr, _batchHeader.offset, length)
                  }
              }
              /// @notice Get the blob versioned hash of the batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _blobVersionedHash The blob versioned hash of the batch header.
              function getBlobVersionedHash(uint256 batchPtr) internal pure returns (bytes32 _blobVersionedHash) {
                  assembly {
                      _blobVersionedHash := mload(add(batchPtr, 9))
                  }
              }
              /// @notice Get the parent batch hash of the batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @return _parentBatchHash The parent batch hash of the batch header.
              function getParentBatchHash(uint256 batchPtr) internal pure returns (bytes32 _parentBatchHash) {
                  assembly {
                      _parentBatchHash := mload(add(batchPtr, 41))
                  }
              }
              /// @notice Store the blob versioned hash of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _blobVersionedHash The versioned hash of the blob with this batch’s data.
              function storeBlobVersionedHash(uint256 batchPtr, bytes32 _blobVersionedHash) internal pure {
                  assembly {
                      mstore(add(batchPtr, 9), _blobVersionedHash)
                  }
              }
              /// @notice Store the parent batch hash of batch header.
              /// @param batchPtr The start memory offset of the batch header in memory.
              /// @param _parentBatchHash The parent batch hash.
              function storeParentBatchHash(uint256 batchPtr, bytes32 _parentBatchHash) internal pure {
                  assembly {
                      mstore(add(batchPtr, 41), _parentBatchHash)
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          /// @dev Below is the encoding for `Chunk`, total 60*n+1+m bytes.
          /// ```text
          ///   * Field           Bytes       Type            Index       Comments
          ///   * numBlocks       1           uint8           0           The number of blocks in this chunk
          ///   * block[0]        60          BlockContext    1           The first block in this chunk
          ///   * ......
          ///   * block[i]        60          BlockContext    60*i+1      The (i+1)'th block in this chunk
          ///   * ......
          ///   * block[n-1]      60          BlockContext    60*n-59     The last block in this chunk
          ///   * l2Transactions  dynamic     bytes           60*n+1
          /// ```
          ///
          /// @dev Below is the encoding for `BlockContext`, total 60 bytes.
          /// ```text
          ///   * Field                   Bytes      Type         Index  Comments
          ///   * blockNumber             8          uint64       0      The height of this block.
          ///   * timestamp               8          uint64       8      The timestamp of this block.
          ///   * baseFee                 32         uint256      16     The base fee of this block.
          ///   * gasLimit                8          uint64       48     The gas limit of this block.
          ///   * numTransactions         2          uint16       56     The number of transactions in this block, both L1 & L2 txs.
          ///   * numL1Messages           2          uint16       58     The number of l1 messages in this block.
          /// ```
          library ChunkCodecV0 {
              /// @dev Thrown when no blocks in chunk.
              error ErrorNoBlockInChunkV0();
              /// @dev Thrown when the length of chunk is incorrect.
              error ErrorIncorrectChunkLengthV0();
              /// @dev The length of one block context.
              uint256 internal constant BLOCK_CONTEXT_LENGTH = 60;
              /// @notice Validate the length of chunk.
              /// @param chunkPtr The start memory offset of the chunk in memory.
              /// @param _length The length of the chunk.
              /// @return _numBlocks The number of blocks in current chunk.
              function validateChunkLength(uint256 chunkPtr, uint256 _length) internal pure returns (uint256 _numBlocks) {
                  _numBlocks = getNumBlocks(chunkPtr);
                  // should contain at least one block
                  if (_numBlocks == 0) revert ErrorNoBlockInChunkV0();
                  // should contain at least the number of the blocks and block contexts
                  if (_length < 1 + _numBlocks * BLOCK_CONTEXT_LENGTH) revert ErrorIncorrectChunkLengthV0();
              }
              /// @notice Return the start memory offset of `l2Transactions`.
              /// @dev The caller should make sure `_numBlocks` is correct.
              /// @param chunkPtr The start memory offset of the chunk in memory.
              /// @param _numBlocks The number of blocks in current chunk.
              /// @return _l2TxPtr the start memory offset of `l2Transactions`.
              function getL2TxPtr(uint256 chunkPtr, uint256 _numBlocks) internal pure returns (uint256 _l2TxPtr) {
                  unchecked {
                      _l2TxPtr = chunkPtr + 1 + _numBlocks * BLOCK_CONTEXT_LENGTH;
                  }
              }
              /// @notice Return the number of blocks in current chunk.
              /// @param chunkPtr The start memory offset of the chunk in memory.
              /// @return _numBlocks The number of blocks in current chunk.
              function getNumBlocks(uint256 chunkPtr) internal pure returns (uint256 _numBlocks) {
                  assembly {
                      _numBlocks := shr(248, mload(chunkPtr))
                  }
              }
              /// @notice Copy the block context to another memory.
              /// @param chunkPtr The start memory offset of the chunk in memory.
              /// @param dstPtr The destination memory offset to store the block context.
              /// @param index The index of block context to copy.
              /// @return uint256 The new destination memory offset after copy.
              function copyBlockContext(
                  uint256 chunkPtr,
                  uint256 dstPtr,
                  uint256 index
              ) internal pure returns (uint256) {
                  // only first 58 bytes is needed.
                  assembly {
                      chunkPtr := add(chunkPtr, add(1, mul(BLOCK_CONTEXT_LENGTH, index)))
                      mcopy(dstPtr, chunkPtr, 58)
                      dstPtr := add(dstPtr, 58)
                  }
                  return dstPtr;
              }
              /// @notice Return the number of transactions in current block.
              /// @param blockPtr The start memory offset of the block context in memory.
              /// @return _numTransactions The number of transactions in current block.
              function getNumTransactions(uint256 blockPtr) internal pure returns (uint256 _numTransactions) {
                  assembly {
                      _numTransactions := shr(240, mload(add(blockPtr, 56)))
                  }
              }
              /// @notice Return the number of L1 messages in current block.
              /// @param blockPtr The start memory offset of the block context in memory.
              /// @return _numL1Messages The number of L1 messages in current block.
              function getNumL1Messages(uint256 blockPtr) internal pure returns (uint256 _numL1Messages) {
                  assembly {
                      _numL1Messages := shr(240, mload(add(blockPtr, 58)))
                  }
              }
              /// @notice Compute and load the transaction hash.
              /// @param _l2TxPtr The start memory offset of the transaction in memory.
              /// @return bytes32 The transaction hash of the transaction.
              /// @return uint256 The start memory offset of the next transaction in memory.
              function loadL2TxHash(uint256 _l2TxPtr) internal pure returns (bytes32, uint256) {
                  bytes32 txHash;
                  assembly {
                      // first 4 bytes indicate the length
                      let txPayloadLength := shr(224, mload(_l2TxPtr))
                      _l2TxPtr := add(_l2TxPtr, 4)
                      txHash := keccak256(_l2TxPtr, txPayloadLength)
                      _l2TxPtr := add(_l2TxPtr, txPayloadLength)
                  }
                  return (txHash, _l2TxPtr);
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          import {ChunkCodecV0} from "./ChunkCodecV0.sol";
          /// @dev Below is the encoding for `Chunk`, total 60*n+1 bytes.
          /// The only difference between `ChunkCodecV0` is we remove `l2Transactions` from chunk encoding.
          /// ```text
          ///   * Field           Bytes       Type            Index       Comments
          ///   * numBlocks       1           uint8           0           The number of blocks in this chunk
          ///   * block[0]        60          BlockContext    1           The first block in this chunk
          ///   * ......
          ///   * block[i]        60          BlockContext    60*i+1      The (i+1)'th block in this chunk
          ///   * ......
          ///   * block[n-1]      60          BlockContext    60*n-59     The last block in this chunk
          /// ```
          ///
          /// @dev Below is the encoding for `BlockContext`, total 60 bytes.
          /// ```text
          ///   * Field                   Bytes      Type         Index  Comments
          ///   * blockNumber             8          uint64       0      The height of this block.
          ///   * timestamp               8          uint64       8      The timestamp of this block.
          ///   * baseFee                 32         uint256      16     The base fee of this block.
          ///   * gasLimit                8          uint64       48     The gas limit of this block.
          ///   * numTransactions         2          uint16       56     The number of transactions in this block, both L1 & L2 txs.
          ///   * numL1Messages           2          uint16       58     The number of l1 messages in this block.
          /// ```
          library ChunkCodecV1 {
              /// @dev Thrown when no blocks in chunk.
              error ErrorNoBlockInChunkV1();
              /// @dev Thrown when the length of chunk is incorrect.
              error ErrorIncorrectChunkLengthV1();
              /// @dev The length of one block context.
              uint256 internal constant BLOCK_CONTEXT_LENGTH = 60;
              /// @notice Validate the length of chunk.
              /// @param chunkPtr The start memory offset of the chunk in memory.
              /// @param _length The length of the chunk.
              /// @return _numBlocks The number of blocks in current chunk.
              function validateChunkLength(uint256 chunkPtr, uint256 _length) internal pure returns (uint256 _numBlocks) {
                  _numBlocks = getNumBlocks(chunkPtr);
                  // should contain at least one block
                  if (_numBlocks == 0) revert ErrorNoBlockInChunkV1();
                  // should contain the number of the blocks and block contexts
                  if (_length != 1 + _numBlocks * BLOCK_CONTEXT_LENGTH) revert ErrorIncorrectChunkLengthV1();
              }
              /// @notice Return the number of blocks in current chunk.
              /// @param chunkPtr The start memory offset of the chunk in memory.
              /// @return _numBlocks The number of blocks in current chunk.
              function getNumBlocks(uint256 chunkPtr) internal pure returns (uint256 _numBlocks) {
                  return ChunkCodecV0.getNumBlocks(chunkPtr);
              }
              /// @notice Copy the block context to another memory.
              /// @param chunkPtr The start memory offset of the chunk in memory.
              /// @param dstPtr The destination memory offset to store the block context.
              /// @param index The index of block context to copy.
              /// @return uint256 The new destination memory offset after copy.
              function copyBlockContext(
                  uint256 chunkPtr,
                  uint256 dstPtr,
                  uint256 index
              ) internal pure returns (uint256) {
                  return ChunkCodecV0.copyBlockContext(chunkPtr, dstPtr, index);
              }
              /// @notice Return the number of transactions in current block.
              /// @param blockPtr The start memory offset of the block context in memory.
              /// @return _numTransactions The number of transactions in current block.
              function getNumTransactions(uint256 blockPtr) internal pure returns (uint256 _numTransactions) {
                  return ChunkCodecV0.getNumTransactions(blockPtr);
              }
              /// @notice Return the number of L1 messages in current block.
              /// @param blockPtr The start memory offset of the block context in memory.
              /// @return _numL1Messages The number of L1 messages in current block.
              function getNumL1Messages(uint256 blockPtr) internal pure returns (uint256 _numL1Messages) {
                  return ChunkCodecV0.getNumL1Messages(blockPtr);
              }
              /// @notice Return the block timestamp of last block in current chunk
              /// @param chunk Current chunk in memory.
              /// @return _timestamp The number of L1 messages in current block.
              function getLastBlockTimestamp(bytes memory chunk) internal pure returns (uint256 _timestamp) {
                  assembly {
                      let chunkPtr := add(chunk, 0x20)
                      let numBlocks := shr(248, mload(chunkPtr))
                      // blockPtr is chunkPtr + 1 + (numBlocks - 1) * BLOCK_CONTEXT_LENGTH
                      let blockPtr := sub(add(chunkPtr, mul(numBlocks, 60)), 59)
                      _timestamp := shr(192, mload(add(blockPtr, 8)))
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity ^0.8.24;
          /// @title IRollupVerifier
          /// @notice The interface for rollup verifier.
          interface IRollupVerifier {
              /// @notice Verify aggregate zk proof.
              /// @param batchIndex The batch index to verify.
              /// @param aggrProof The aggregated proof.
              /// @param publicInputHash The public input hash.
              function verifyAggregateProof(
                  uint256 batchIndex,
                  bytes calldata aggrProof,
                  bytes32 publicInputHash
              ) external view;
              /// @notice Verify aggregate zk proof.
              /// @param version The version of verifier to use.
              /// @param batchIndex The batch index to verify.
              /// @param aggrProof The aggregated proof.
              /// @param publicInputHash The public input hash.
              function verifyAggregateProof(
                  uint256 version,
                  uint256 batchIndex,
                  bytes calldata aggrProof,
                  bytes32 publicInputHash
              ) external view;
              /// @notice Verify bundle zk proof.
              /// @param version The version of verifier to use.
              /// @param batchIndex The batch index used to select verifier.
              /// @param bundleProof The aggregated proof.
              /// @param publicInput The public input.
              function verifyBundleProof(
                  uint256 version,
                  uint256 batchIndex,
                  bytes calldata bundleProof,
                  bytes calldata publicInput
              ) external view;
          }