ETH Price: $2,532.01 (+0.44%)

Transaction Decoder

Block:
19456562 at Mar-17-2024 07:11:47 PM +UTC
Transaction Fee:
0.01733715734962926 ETH $43.90
Gas Used:
438,180 Gas / 39.566290907 Gwei

Emitted Events:

240 TransparentUpgradeableProxy.0xc77f792f838ae38399ac31acc3348389aeb110ce7bedf3cfdbdd5e6679267970( 0xc77f792f838ae38399ac31acc3348389aeb110ce7bedf3cfdbdd5e6679267970, 0000000000000000000000000000000000000000000000000000000000034116, 0000000000000000000000000000000000000000000000000000000000000015, 0000000000000000000000000000000000000000000000000000000000000000 )
241 TransparentUpgradeableProxy.0x26ba82f907317eedc97d0cbef23de76a43dd6edb563bdb6e9407645b950a7a2d( 0x26ba82f907317eedc97d0cbef23de76a43dd6edb563bdb6e9407645b950a7a2d, 0x000000000000000000000000000000000000000000000000000000000001b754, 0x1f7003cd9dba7fa4cb7ad4c3c16ff0d1b127f1c7e1a11f67be6ea0c9bf59422c, 2efd595359c1e91974116361e2ced6f494231f83761e5f3b487dbec2dcafa6d6, 0ab4bbc3833772b8c324ab5426c7bffb61e180ee2556ffc068374378ecbbd31c )

Account State Difference:

  Address   Before After State Difference Code
0x0d7E906B...54E39AF9B
(Scroll: L1 Message Queue Proxy)
4.954974876790477382 Eth4.954975314970915562 Eth0.00000043818043818
0x356483dC...9886e9074
(Scroll: Batch Finalizer (Old))
51.344231076990959045 Eth
Nonce: 112467
51.326893919641329785 Eth
Nonce: 112468
0.01733715734962926
0xa13BAF47...6DAc1E556
(Scroll: L1 Scroll Chain Proxy)

Execution Trace

TransparentUpgradeableProxy.31fa742d( )
  • ScrollChain.finalizeBatchWithProof( _batchHeader=0x00000000000001B7540000000000000015000000000003412BD1D50A590114A6C6DA44D5553E03BB9E27CB09883F325C8C3D219733C7E2FD212F3C40DB446DDC26C2D9A5E535D4AD9BE6546FA82C5A12D2849BB6F0CBDE367A0000000000000000000000000000000000000000000000000000000000000000, _prevStateRoot=066EE801F6CB109F8E67BD805FDB0B182CC193579A1E9E118BFFAE9A5C3AF315, _postStateRoot=2EFD595359C1E91974116361E2CED6F494231F83761E5F3B487DBEC2DCAFA6D6, _withdrawRoot=0AB4BBC3833772B8C324AB5426C7BFFB61E180EE2556FFC068374378ECBBD31C, _aggrProof=0x000000000000000000000000000000000000000000C35DE2D1B20E74D68827060000000000000000000000000000000000000000002B9BE29C51F43A426EFB310000000000000000000000000000000000000000000000EBAB7A4246F1C60E26000000000000000000000000000000000000000000DFE69FFC8C94234591580D000000000000000000000000000000000000000000281B50B6E68547D967EA19000000000000000000000000000000000000000000000C62C176951D278BE48E000000000000000000000000000000000000000000E7FEB05DE6E952D42455E1000000000000000000000000000000000000000000F640512C46FA40015C574F00000000000000000000000000000000000000000000012B65019A7E0C7A7CEF000000000000000000000000000000000000000000E4D41FECC9B28D375921DD0000000000000000000000000000000000000000000AE6FF5DF9DF192652DEC600000000000000000000000000000000000000000000218A2DBB781001420D0910C565DFDEC216265DF5285B8BAE207BF682D783DD97D7342F42DB4557135CF7108AF2DCF835F245606237A6BC5B222C6D4529FB7FB8926CD79556D3ED07D1C12C0215129EDEBCFEC566F22B029A436FF7F5954CAC432AD9FC0A0392244034060314985471344A5281EB57CACA31BC4A14DF33408BF491227C8E2FD148AA738F14FE3275C413FBA6BAFA346B89958CFE0A2DC9DFC402E553C1B630FA7E2515C5229E56ADB95015520969252A898B0A33574E64C98D8EAF305FE64FA30B1D866F2E02231A2C42860542878DE4BB28141812B13837CEFB56E933E9C413E993304E289A559C44B2B3865FDAB3A2D61883BCCCC0D9021BB49AC54BBB3FC57D9377600C0100A69AFA6C5A2DBA77C42DDC3F76ED62791746A16F7068DA0459B22971E23060D4273055F98BDE35FCB7DD138C3D17ADEB4D7693E6C3A842595EFE86332600000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002025C384CFA0ED8B3D19D05CAF63F30EF8B0572EF29344870056A04A54236E0091120316BB27D9A6BD71E98985EDE672EDE19644984E4FA5B6BF537911ED8705403393FF8BB0F8057E094D6648DB713D1004A20DABA407C18A598257513F725732774D0678E4AE012AC8244C2EA20C8C3F24EBF4823115433F7BC9B800D2CD9011461007016594ABE22D405AD699B3AF10840B54E22E3CF395C9D7DAD172535291FB6775281628E7CDA5B374C972B592FC07BB1F1EAAF69DA0E91F36B620208A61D1982644CC472BC06E53C1547752E2F994541EC6C35D47632470FEA93945F2B1BF3CC91FA735ACA778414DB60D98B887C0CFBEEC5A2E17C0B019A4DBFF7A9C72AD05BFDEFBD5CCF289D07A9302BE29E244D7CA622C3B20F5A6EC0C13805AD1A0440C0945312CB948DA6BD0A5B143B9C7036A83D3D989B9C75A2612061BF0AD41609889FED7DC551E91EBAC77F4F208437376AA79B2D3726D6F27AB22E8C442812FB600536CA73AB1F37BBED37F121F01C7B098D988D542CFB8DBE5DF28A94D1227F20F14D98292B307C1F954EADBEBE9DDCC3AA5F040DA856D538CF5521EB3210ACC6DD18AFFFC6BC5D0D07BB48AD00A8AEF392CB96E2F26FA40B4A949641DE1C3705549C792A8B30DEA2AB9404CD6463557C809A8F6D719CA6BD445B4ADCE920331E9C8F099EFCF0B83EFD0DE2F588A6C55F36D3BC93266E23C29690D7437000000000000000000000000000000000000000000000000000000000000000012828797ACA90B0C72374A8AE830401F00BD9FB2E13E70F2BFF4789AF725B661006DB53007079C285F44420290440ACCAB826546B9BE570CA1358F90D8989C3400DD00C68C5DFBEBDA8B71E71E1CF72AA9B487B782D8826A535C8F0F7538F10192E99B57D960ED95660B7C29167594B22DD6DEC48112EDB2C118ED3F48087B06B0EB8D78EAC1E783D1BBDFE0660A37A6B1AF6A85A7A12292558DA14161A693FB11028B5498540BCE9038F91A60C46F3ACD9D049C3963B3831531E1EACC8729CAF1C2C31002675DC16D33CB9805D14655F68E18A8A098F8F92564BCB0893365BE92F91F65F4510B547637A5DA5D281EE963099FC195795F180F6890D1A15982A4618FAA8125354E2D04AF6BDE8D32D284B1DF2DB7482198E8DC9E78D0CC1B50727164FA645244A8CC9D52620C09AD400CA8D8588FBB9114E1B2BB3065B8636A73A09A57E6568A44949FF0642502727AD8A1A8C45B4B08BBD62D57C9F398E234AE32A16D965DDD26E9B9826248D60EA38CCBD7062670A2429DE4430BA2EADF72D2502D0B5F7ACCB37098D6FAB1F704FF910EA811051E134E8BBD0FDFCF54A327EA023F995A7D9D7AE5DF1E43CE07239CA86279F96C9E48DF3A3C6225279299252B5 )
    • MultipleVersionRollupVerifier.verifyAggregateProof( _batchIndex=112468, _aggrProof=0x000000000000000000000000000000000000000000C35DE2D1B20E74D68827060000000000000000000000000000000000000000002B9BE29C51F43A426EFB310000000000000000000000000000000000000000000000EBAB7A4246F1C60E26000000000000000000000000000000000000000000DFE69FFC8C94234591580D000000000000000000000000000000000000000000281B50B6E68547D967EA19000000000000000000000000000000000000000000000C62C176951D278BE48E000000000000000000000000000000000000000000E7FEB05DE6E952D42455E1000000000000000000000000000000000000000000F640512C46FA40015C574F00000000000000000000000000000000000000000000012B65019A7E0C7A7CEF000000000000000000000000000000000000000000E4D41FECC9B28D375921DD0000000000000000000000000000000000000000000AE6FF5DF9DF192652DEC600000000000000000000000000000000000000000000218A2DBB781001420D0910C565DFDEC216265DF5285B8BAE207BF682D783DD97D7342F42DB4557135CF7108AF2DCF835F245606237A6BC5B222C6D4529FB7FB8926CD79556D3ED07D1C12C0215129EDEBCFEC566F22B029A436FF7F5954CAC432AD9FC0A0392244034060314985471344A5281EB57CACA31BC4A14DF33408BF491227C8E2FD148AA738F14FE3275C413FBA6BAFA346B89958CFE0A2DC9DFC402E553C1B630FA7E2515C5229E56ADB95015520969252A898B0A33574E64C98D8EAF305FE64FA30B1D866F2E02231A2C42860542878DE4BB28141812B13837CEFB56E933E9C413E993304E289A559C44B2B3865FDAB3A2D61883BCCCC0D9021BB49AC54BBB3FC57D9377600C0100A69AFA6C5A2DBA77C42DDC3F76ED62791746A16F7068DA0459B22971E23060D4273055F98BDE35FCB7DD138C3D17ADEB4D7693E6C3A842595EFE86332600000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002025C384CFA0ED8B3D19D05CAF63F30EF8B0572EF29344870056A04A54236E0091120316BB27D9A6BD71E98985EDE672EDE19644984E4FA5B6BF537911ED8705403393FF8BB0F8057E094D6648DB713D1004A20DABA407C18A598257513F725732774D0678E4AE012AC8244C2EA20C8C3F24EBF4823115433F7BC9B800D2CD9011461007016594ABE22D405AD699B3AF10840B54E22E3CF395C9D7DAD172535291FB6775281628E7CDA5B374C972B592FC07BB1F1EAAF69DA0E91F36B620208A61D1982644CC472BC06E53C1547752E2F994541EC6C35D47632470FEA93945F2B1BF3CC91FA735ACA778414DB60D98B887C0CFBEEC5A2E17C0B019A4DBFF7A9C72AD05BFDEFBD5CCF289D07A9302BE29E244D7CA622C3B20F5A6EC0C13805AD1A0440C0945312CB948DA6BD0A5B143B9C7036A83D3D989B9C75A2612061BF0AD41609889FED7DC551E91EBAC77F4F208437376AA79B2D3726D6F27AB22E8C442812FB600536CA73AB1F37BBED37F121F01C7B098D988D542CFB8DBE5DF28A94D1227F20F14D98292B307C1F954EADBEBE9DDCC3AA5F040DA856D538CF5521EB3210ACC6DD18AFFFC6BC5D0D07BB48AD00A8AEF392CB96E2F26FA40B4A949641DE1C3705549C792A8B30DEA2AB9404CD6463557C809A8F6D719CA6BD445B4ADCE920331E9C8F099EFCF0B83EFD0DE2F588A6C55F36D3BC93266E23C29690D7437000000000000000000000000000000000000000000000000000000000000000012828797ACA90B0C72374A8AE830401F00BD9FB2E13E70F2BFF4789AF725B661006DB53007079C285F44420290440ACCAB826546B9BE570CA1358F90D8989C3400DD00C68C5DFBEBDA8B71E71E1CF72AA9B487B782D8826A535C8F0F7538F10192E99B57D960ED95660B7C29167594B22DD6DEC48112EDB2C118ED3F48087B06B0EB8D78EAC1E783D1BBDFE0660A37A6B1AF6A85A7A12292558DA14161A693FB11028B5498540BCE9038F91A60C46F3ACD9D049C3963B3831531E1EACC8729CAF1C2C31002675DC16D33CB9805D14655F68E18A8A098F8F92564BCB0893365BE92F91F65F4510B547637A5DA5D281EE963099FC195795F180F6890D1A15982A4618FAA8125354E2D04AF6BDE8D32D284B1DF2DB7482198E8DC9E78D0CC1B50727164FA645244A8CC9D52620C09AD400CA8D8588FBB9114E1B2BB3065B8636A73A09A57E6568A44949FF0642502727AD8A1A8C45B4B08BBD62D57C9F398E234AE32A16D965DDD26E9B9826248D60EA38CCBD7062670A2429DE4430BA2EADF72D2502D0B5F7ACCB37098D6FAB1F704FF910EA811051E134E8BBD0FDFCF54A327EA023F995A7D9D7AE5DF1E43CE07239CA86279F96C9E48DF3A3C6225279299252B5, _publicInputHash=601F608AEC7401FBDE2E4349E3CAE6E3576EBE54DFC4C9A271275B202FDB0F77 )
      • ZkEvmVerifierV1.verify( aggrProof=0x000000000000000000000000000000000000000000C35DE2D1B20E74D68827060000000000000000000000000000000000000000002B9BE29C51F43A426EFB310000000000000000000000000000000000000000000000EBAB7A4246F1C60E26000000000000000000000000000000000000000000DFE69FFC8C94234591580D000000000000000000000000000000000000000000281B50B6E68547D967EA19000000000000000000000000000000000000000000000C62C176951D278BE48E000000000000000000000000000000000000000000E7FEB05DE6E952D42455E1000000000000000000000000000000000000000000F640512C46FA40015C574F00000000000000000000000000000000000000000000012B65019A7E0C7A7CEF000000000000000000000000000000000000000000E4D41FECC9B28D375921DD0000000000000000000000000000000000000000000AE6FF5DF9DF192652DEC600000000000000000000000000000000000000000000218A2DBB781001420D0910C565DFDEC216265DF5285B8BAE207BF682D783DD97D7342F42DB4557135CF7108AF2DCF835F245606237A6BC5B222C6D4529FB7FB8926CD79556D3ED07D1C12C0215129EDEBCFEC566F22B029A436FF7F5954CAC432AD9FC0A0392244034060314985471344A5281EB57CACA31BC4A14DF33408BF491227C8E2FD148AA738F14FE3275C413FBA6BAFA346B89958CFE0A2DC9DFC402E553C1B630FA7E2515C5229E56ADB95015520969252A898B0A33574E64C98D8EAF305FE64FA30B1D866F2E02231A2C42860542878DE4BB28141812B13837CEFB56E933E9C413E993304E289A559C44B2B3865FDAB3A2D61883BCCCC0D9021BB49AC54BBB3FC57D9377600C0100A69AFA6C5A2DBA77C42DDC3F76ED62791746A16F7068DA0459B22971E23060D4273055F98BDE35FCB7DD138C3D17ADEB4D7693E6C3A842595EFE86332600000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002025C384CFA0ED8B3D19D05CAF63F30EF8B0572EF29344870056A04A54236E0091120316BB27D9A6BD71E98985EDE672EDE19644984E4FA5B6BF537911ED8705403393FF8BB0F8057E094D6648DB713D1004A20DABA407C18A598257513F725732774D0678E4AE012AC8244C2EA20C8C3F24EBF4823115433F7BC9B800D2CD9011461007016594ABE22D405AD699B3AF10840B54E22E3CF395C9D7DAD172535291FB6775281628E7CDA5B374C972B592FC07BB1F1EAAF69DA0E91F36B620208A61D1982644CC472BC06E53C1547752E2F994541EC6C35D47632470FEA93945F2B1BF3CC91FA735ACA778414DB60D98B887C0CFBEEC5A2E17C0B019A4DBFF7A9C72AD05BFDEFBD5CCF289D07A9302BE29E244D7CA622C3B20F5A6EC0C13805AD1A0440C0945312CB948DA6BD0A5B143B9C7036A83D3D989B9C75A2612061BF0AD41609889FED7DC551E91EBAC77F4F208437376AA79B2D3726D6F27AB22E8C442812FB600536CA73AB1F37BBED37F121F01C7B098D988D542CFB8DBE5DF28A94D1227F20F14D98292B307C1F954EADBEBE9DDCC3AA5F040DA856D538CF5521EB3210ACC6DD18AFFFC6BC5D0D07BB48AD00A8AEF392CB96E2F26FA40B4A949641DE1C3705549C792A8B30DEA2AB9404CD6463557C809A8F6D719CA6BD445B4ADCE920331E9C8F099EFCF0B83EFD0DE2F588A6C55F36D3BC93266E23C29690D7437000000000000000000000000000000000000000000000000000000000000000012828797ACA90B0C72374A8AE830401F00BD9FB2E13E70F2BFF4789AF725B661006DB53007079C285F44420290440ACCAB826546B9BE570CA1358F90D8989C3400DD00C68C5DFBEBDA8B71E71E1CF72AA9B487B782D8826A535C8F0F7538F10192E99B57D960ED95660B7C29167594B22DD6DEC48112EDB2C118ED3F48087B06B0EB8D78EAC1E783D1BBDFE0660A37A6B1AF6A85A7A12292558DA14161A693FB11028B5498540BCE9038F91A60C46F3ACD9D049C3963B3831531E1EACC8729CAF1C2C31002675DC16D33CB9805D14655F68E18A8A098F8F92564BCB0893365BE92F91F65F4510B547637A5DA5D281EE963099FC195795F180F6890D1A15982A4618FAA8125354E2D04AF6BDE8D32D284B1DF2DB7482198E8DC9E78D0CC1B50727164FA645244A8CC9D52620C09AD400CA8D8588FBB9114E1B2BB3065B8636A73A09A57E6568A44949FF0642502727AD8A1A8C45B4B08BBD62D57C9F398E234AE32A16D965DDD26E9B9826248D60EA38CCBD7062670A2429DE4430BA2EADF72D2502D0B5F7ACCB37098D6FAB1F704FF910EA811051E134E8BBD0FDFCF54A327EA023F995A7D9D7AE5DF1E43CE07239CA86279F96C9E48DF3A3C6225279299252B5, publicInputHash=601F608AEC7401FBDE2E4349E3CAE6E3576EBE54DFC4C9A271275B202FDB0F77 )
        • Scroll: L1 Plonk Verifier.00000000( )
          • Null: 0x000...005.00000000( )
          • Null: 0x000...005.00000000( )
          • Null: 0x000...005.00000000( )
          • Null: 0x000...007.00000000( )
          • Null: 0x000...006.0d0f7c56( )
          • Null: 0x000...007.2e02231a( )
          • Null: 0x000...006.09240dcc( )
          • Null: 0x000...007.0c0100a6( )
          • Null: 0x000...006.17ad8faf( )
          • Null: 0x000...007.2c021512( )
          • Null: 0x000...006.02e02fa9( )
          • Null: 0x000...007.14fe3275( )
          • Null: 0x000...006.164be49d( )
          • Null: 0x000...007.15084476( )
          • Null: 0x000...006.14869645( )
          • Null: 0x000...007.030a8de1( )
          • Null: 0x000...006.07325fae( )
          • Null: 0x000...007.2d8725ea( )
          • Null: 0x000...006.2469b0df( )
          • Null: 0x000...007.0a85625d( )
          • Null: 0x000...006.0511cb0d( )
          • Null: 0x000...007.04972ee1( )
          • Null: 0x000...006.04390cea( )
          • Null: 0x000...007.0c8294e9( )
          • Null: 0x000...006.1047490a( )
          • Null: 0x000...007.0e455b2b( )
          • Null: 0x000...006.1eb7a578( )
          • Null: 0x000...007.025c384c( )
          • Null: 0x000...006.1377e7ae( )
          • Null: 0x000...007.03393ff8( )
          • Null: 0x000...006.02cec032( )
          • Null: 0x000...007.14610070( )
          • Null: 0x000...006.24ff6a80( )
          • Null: 0x000...007.1d198264( )
          • Null: 0x000...006.0f3366e7( )
          • Null: 0x000...007.00000000( )
          • Null: 0x000...006.2a0da259( )
          • Null: 0x000...007.09a57e65( )
          • Null: 0x000...006.0812f52f( )
          • Null: 0x000...007.02d0b5f7( )
          • Null: 0x000...006.0e2d5f1a( )
          • Null: 0x000...007.00ebab7a( )
          • Null: 0x000...006.20655598( )
          • Null: 0x000...007.012b6501( )
          • Null: 0x000...006.02d0b5f7( )
          • Null: 0x000...008.285fe51a( )
          • TransparentUpgradeableProxy.55f613ce( )
            • L1MessageQueueWithGasPriceOracle.popCrossDomainMessage( _startIndex=213270, _count=21, _skippedBitmap=0 )
              finalizeBatchWithProof[ScrollChain (ln:1045)]
              File 1 of 6: 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 6: 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 3 of 6: 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.16;
              interface IL1MessageQueue {
                  /**********
                   * 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 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 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 finalized 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 Drop a skipped message from the queue.
                  function dropCrossDomainMessage(uint256 index) external;
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              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 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);
                  /**********
                   * Errors *
                   **********/
                  /// @dev Thrown when the given address is `address(0)`.
                  error ErrorZeroAddress();
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @notice The latest finalized batch index.
                  function lastFinalizedBatchIndex() external view returns (uint256);
                  /// @notice Return the batch hash of a committed batch.
                  /// @param batchIndex The index of the batch.
                  function committedBatches(uint256 batchIndex) external view returns (bytes32);
                  /// @notice Return the state root of a committed batch.
                  /// @param batchIndex The index of the batch.
                  function finalizedStateRoots(uint256 batchIndex) external view returns (bytes32);
                  /// @notice Return the message root of a committed batch.
                  /// @param batchIndex The index of the batch.
                  function withdrawRoots(uint256 batchIndex) external view returns (bytes32);
                  /// @notice Return whether the batch is finalized by batch index.
                  /// @param batchIndex The index of the batch.
                  function isBatchFinalized(uint256 batchIndex) external view returns (bool);
                  /*****************************
                   * Public Mutating Functions *
                   *****************************/
                  /// @notice Commit a batch of transactions on layer 1.
                  ///
                  /// @param version The version of current batch.
                  /// @param parentBatchHeader The header of parent batch, see the comments of `BatchHeaderV0Codec`.
                  /// @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.
                  function commitBatch(
                      uint8 version,
                      bytes calldata parentBatchHeader,
                      bytes[] memory chunks,
                      bytes calldata skippedL1MessageBitmap
                  ) external;
                  /// @notice Revert a pending batch.
                  /// @dev one can only revert unfinalized batches.
                  /// @param batchHeader The header of current batch, see the encoding in comments of `commitBatch`.
                  /// @param count The number of subsequent batches to revert, including current batch.
                  function revertBatch(bytes calldata batchHeader, uint256 count) external;
                  /// @notice Finalize a committed batch on layer 1.
                  /// @param batchHeader The header of current batch, see the encoding in comments of `commitBatch.
                  /// @param prevStateRoot The state root of parent batch.
                  /// @param postStateRoot The state root of current batch.
                  /// @param withdrawRoot The withdraw trie root of current batch.
                  /// @param aggrProof The aggregation proof for current batch.
                  function finalizeBatchWithProof(
                      bytes calldata batchHeader,
                      bytes32 prevStateRoot,
                      bytes32 postStateRoot,
                      bytes32 withdrawRoot,
                      bytes calldata aggrProof
                  ) external;
              }
              // SPDX-License-Identifier: MIT
              pragma solidity =0.8.16;
              import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
              import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
              import {IL1MessageQueue} from "./IL1MessageQueue.sol";
              import {IScrollChain} from "./IScrollChain.sol";
              import {BatchHeaderV0Codec} from "../../libraries/codec/BatchHeaderV0Codec.sol";
              import {ChunkCodec} from "../../libraries/codec/ChunkCodec.sol";
              import {IRollupVerifier} from "../../libraries/verifier/IRollupVerifier.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 {
                  /**********
                   * Events *
                   **********/
                  /// @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);
                  /*************
                   * Constants *
                   *************/
                  /// @notice The chain id of the corresponding layer 2 chain.
                  uint64 public immutable layer2ChainId;
                  /// @notice The address of L1MessageQueue contract.
                  address public immutable messageQueue;
                  /// @notice The address of RollupVerifier.
                  address public immutable verifier;
                  /*************
                   * 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;
                  /// @inheritdoc IScrollChain
                  uint256 public override lastFinalizedBatchIndex;
                  /// @inheritdoc IScrollChain
                  mapping(uint256 => bytes32) public override committedBatches;
                  /// @inheritdoc IScrollChain
                  mapping(uint256 => bytes32) public override finalizedStateRoots;
                  /// @inheritdoc IScrollChain
                  mapping(uint256 => bytes32) public override withdrawRoots;
                  /**********************
                   * Function Modifiers *
                   **********************/
                  modifier OnlySequencer() {
                      // @note In the decentralized mode, it should be only called by a list of validator.
                      require(isSequencer[_msgSender()], "caller not sequencer");
                      _;
                  }
                  modifier OnlyProver() {
                      require(isProver[_msgSender()], "caller not prover");
                      _;
                  }
                  /***************
                   * Constructor *
                   ***************/
                  /// @notice Constructor for `ScrollChain` implementation contract.
                  ///
                  /// @param _chainId The chain id of L2.
                  /// @param _messageQueue The address of `L1MessageQueue` contract.
                  /// @param _verifier The address of zkevm verifier contract.
                  constructor(
                      uint64 _chainId,
                      address _messageQueue,
                      address _verifier
                  ) {
                      if (_messageQueue == address(0) || _verifier == address(0)) {
                          revert ErrorZeroAddress();
                      }
                      _disableInitializers();
                      layer2ChainId = _chainId;
                      messageQueue = _messageQueue;
                      verifier = _verifier;
                  }
                  /// @notice Initialize the storage of ScrollChain.
                  ///
                  /// @dev The parameters `_messageQueue` 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
                  ) public initializer {
                      OwnableUpgradeable.__Ownable_init();
                      maxNumTxInChunk = _maxNumTxInChunk;
                      __verifier = _verifier;
                      __messageQueue = _messageQueue;
                      emit UpdateMaxNumTxInChunk(0, _maxNumTxInChunk);
                  }
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @inheritdoc IScrollChain
                  function isBatchFinalized(uint256 _batchIndex) external view override returns (bool) {
                      return _batchIndex <= lastFinalizedBatchIndex;
                  }
                  /*****************************
                   * Public Mutating Functions *
                   *****************************/
                  /// @notice Import layer 2 genesis block
                  function importGenesisBatch(bytes calldata _batchHeader, bytes32 _stateRoot) external {
                      // check genesis batch header length
                      require(_stateRoot != bytes32(0), "zero state root");
                      // check whether the genesis batch is imported
                      require(finalizedStateRoots[0] == bytes32(0), "Genesis batch imported");
                      (uint256 memPtr, bytes32 _batchHash) = _loadBatchHeader(_batchHeader);
                      // check all fields except `dataHash` and `lastBlockHash` are zero
                      unchecked {
                          uint256 sum = BatchHeaderV0Codec.version(memPtr) +
                              BatchHeaderV0Codec.batchIndex(memPtr) +
                              BatchHeaderV0Codec.l1MessagePopped(memPtr) +
                              BatchHeaderV0Codec.totalL1MessagePopped(memPtr);
                          require(sum == 0, "not all fields are zero");
                      }
                      require(BatchHeaderV0Codec.dataHash(memPtr) != bytes32(0), "zero data hash");
                      require(BatchHeaderV0Codec.parentBatchHash(memPtr) == bytes32(0), "nonzero parent batch hash");
                      committedBatches[0] = _batchHash;
                      finalizedStateRoots[0] = _stateRoot;
                      emit CommitBatch(0, _batchHash);
                      emit FinalizeBatch(0, _batchHash, _stateRoot, bytes32(0));
                  }
                  /// @inheritdoc IScrollChain
                  function commitBatch(
                      uint8 _version,
                      bytes calldata _parentBatchHeader,
                      bytes[] memory _chunks,
                      bytes calldata _skippedL1MessageBitmap
                  ) external override OnlySequencer whenNotPaused {
                      require(_version == 0, "invalid version");
                      // check whether the batch is empty
                      uint256 _chunksLength = _chunks.length;
                      require(_chunksLength > 0, "batch is empty");
                      // The overall memory layout in this function is organized as follows
                      // +---------------------+-------------------+------------------+
                      // | parent batch header | chunk data hashes | new batch header |
                      // +---------------------+-------------------+------------------+
                      // ^                     ^                   ^
                      // batchPtr              dataPtr             newBatchPtr (re-use var batchPtr)
                      //
                      // 1. We copy the parent batch header from calldata to memory starting at batchPtr
                      // 2. We store `_chunksLength` number of Keccak hashes starting at `dataPtr`. Each Keccak
                      //    hash corresponds to the data hash of a chunk. So we reserve the memory region from
                      //    `dataPtr` to `dataPtr + _chunkLength * 32` for the chunk data hashes.
                      // 3. The memory starting at `newBatchPtr` is used to store the new batch header and compute
                      //    the batch hash.
                      // the variable `batchPtr` will be reused later for the current batch
                      (uint256 batchPtr, bytes32 _parentBatchHash) = _loadBatchHeader(_parentBatchHeader);
                      uint256 _batchIndex = BatchHeaderV0Codec.batchIndex(batchPtr);
                      uint256 _totalL1MessagesPoppedOverall = BatchHeaderV0Codec.totalL1MessagePopped(batchPtr);
                      require(committedBatches[_batchIndex] == _parentBatchHash, "incorrect parent batch hash");
                      require(committedBatches[_batchIndex + 1] == 0, "batch already committed");
                      // load `dataPtr` and reserve the memory region for chunk data hashes
                      uint256 dataPtr;
                      assembly {
                          dataPtr := mload(0x40)
                          mstore(0x40, add(dataPtr, mul(_chunksLength, 32)))
                      }
                      // compute the data hash for each chunk
                      uint256 _totalL1MessagesPoppedInBatch;
                      for (uint256 i = 0; i < _chunksLength; i++) {
                          uint256 _totalNumL1MessagesInChunk = _commitChunk(
                              dataPtr,
                              _chunks[i],
                              _totalL1MessagesPoppedInBatch,
                              _totalL1MessagesPoppedOverall,
                              _skippedL1MessageBitmap
                          );
                          unchecked {
                              _totalL1MessagesPoppedInBatch += _totalNumL1MessagesInChunk;
                              _totalL1MessagesPoppedOverall += _totalNumL1MessagesInChunk;
                              dataPtr += 32;
                          }
                      }
                      // check the length of bitmap
                      unchecked {
                          require(
                              ((_totalL1MessagesPoppedInBatch + 255) / 256) * 32 == _skippedL1MessageBitmap.length,
                              "wrong bitmap length"
                          );
                      }
                      // compute the data hash for current batch
                      bytes32 _dataHash;
                      assembly {
                          let dataLen := mul(_chunksLength, 0x20)
                          _dataHash := keccak256(sub(dataPtr, dataLen), dataLen)
                          batchPtr := mload(0x40) // reset batchPtr
                          _batchIndex := add(_batchIndex, 1) // increase batch index
                      }
                      // store entries, the order matters
                      BatchHeaderV0Codec.storeVersion(batchPtr, _version);
                      BatchHeaderV0Codec.storeBatchIndex(batchPtr, _batchIndex);
                      BatchHeaderV0Codec.storeL1MessagePopped(batchPtr, _totalL1MessagesPoppedInBatch);
                      BatchHeaderV0Codec.storeTotalL1MessagePopped(batchPtr, _totalL1MessagesPoppedOverall);
                      BatchHeaderV0Codec.storeDataHash(batchPtr, _dataHash);
                      BatchHeaderV0Codec.storeParentBatchHash(batchPtr, _parentBatchHash);
                      BatchHeaderV0Codec.storeSkippedBitmap(batchPtr, _skippedL1MessageBitmap);
                      // compute batch hash
                      bytes32 _batchHash = BatchHeaderV0Codec.computeBatchHash(batchPtr, 89 + _skippedL1MessageBitmap.length);
                      committedBatches[_batchIndex] = _batchHash;
                      emit CommitBatch(_batchIndex, _batchHash);
                  }
                  /// @inheritdoc IScrollChain
                  /// @dev If the owner want to revert a sequence of batches by sending multiple transactions,
                  ///      make sure to revert recent batches first.
                  function revertBatch(bytes calldata _batchHeader, uint256 _count) external onlyOwner {
                      require(_count > 0, "count must be nonzero");
                      (uint256 memPtr, bytes32 _batchHash) = _loadBatchHeader(_batchHeader);
                      // check batch hash
                      uint256 _batchIndex = BatchHeaderV0Codec.batchIndex(memPtr);
                      require(committedBatches[_batchIndex] == _batchHash, "incorrect batch hash");
                      // make sure no gap is left when reverting from the ending to the beginning.
                      require(committedBatches[_batchIndex + _count] == bytes32(0), "reverting must start from the ending");
                      // check finalization
                      require(_batchIndex > lastFinalizedBatchIndex, "can only revert unfinalized batch");
                      while (_count > 0) {
                          committedBatches[_batchIndex] = bytes32(0);
                          emit RevertBatch(_batchIndex, _batchHash);
                          unchecked {
                              _batchIndex += 1;
                              _count -= 1;
                          }
                          _batchHash = committedBatches[_batchIndex];
                          if (_batchHash == bytes32(0)) break;
                      }
                  }
                  /// @inheritdoc IScrollChain
                  function finalizeBatchWithProof(
                      bytes calldata _batchHeader,
                      bytes32 _prevStateRoot,
                      bytes32 _postStateRoot,
                      bytes32 _withdrawRoot,
                      bytes calldata _aggrProof
                  ) external override OnlyProver whenNotPaused {
                      require(_prevStateRoot != bytes32(0), "previous state root is zero");
                      require(_postStateRoot != bytes32(0), "new state root is zero");
                      // compute batch hash and verify
                      (uint256 memPtr, bytes32 _batchHash) = _loadBatchHeader(_batchHeader);
                      bytes32 _dataHash = BatchHeaderV0Codec.dataHash(memPtr);
                      uint256 _batchIndex = BatchHeaderV0Codec.batchIndex(memPtr);
                      require(committedBatches[_batchIndex] == _batchHash, "incorrect batch hash");
                      // verify previous state root.
                      require(finalizedStateRoots[_batchIndex - 1] == _prevStateRoot, "incorrect previous state root");
                      // avoid duplicated verification
                      require(finalizedStateRoots[_batchIndex] == bytes32(0), "batch already verified");
                      // compute public input hash
                      bytes32 _publicInputHash = keccak256(
                          abi.encodePacked(layer2ChainId, _prevStateRoot, _postStateRoot, _withdrawRoot, _dataHash)
                      );
                      // verify batch
                      IRollupVerifier(verifier).verifyAggregateProof(_batchIndex, _aggrProof, _publicInputHash);
                      // check and update lastFinalizedBatchIndex
                      unchecked {
                          require(lastFinalizedBatchIndex + 1 == _batchIndex, "incorrect batch index");
                          lastFinalizedBatchIndex = _batchIndex;
                      }
                      // record state root and withdraw root
                      finalizedStateRoots[_batchIndex] = _postStateRoot;
                      withdrawRoots[_batchIndex] = _withdrawRoot;
                      // Pop finalized and non-skipped message from L1MessageQueue.
                      uint256 _l1MessagePopped = BatchHeaderV0Codec.l1MessagePopped(memPtr);
                      if (_l1MessagePopped > 0) {
                          IL1MessageQueue _queue = IL1MessageQueue(messageQueue);
                          unchecked {
                              uint256 _startIndex = BatchHeaderV0Codec.totalL1MessagePopped(memPtr) - _l1MessagePopped;
                              for (uint256 i = 0; i < _l1MessagePopped; i += 256) {
                                  uint256 _count = 256;
                                  if (_l1MessagePopped - i < _count) {
                                      _count = _l1MessagePopped - i;
                                  }
                                  uint256 _skippedBitmap = BatchHeaderV0Codec.skippedBitmap(memPtr, i / 256);
                                  _queue.popCrossDomainMessage(_startIndex, _count, _skippedBitmap);
                                  _startIndex += 256;
                              }
                          }
                      }
                      emit FinalizeBatch(_batchIndex, _batchHash, _postStateRoot, _withdrawRoot);
                  }
                  /************************
                   * 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.
                      require(_account.code.length == 0, "not EOA");
                      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.
                      require(_account.code.length == 0, "not EOA");
                      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();
                      }
                  }
                  /**********************
                   * Internal Functions *
                   **********************/
                  /// @dev Internal function to load batch header from calldata to memory.
                  /// @param _batchHeader The batch header in calldata.
                  /// @return memPtr The start memory offset of loaded batch header.
                  /// @return _batchHash The hash of the loaded batch header.
                  function _loadBatchHeader(bytes calldata _batchHeader) internal pure returns (uint256 memPtr, bytes32 _batchHash) {
                      // load to memory
                      uint256 _length;
                      (memPtr, _length) = BatchHeaderV0Codec.loadAndValidate(_batchHeader);
                      // compute batch hash
                      _batchHash = BatchHeaderV0Codec.computeBatchHash(memPtr, _length);
                  }
                  /// @dev Internal function to commit a chunk.
                  /// @param memPtr The start memory offset to store list of `dataHash`.
                  /// @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 _totalNumL1MessagesInChunk The total number of L1 message popped in current chunk
                  function _commitChunk(
                      uint256 memPtr,
                      bytes memory _chunk,
                      uint256 _totalL1MessagesPoppedInBatch,
                      uint256 _totalL1MessagesPoppedOverall,
                      bytes calldata _skippedL1MessageBitmap
                  ) internal view returns (uint256 _totalNumL1MessagesInChunk) {
                      uint256 chunkPtr;
                      uint256 startDataPtr;
                      uint256 dataPtr;
                      uint256 blockPtr;
                      assembly {
                          dataPtr := mload(0x40)
                          startDataPtr := dataPtr
                          chunkPtr := add(_chunk, 0x20) // skip chunkLength
                          blockPtr := add(chunkPtr, 1) // skip numBlocks
                      }
                      uint256 _numBlocks = ChunkCodec.validateChunkLength(chunkPtr, _chunk.length);
                      // concatenate block contexts, use scope to avoid stack too deep
                      {
                          uint256 _totalTransactionsInChunk;
                          for (uint256 i = 0; i < _numBlocks; i++) {
                              dataPtr = ChunkCodec.copyBlockContext(chunkPtr, dataPtr, i);
                              uint256 _numTransactionsInBlock = ChunkCodec.numTransactions(blockPtr);
                              unchecked {
                                  _totalTransactionsInChunk += _numTransactionsInBlock;
                                  blockPtr += ChunkCodec.BLOCK_CONTEXT_LENGTH;
                              }
                          }
                          assembly {
                              mstore(0x40, add(dataPtr, mul(_totalTransactionsInChunk, 0x20))) // reserve memory for tx hashes
                          }
                      }
                      // It is used to compute the actual number of transactions in chunk.
                      uint256 txHashStartDataPtr;
                      assembly {
                          txHashStartDataPtr := dataPtr
                          blockPtr := add(chunkPtr, 1) // reset block ptr
                      }
                      // concatenate tx hashes
                      uint256 l2TxPtr = ChunkCodec.l2TxPtr(chunkPtr, _numBlocks);
                      while (_numBlocks > 0) {
                          // concatenate l1 message hashes
                          uint256 _numL1MessagesInBlock = ChunkCodec.numL1Messages(blockPtr);
                          dataPtr = _loadL1MessageHashes(
                              dataPtr,
                              _numL1MessagesInBlock,
                              _totalL1MessagesPoppedInBatch,
                              _totalL1MessagesPoppedOverall,
                              _skippedL1MessageBitmap
                          );
                          // concatenate l2 transaction hashes
                          uint256 _numTransactionsInBlock = ChunkCodec.numTransactions(blockPtr);
                          require(_numTransactionsInBlock >= _numL1MessagesInBlock, "num txs less than num L1 msgs");
                          for (uint256 j = _numL1MessagesInBlock; j < _numTransactionsInBlock; j++) {
                              bytes32 txHash;
                              (txHash, l2TxPtr) = ChunkCodec.loadL2TxHash(l2TxPtr);
                              assembly {
                                  mstore(dataPtr, txHash)
                                  dataPtr := add(dataPtr, 0x20)
                              }
                          }
                          unchecked {
                              _totalNumL1MessagesInChunk += _numL1MessagesInBlock;
                              _totalL1MessagesPoppedInBatch += _numL1MessagesInBlock;
                              _totalL1MessagesPoppedOverall += _numL1MessagesInBlock;
                              _numBlocks -= 1;
                              blockPtr += ChunkCodec.BLOCK_CONTEXT_LENGTH;
                          }
                      }
                      // check the actual number of transactions in the chunk
                      require((dataPtr - txHashStartDataPtr) / 32 <= maxNumTxInChunk, "too many txs in one chunk");
                      // check chunk has correct length
                      require(l2TxPtr - chunkPtr == _chunk.length, "incomplete l2 transaction data");
                      // compute data hash and store to memory
                      assembly {
                          let dataHash := keccak256(startDataPtr, sub(dataPtr, startDataPtr))
                          mstore(memPtr, dataHash)
                      }
                      return _totalNumL1MessagesInChunk;
                  }
                  /// @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;
                      IL1MessageQueue _messageQueue = IL1MessageQueue(messageQueue);
                      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;
                          require(((_bitmap >> rem) & 1) == 0, "cannot skip last L1 message");
                      }
                      return _ptr;
                  }
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              // 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 message 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 {
                  /// @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;
                      require(length >= 89, "batch header length too small");
                      // 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.l1MessagePopped(batchPtr);
                      unchecked {
                          require(length == 89 + ((_l1MessagePopped + 255) / 256) * 32, "wrong bitmap length");
                      }
                  }
                  /// @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 version(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 batchIndex(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 l1MessagePopped(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 the number of L1 messages popped before this batch.
                  function totalL1MessagePopped(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 dataHash(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 parentBatchHash(uint256 batchPtr) internal pure returns (bytes32 _parentBatchHash) {
                      assembly {
                          _parentBatchHash := mload(add(batchPtr, 57))
                      }
                  }
                  /// @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 skippedBitmap(uint256 batchPtr, uint256 index) internal pure returns (uint256 _bitmap) {
                      assembly {
                          batchPtr := add(batchPtr, 89)
                          _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, 89), _skippedL1MessageBitmap.offset, _skippedL1MessageBitmap.length)
                      }
                  }
                  /// @notice Compute the batch hash.
                  /// @dev Caller should make sure that the encoded batch header is correct.
                  ///
                  /// @param batchPtr The memory offset of the encoded batch header.
                  /// @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.16;
              /// @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. Currently, it is always 0, because we disable EIP-1559.
              ///   * 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 ChunkCodec {
                  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 = numBlocks(chunkPtr);
                      // should contain at least one block
                      require(_numBlocks > 0, "no block in chunk");
                      // should contain at least the number of the blocks and block contexts
                      require(_length >= 1 + _numBlocks * BLOCK_CONTEXT_LENGTH, "invalid chunk length");
                  }
                  /// @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 l2TxPtr(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 numBlocks(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)))
                          mstore(dstPtr, mload(chunkPtr)) // first 32 bytes
                          mstore(
                              add(dstPtr, 0x20),
                              and(mload(add(chunkPtr, 0x20)), 0xffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000)
                          ) // next 26 bytes
                          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 numTransactions(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 numL1Messages(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.16;
              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;
              }
              

              File 4 of 6: MultipleVersionRollupVerifier
              // SPDX-License-Identifier: MIT
              pragma solidity =0.8.16;
              import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
              import {IScrollChain} from "./IScrollChain.sol";
              import {IRollupVerifier} from "../../libraries/verifier/IRollupVerifier.sol";
              import {IZkEvmVerifier} from "../../libraries/verifier/IZkEvmVerifier.sol";
              contract MultipleVersionRollupVerifier is IRollupVerifier, Ownable {
                  /**********
                   * Events *
                   **********/
                  /// @notice Emitted when the address of verifier is updated.
                  /// @param startBatchIndex The start batch index when the verifier will be used.
                  /// @param verifier The address of new verifier.
                  event UpdateVerifier(uint256 startBatchIndex, address verifier);
                  /***********
                   * Structs *
                   ***********/
                  struct Verifier {
                      // The start batch index for the verifier.
                      uint64 startBatchIndex;
                      // The address of zkevm verifier.
                      address verifier;
                  }
                  /*************
                   * Variables *
                   *************/
                  /// @notice The list of legacy zkevm verifier, sorted by batchIndex in increasing order.
                  Verifier[] public legacyVerifiers;
                  /// @notice The lastest used zkevm verifier.
                  Verifier public latestVerifier;
                  /// @notice The address of ScrollChain contract.
                  address public scrollChain;
                  /***************
                   * Constructor *
                   ***************/
                  constructor(address _verifier) {
                      require(_verifier != address(0), "zero verifier address");
                      latestVerifier.verifier = _verifier;
                  }
                  function initialize(address _scrollChain) external onlyOwner {
                      require(scrollChain == address(0), "initialized");
                      scrollChain = _scrollChain;
                  }
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @notice Return the number of legacy verifiers.
                  function legacyVerifiersLength() external view returns (uint256) {
                      return legacyVerifiers.length;
                  }
                  /// @notice Compute the verifier should be used for specific batch.
                  /// @param _batchIndex The batch index to query.
                  function getVerifier(uint256 _batchIndex) public view returns (address) {
                      // Normally, we will use the latest verifier.
                      Verifier memory _verifier = latestVerifier;
                      if (_verifier.startBatchIndex > _batchIndex) {
                          uint256 _length = legacyVerifiers.length;
                          // In most case, only last few verifier will be used by `ScrollChain`.
                          // So, we use linear search instead of binary search.
                          unchecked {
                              for (uint256 i = _length; i > 0; --i) {
                                  _verifier = legacyVerifiers[i - 1];
                                  if (_verifier.startBatchIndex <= _batchIndex) break;
                              }
                          }
                      }
                      return _verifier.verifier;
                  }
                  /*****************************
                   * Public Mutating Functions *
                   *****************************/
                  /// @inheritdoc IRollupVerifier
                  function verifyAggregateProof(
                      uint256 _batchIndex,
                      bytes calldata _aggrProof,
                      bytes32 _publicInputHash
                  ) external view override {
                      address _verifier = getVerifier(_batchIndex);
                      IZkEvmVerifier(_verifier).verify(_aggrProof, _publicInputHash);
                  }
                  /************************
                   * Restricted Functions *
                   ************************/
                  /// @notice Update the address of zkevm verifier.
                  /// @param _startBatchIndex The start batch index when the verifier will be used.
                  /// @param _verifier The address of new verifier.
                  function updateVerifier(uint64 _startBatchIndex, address _verifier) external onlyOwner {
                      require(_startBatchIndex > IScrollChain(scrollChain).lastFinalizedBatchIndex(), "start batch index finalized");
                      Verifier memory _latestVerifier = latestVerifier;
                      require(_startBatchIndex >= _latestVerifier.startBatchIndex, "start batch index too small");
                      require(_verifier != address(0), "zero verifier address");
                      if (_latestVerifier.startBatchIndex < _startBatchIndex) {
                          legacyVerifiers.push(_latestVerifier);
                          _latestVerifier.startBatchIndex = _startBatchIndex;
                      }
                      _latestVerifier.verifier = _verifier;
                      latestVerifier = _latestVerifier;
                      emit UpdateVerifier(_startBatchIndex, _verifier);
                  }
              }
              // SPDX-License-Identifier: MIT
              // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
              pragma solidity ^0.8.0;
              import "../utils/Context.sol";
              /**
               * @dev Contract module which provides a basic access control mechanism, where
               * there is an account (an owner) that can be granted exclusive access to
               * specific functions.
               *
               * By default, the owner account will be the one that deploys the contract. This
               * can later be changed with {transferOwnership}.
               *
               * This module is used through inheritance. It will make available the modifier
               * `onlyOwner`, which can be applied to your functions to restrict their use to
               * the owner.
               */
              abstract contract Ownable is Context {
                  address private _owner;
                  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                  /**
                   * @dev Initializes the contract setting the deployer as the initial owner.
                   */
                  constructor() {
                      _transferOwnership(_msgSender());
                  }
                  /**
                   * @dev Throws if called by any account other than the owner.
                   */
                  modifier onlyOwner() {
                      _checkOwner();
                      _;
                  }
                  /**
                   * @dev Returns the address of the current owner.
                   */
                  function owner() public view virtual returns (address) {
                      return _owner;
                  }
                  /**
                   * @dev Throws if the sender is not the owner.
                   */
                  function _checkOwner() internal view virtual {
                      require(owner() == _msgSender(), "Ownable: caller is not the owner");
                  }
                  /**
                   * @dev Leaves the contract without owner. It will not be possible to call
                   * `onlyOwner` functions. Can only be called by the current owner.
                   *
                   * NOTE: Renouncing ownership will leave the contract without an owner,
                   * thereby disabling any functionality that is only available to the owner.
                   */
                  function renounceOwnership() public virtual onlyOwner {
                      _transferOwnership(address(0));
                  }
                  /**
                   * @dev Transfers ownership of the contract to a new account (`newOwner`).
                   * Can only be called by the current owner.
                   */
                  function transferOwnership(address newOwner) public virtual onlyOwner {
                      require(newOwner != address(0), "Ownable: new owner is the zero address");
                      _transferOwnership(newOwner);
                  }
                  /**
                   * @dev Transfers ownership of the contract to a new account (`newOwner`).
                   * Internal function without access restriction.
                   */
                  function _transferOwnership(address newOwner) internal virtual {
                      address oldOwner = _owner;
                      _owner = newOwner;
                      emit OwnershipTransferred(oldOwner, newOwner);
                  }
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              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 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);
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @notice The latest finalized batch index.
                  function lastFinalizedBatchIndex() external view returns (uint256);
                  /// @notice Return the batch hash of a committed batch.
                  /// @param batchIndex The index of the batch.
                  function committedBatches(uint256 batchIndex) external view returns (bytes32);
                  /// @notice Return the state root of a committed batch.
                  /// @param batchIndex The index of the batch.
                  function finalizedStateRoots(uint256 batchIndex) external view returns (bytes32);
                  /// @notice Return the message root of a committed batch.
                  /// @param batchIndex The index of the batch.
                  function withdrawRoots(uint256 batchIndex) external view returns (bytes32);
                  /// @notice Return whether the batch is finalized by batch index.
                  /// @param batchIndex The index of the batch.
                  function isBatchFinalized(uint256 batchIndex) external view returns (bool);
                  /*****************************
                   * Public Mutating Functions *
                   *****************************/
                  /// @notice Commit a batch of transactions on layer 1.
                  ///
                  /// @param version The version of current batch.
                  /// @param parentBatchHeader The header of parent batch, see the comments of `BatchHeaderV0Codec`.
                  /// @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.
                  function commitBatch(
                      uint8 version,
                      bytes calldata parentBatchHeader,
                      bytes[] memory chunks,
                      bytes calldata skippedL1MessageBitmap
                  ) external;
                  /// @notice Revert a pending batch.
                  /// @dev one can only revert unfinalized batches.
                  /// @param batchHeader The header of current batch, see the encoding in comments of `commitBatch`.
                  /// @param count The number of subsequent batches to revert, including current batch.
                  function revertBatch(bytes calldata batchHeader, uint256 count) external;
                  /// @notice Finalize a committed batch on layer 1.
                  /// @param batchHeader The header of current batch, see the encoding in comments of `commitBatch.
                  /// @param prevStateRoot The state root of parent batch.
                  /// @param postStateRoot The state root of current batch.
                  /// @param withdrawRoot The withdraw trie root of current batch.
                  /// @param aggrProof The aggregation proof for current batch.
                  function finalizeBatchWithProof(
                      bytes calldata batchHeader,
                      bytes32 prevStateRoot,
                      bytes32 postStateRoot,
                      bytes32 withdrawRoot,
                      bytes calldata aggrProof
                  ) external;
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              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;
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              interface IZkEvmVerifier {
                  /// @notice Verify aggregate zk proof.
                  /// @param aggrProof The aggregated proof.
                  /// @param publicInputHash The public input hash.
                  function verify(bytes calldata aggrProof, bytes32 publicInputHash) external view;
              }
              // SPDX-License-Identifier: MIT
              // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
              pragma solidity ^0.8.0;
              /**
               * @dev Provides information about the current execution context, including the
               * sender of the transaction and its data. While these are generally available
               * via msg.sender and msg.data, they should not be accessed in such a direct
               * manner, since when dealing with meta-transactions the account sending and
               * paying for execution may not be the actual sender (as far as an application
               * is concerned).
               *
               * This contract is only required for intermediate, library-like contracts.
               */
              abstract contract Context {
                  function _msgSender() internal view virtual returns (address) {
                      return msg.sender;
                  }
                  function _msgData() internal view virtual returns (bytes calldata) {
                      return msg.data;
                  }
              }
              

              File 5 of 6: ZkEvmVerifierV1
              // SPDX-License-Identifier: MIT
              pragma solidity =0.8.16;
              import {IZkEvmVerifier} from "./IZkEvmVerifier.sol";
              // solhint-disable no-inline-assembly
              contract ZkEvmVerifierV1 is IZkEvmVerifier {
                  /**********
                   * Errors *
                   **********/
                  /// @dev Thrown when aggregate zk proof verification is failed.
                  error VerificationFailed();
                  /*************
                   * Constants *
                   *************/
                  /// @notice The address of highly optimized plonk verifier contract.
                  address public immutable plonkVerifier;
                  /***************
                   * Constructor *
                   ***************/
                  constructor(address _verifier) {
                      plonkVerifier = _verifier;
                  }
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @inheritdoc IZkEvmVerifier
                  function verify(bytes calldata aggrProof, bytes32 publicInputHash) external view override {
                      address _verifier = plonkVerifier;
                      bool success;
                      // 1. the first 12 * 32 (0x180) bytes of `aggrProof` is `accumulator`
                      // 2. the rest bytes of `aggrProof` is the actual `batch_aggregated_proof`
                      // 3. each byte of the `public_input_hash` should be converted to a `uint256` and the
                      //    1024 (0x400) bytes should inserted between `accumulator` and `batch_aggregated_proof`.
                      assembly {
                          let p := mload(0x40)
                          calldatacopy(p, aggrProof.offset, 0x180)
                          for {
                              let i := 0
                          } lt(i, 0x400) {
                              i := add(i, 0x20)
                          } {
                              mstore(add(p, sub(0x560, i)), and(publicInputHash, 0xff))
                              publicInputHash := shr(8, publicInputHash)
                          }
                          calldatacopy(add(p, 0x580), add(aggrProof.offset, 0x180), sub(aggrProof.length, 0x180))
                          success := staticcall(gas(), _verifier, p, add(aggrProof.length, 0x400), 0x00, 0x00)
                      }
                      if (!success) {
                          revert VerificationFailed();
                      }
                  }
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              interface IZkEvmVerifier {
                  /// @notice Verify aggregate zk proof.
                  /// @param aggrProof The aggregated proof.
                  /// @param publicInputHash The public input hash.
                  function verify(bytes calldata aggrProof, bytes32 publicInputHash) external view;
              }
              

              File 6 of 6: L1MessageQueueWithGasPriceOracle
              // 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.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
              // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/BitMaps.sol)
              pragma solidity ^0.8.0;
              /**
               * @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
               * Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
               */
              library BitMapsUpgradeable {
                  struct BitMap {
                      mapping(uint256 => uint256) _data;
                  }
                  /**
                   * @dev Returns whether the bit at `index` is set.
                   */
                  function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
                      uint256 bucket = index >> 8;
                      uint256 mask = 1 << (index & 0xff);
                      return bitmap._data[bucket] & mask != 0;
                  }
                  /**
                   * @dev Sets the bit at `index` to the boolean `value`.
                   */
                  function setTo(BitMap storage bitmap, uint256 index, bool value) internal {
                      if (value) {
                          set(bitmap, index);
                      } else {
                          unset(bitmap, index);
                      }
                  }
                  /**
                   * @dev Sets the bit at `index`.
                   */
                  function set(BitMap storage bitmap, uint256 index) internal {
                      uint256 bucket = index >> 8;
                      uint256 mask = 1 << (index & 0xff);
                      bitmap._data[bucket] |= mask;
                  }
                  /**
                   * @dev Unsets the bit at `index`.
                   */
                  function unset(BitMap storage bitmap, uint256 index) internal {
                      uint256 bucket = index >> 8;
                      uint256 mask = 1 << (index & 0xff);
                      bitmap._data[bucket] &= ~mask;
                  }
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              interface IL1MessageQueue {
                  /**********
                   * 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 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 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 finalized 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 Drop a skipped message from the queue.
                  function dropCrossDomainMessage(uint256 index) external;
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              import {IL1MessageQueue} from "./IL1MessageQueue.sol";
              interface IL1MessageQueueWithGasPriceOracle is IL1MessageQueue {
                  /**********
                   * Events *
                   **********/
                  /// @notice Emitted when owner updates whitelist checker contract.
                  /// @param _oldWhitelistChecker The address of old whitelist checker contract.
                  /// @param _newWhitelistChecker The address of new whitelist checker contract.
                  event UpdateWhitelistChecker(address indexed _oldWhitelistChecker, address indexed _newWhitelistChecker);
                  /// @notice Emitted when current l2 base fee is updated.
                  /// @param oldL2BaseFee The original l2 base fee before update.
                  /// @param newL2BaseFee The current l2 base fee updated.
                  event UpdateL2BaseFee(uint256 oldL2BaseFee, uint256 newL2BaseFee);
                  /**********
                   * Errors *
                   **********/
                  /// @dev Thrown when the caller is not whitelisted.
                  error ErrorNotWhitelistedSender();
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @notice Return the latest known l2 base fee.
                  function l2BaseFee() external view returns (uint256);
                  /// @notice Return the address of whitelist checker contract.
                  function whitelistChecker() external view returns (address);
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              interface IL2GasPriceOracle {
                  /// @notice Return the latest known l2 base fee.
                  function l2BaseFee() external view returns (uint256);
                  /// @notice Return the address of whitelist contract.
                  function whitelist() external view returns (address);
                  /// @notice Estimate fee for cross chain message call.
                  /// @param _gasLimit Gas limit required to complete the message relay on L2.
                  function estimateCrossDomainMessageFee(uint256 _gasLimit) external view returns (uint256);
                  /// @notice Estimate intrinsic gas fee for cross chain message call.
                  /// @param _message The message to be relayed on L2.
                  function calculateIntrinsicGasFee(bytes memory _message) external view returns (uint256);
              }
              // SPDX-License-Identifier: MIT
              pragma solidity =0.8.16;
              import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
              import {BitMapsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol";
              import {IL2GasPriceOracle} from "./IL2GasPriceOracle.sol";
              import {IL1MessageQueue} from "./IL1MessageQueue.sol";
              import {AddressAliasHelper} from "../../libraries/common/AddressAliasHelper.sol";
              // solhint-disable no-empty-blocks
              // solhint-disable no-inline-assembly
              // solhint-disable reason-string
              /// @title L1MessageQueue
              /// @notice This contract will hold all L1 to L2 messages.
              /// Each appended message is assigned with a unique and increasing `uint256` index.
              contract L1MessageQueue is OwnableUpgradeable, IL1MessageQueue {
                  using BitMapsUpgradeable for BitMapsUpgradeable.BitMap;
                  /*************
                   * Constants *
                   *************/
                  /// @notice The address of L1ScrollMessenger contract.
                  address public immutable messenger;
                  /// @notice The address of ScrollChain contract.
                  address public immutable scrollChain;
                  /// @notice The address EnforcedTxGateway contract.
                  address public immutable enforcedTxGateway;
                  /*************
                   * Variables *
                   *************/
                  /// @dev The storage slot used as L1ScrollMessenger contract, which is deprecated now.
                  address private __messenger;
                  /// @dev The storage slot used as ScrollChain contract, which is deprecated now.
                  address private __scrollChain;
                  /// @dev The storage slot used as EnforcedTxGateway contract, which is deprecated now.
                  address private __enforcedTxGateway;
                  /// @notice The address of GasOracle contract.
                  address public gasOracle;
                  /// @notice The list of queued cross domain messages.
                  bytes32[] public messageQueue;
                  /// @inheritdoc IL1MessageQueue
                  uint256 public pendingQueueIndex;
                  /// @notice The max gas limit of L1 transactions.
                  uint256 public maxGasLimit;
                  /// @dev The bitmap for dropped messages, where `droppedMessageBitmap[i]` keeps the bits from `[i*256, (i+1)*256)`.
                  BitMapsUpgradeable.BitMap private droppedMessageBitmap;
                  /// @dev The bitmap for skipped messages, where `skippedMessageBitmap[i]` keeps the bits from `[i*256, (i+1)*256)`.
                  mapping(uint256 => uint256) private skippedMessageBitmap;
                  /// @dev The storage slots for future usage.
                  uint256[41] private __gap;
                  /**********************
                   * Function Modifiers *
                   **********************/
                  modifier onlyMessenger() {
                      require(_msgSender() == messenger, "Only callable by the L1ScrollMessenger");
                      _;
                  }
                  /***************
                   * Constructor *
                   ***************/
                  /// @notice Constructor for `L1MessageQueue` implementation contract.
                  ///
                  /// @param _messenger The address of `L1ScrollMessenger` contract.
                  /// @param _scrollChain The address of `ScrollChain` contract.
                  /// @param _enforcedTxGateway The address of `EnforcedTxGateway` contract.
                  constructor(
                      address _messenger,
                      address _scrollChain,
                      address _enforcedTxGateway
                  ) {
                      if (_messenger == address(0) || _scrollChain == address(0) || _enforcedTxGateway == address(0)) {
                          revert ErrorZeroAddress();
                      }
                      _disableInitializers();
                      messenger = _messenger;
                      scrollChain = _scrollChain;
                      enforcedTxGateway = _enforcedTxGateway;
                  }
                  /// @notice Initialize the storage of L1MessageQueue.
                  ///
                  /// @dev The parameters `_messenger`, `_scrollChain` and `_enforcedTxGateway` are no longer used.
                  ///
                  /// @param _messenger The address of `L1ScrollMessenger` contract.
                  /// @param _scrollChain The address of `ScrollChain` contract.
                  /// @param _enforcedTxGateway The address of `EnforcedTxGateway` contract.
                  /// @param _gasOracle The address of `GasOracle` contract.
                  /// @param _maxGasLimit The maximum gas limit allowed in single transaction.
                  function initialize(
                      address _messenger,
                      address _scrollChain,
                      address _enforcedTxGateway,
                      address _gasOracle,
                      uint256 _maxGasLimit
                  ) external initializer {
                      OwnableUpgradeable.__Ownable_init();
                      gasOracle = _gasOracle;
                      maxGasLimit = _maxGasLimit;
                      __messenger = _messenger;
                      __scrollChain = _scrollChain;
                      __enforcedTxGateway = _enforcedTxGateway;
                  }
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @inheritdoc IL1MessageQueue
                  function nextCrossDomainMessageIndex() external view returns (uint256) {
                      return messageQueue.length;
                  }
                  /// @inheritdoc IL1MessageQueue
                  function getCrossDomainMessage(uint256 _queueIndex) external view returns (bytes32) {
                      return messageQueue[_queueIndex];
                  }
                  /// @inheritdoc IL1MessageQueue
                  function estimateCrossDomainMessageFee(uint256 _gasLimit) external view virtual override returns (uint256) {
                      address _oracle = gasOracle;
                      if (_oracle == address(0)) return 0;
                      return IL2GasPriceOracle(_oracle).estimateCrossDomainMessageFee(_gasLimit);
                  }
                  /// @inheritdoc IL1MessageQueue
                  function calculateIntrinsicGasFee(bytes calldata _calldata) public view virtual override returns (uint256) {
                      address _oracle = gasOracle;
                      if (_oracle == address(0)) return 0;
                      return IL2GasPriceOracle(_oracle).calculateIntrinsicGasFee(_calldata);
                  }
                  /// @inheritdoc IL1MessageQueue
                  function computeTransactionHash(
                      address _sender,
                      uint256 _queueIndex,
                      uint256 _value,
                      address _target,
                      uint256 _gasLimit,
                      bytes calldata _data
                  ) public pure override returns (bytes32) {
                      // We use EIP-2718 to encode the L1 message, and the encoding of the message is
                      //      `TransactionType || TransactionPayload`
                      // where
                      //  1. `TransactionType` is 0x7E
                      //  2. `TransactionPayload` is `rlp([queueIndex, gasLimit, to, value, data, sender])`
                      //
                      // The spec of rlp: https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/
                      uint256 transactionType = 0x7E;
                      bytes32 hash;
                      assembly {
                          function get_uint_bytes(v) -> len {
                              if eq(v, 0) {
                                  len := 1
                                  leave
                              }
                              for {
                              } gt(v, 0) {
                              } {
                                  len := add(len, 1)
                                  v := shr(8, v)
                              }
                          }
                          // This is used for both store uint and single byte.
                          // Integer zero is special handled by geth to encode as `0x80`
                          function store_uint_or_byte(_ptr, v, is_uint) -> ptr {
                              ptr := _ptr
                              switch lt(v, 128)
                              case 1 {
                                  switch and(iszero(v), is_uint)
                                  case 1 {
                                      // integer 0
                                      mstore8(ptr, 0x80)
                                  }
                                  default {
                                      // single byte in the [0x00, 0x7f]
                                      mstore8(ptr, v)
                                  }
                                  ptr := add(ptr, 1)
                              }
                              default {
                                  // 1-32 bytes long
                                  let len := get_uint_bytes(v)
                                  mstore8(ptr, add(len, 0x80))
                                  ptr := add(ptr, 1)
                                  mstore(ptr, shl(mul(8, sub(32, len)), v))
                                  ptr := add(ptr, len)
                              }
                          }
                          function store_address(_ptr, v) -> ptr {
                              ptr := _ptr
                              // 20 bytes long
                              mstore8(ptr, 0x94) // 0x80 + 0x14
                              ptr := add(ptr, 1)
                              mstore(ptr, shl(96, v))
                              ptr := add(ptr, 0x14)
                          }
                          // 1 byte for TransactionType
                          // 4 byte for list payload length
                          let start_ptr := add(mload(0x40), 5)
                          let ptr := start_ptr
                          ptr := store_uint_or_byte(ptr, _queueIndex, 1)
                          ptr := store_uint_or_byte(ptr, _gasLimit, 1)
                          ptr := store_address(ptr, _target)
                          ptr := store_uint_or_byte(ptr, _value, 1)
                          switch eq(_data.length, 1)
                          case 1 {
                              // single byte
                              ptr := store_uint_or_byte(ptr, byte(0, calldataload(_data.offset)), 0)
                          }
                          default {
                              switch lt(_data.length, 56)
                              case 1 {
                                  // a string is 0-55 bytes long
                                  mstore8(ptr, add(0x80, _data.length))
                                  ptr := add(ptr, 1)
                                  calldatacopy(ptr, _data.offset, _data.length)
                                  ptr := add(ptr, _data.length)
                              }
                              default {
                                  // a string is more than 55 bytes long
                                  let len_bytes := get_uint_bytes(_data.length)
                                  mstore8(ptr, add(0xb7, len_bytes))
                                  ptr := add(ptr, 1)
                                  mstore(ptr, shl(mul(8, sub(32, len_bytes)), _data.length))
                                  ptr := add(ptr, len_bytes)
                                  calldatacopy(ptr, _data.offset, _data.length)
                                  ptr := add(ptr, _data.length)
                              }
                          }
                          ptr := store_address(ptr, _sender)
                          let payload_len := sub(ptr, start_ptr)
                          let value
                          let value_bytes
                          switch lt(payload_len, 56)
                          case 1 {
                              // the total payload of a list is 0-55 bytes long
                              value := add(0xc0, payload_len)
                              value_bytes := 1
                          }
                          default {
                              // If the total payload of a list is more than 55 bytes long
                              let len_bytes := get_uint_bytes(payload_len)
                              value_bytes := add(len_bytes, 1)
                              value := add(0xf7, len_bytes)
                              value := shl(mul(len_bytes, 8), value)
                              value := or(value, payload_len)
                          }
                          value := or(value, shl(mul(8, value_bytes), transactionType))
                          value_bytes := add(value_bytes, 1)
                          let value_bits := mul(8, value_bytes)
                          value := or(shl(sub(256, value_bits), value), shr(value_bits, mload(start_ptr)))
                          start_ptr := sub(start_ptr, value_bytes)
                          mstore(start_ptr, value)
                          hash := keccak256(start_ptr, sub(ptr, start_ptr))
                      }
                      return hash;
                  }
                  /// @inheritdoc IL1MessageQueue
                  function isMessageSkipped(uint256 _queueIndex) external view returns (bool) {
                      if (_queueIndex >= pendingQueueIndex) return false;
                      return _isMessageSkipped(_queueIndex);
                  }
                  /// @inheritdoc IL1MessageQueue
                  function isMessageDropped(uint256 _queueIndex) external view returns (bool) {
                      // it should be a skipped message first.
                      return _isMessageSkipped(_queueIndex) && droppedMessageBitmap.get(_queueIndex);
                  }
                  /*****************************
                   * Public Mutating Functions *
                   *****************************/
                  /// @inheritdoc IL1MessageQueue
                  function appendCrossDomainMessage(
                      address _target,
                      uint256 _gasLimit,
                      bytes calldata _data
                  ) external override onlyMessenger {
                      // validate gas limit
                      _validateGasLimit(_gasLimit, _data);
                      // do address alias to avoid replay attack in L2.
                      address _sender = AddressAliasHelper.applyL1ToL2Alias(_msgSender());
                      _queueTransaction(_sender, _target, 0, _gasLimit, _data);
                  }
                  /// @inheritdoc IL1MessageQueue
                  function appendEnforcedTransaction(
                      address _sender,
                      address _target,
                      uint256 _value,
                      uint256 _gasLimit,
                      bytes calldata _data
                  ) external override {
                      require(_msgSender() == enforcedTxGateway, "Only callable by the EnforcedTxGateway");
                      // We will check it in EnforcedTxGateway, just in case.
                      require(_sender.code.length == 0, "only EOA");
                      // validate gas limit
                      _validateGasLimit(_gasLimit, _data);
                      _queueTransaction(_sender, _target, _value, _gasLimit, _data);
                  }
                  /// @inheritdoc IL1MessageQueue
                  function popCrossDomainMessage(
                      uint256 _startIndex,
                      uint256 _count,
                      uint256 _skippedBitmap
                  ) external {
                      require(_msgSender() == scrollChain, "Only callable by the ScrollChain");
                      require(_count <= 256, "pop too many messages");
                      require(pendingQueueIndex == _startIndex, "start index mismatch");
                      unchecked {
                          // clear extra bits in `_skippedBitmap`, and if _count = 256, it's designed to overflow.
                          uint256 mask = (1 << _count) - 1;
                          _skippedBitmap &= mask;
                          uint256 bucket = _startIndex >> 8;
                          uint256 offset = _startIndex & 0xff;
                          skippedMessageBitmap[bucket] |= _skippedBitmap << offset;
                          if (offset + _count > 256) {
                              skippedMessageBitmap[bucket + 1] = _skippedBitmap >> (256 - offset);
                          }
                          pendingQueueIndex = _startIndex + _count;
                      }
                      emit DequeueTransaction(_startIndex, _count, _skippedBitmap);
                  }
                  /// @inheritdoc IL1MessageQueue
                  function dropCrossDomainMessage(uint256 _index) external onlyMessenger {
                      require(_index < pendingQueueIndex, "cannot drop pending message");
                      require(_isMessageSkipped(_index), "drop non-skipped message");
                      require(!droppedMessageBitmap.get(_index), "message already dropped");
                      droppedMessageBitmap.set(_index);
                      emit DropTransaction(_index);
                  }
                  /************************
                   * Restricted Functions *
                   ************************/
                  /// @notice Update the address of gas oracle.
                  /// @dev This function can only called by contract owner.
                  /// @param _newGasOracle The address to update.
                  function updateGasOracle(address _newGasOracle) external onlyOwner {
                      address _oldGasOracle = gasOracle;
                      gasOracle = _newGasOracle;
                      emit UpdateGasOracle(_oldGasOracle, _newGasOracle);
                  }
                  /// @notice Update the max gas limit.
                  /// @dev This function can only called by contract owner.
                  /// @param _newMaxGasLimit The new max gas limit.
                  function updateMaxGasLimit(uint256 _newMaxGasLimit) external onlyOwner {
                      uint256 _oldMaxGasLimit = maxGasLimit;
                      maxGasLimit = _newMaxGasLimit;
                      emit UpdateMaxGasLimit(_oldMaxGasLimit, _newMaxGasLimit);
                  }
                  /**********************
                   * Internal Functions *
                   **********************/
                  /// @dev Internal function to queue a L1 transaction.
                  /// @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 _queueTransaction(
                      address _sender,
                      address _target,
                      uint256 _value,
                      uint256 _gasLimit,
                      bytes calldata _data
                  ) internal {
                      // compute transaction hash
                      uint256 _queueIndex = messageQueue.length;
                      bytes32 _hash = computeTransactionHash(_sender, _queueIndex, _value, _target, _gasLimit, _data);
                      messageQueue.push(_hash);
                      // emit event
                      emit QueueTransaction(_sender, _target, _value, uint64(_queueIndex), _gasLimit, _data);
                  }
                  function _validateGasLimit(uint256 _gasLimit, bytes calldata _calldata) internal view {
                      require(_gasLimit <= maxGasLimit, "Gas limit must not exceed maxGasLimit");
                      // check if the gas limit is above intrinsic gas
                      uint256 intrinsicGas = calculateIntrinsicGasFee(_calldata);
                      require(_gasLimit >= intrinsicGas, "Insufficient gas limit, must be above intrinsic gas");
                  }
                  /// @dev Returns whether the bit at `index` is set.
                  function _isMessageSkipped(uint256 index) internal view returns (bool) {
                      uint256 bucket = index >> 8;
                      uint256 mask = 1 << (index & 0xff);
                      return skippedMessageBitmap[bucket] & mask != 0;
                  }
              }
              // SPDX-License-Identifier: MIT
              pragma solidity =0.8.16;
              import {IWhitelist} from "../../libraries/common/IWhitelist.sol";
              import {IL1MessageQueue} from "./IL1MessageQueue.sol";
              import {IL1MessageQueueWithGasPriceOracle} from "./IL1MessageQueueWithGasPriceOracle.sol";
              import {IL2GasPriceOracle} from "./IL2GasPriceOracle.sol";
              import {L1MessageQueue} from "./L1MessageQueue.sol";
              contract L1MessageQueueWithGasPriceOracle is L1MessageQueue, IL1MessageQueueWithGasPriceOracle {
                  /*************
                   * Constants *
                   *************/
                  /// @notice The intrinsic gas for transaction.
                  uint256 private constant INTRINSIC_GAS_TX = 21000;
                  /// @notice The appropriate intrinsic gas for each byte.
                  uint256 private constant APPROPRIATE_INTRINSIC_GAS_PER_BYTE = 16;
                  /*************
                   * Variables *
                   *************/
                  /// @inheritdoc IL1MessageQueueWithGasPriceOracle
                  uint256 public override l2BaseFee;
                  /// @inheritdoc IL1MessageQueueWithGasPriceOracle
                  address public override whitelistChecker;
                  /***************
                   * Constructor *
                   ***************/
                  /// @notice Constructor for `L1MessageQueueWithGasPriceOracle` implementation contract.
                  ///
                  /// @param _messenger The address of `L1ScrollMessenger` contract.
                  /// @param _scrollChain The address of `ScrollChain` contract.
                  /// @param _enforcedTxGateway The address of `EnforcedTxGateway` contract.
                  constructor(
                      address _messenger,
                      address _scrollChain,
                      address _enforcedTxGateway
                  ) L1MessageQueue(_messenger, _scrollChain, _enforcedTxGateway) {}
                  /// @notice Initialize the storage of L1MessageQueueWithGasPriceOracle.
                  function initializeV2() external reinitializer(2) {
                      l2BaseFee = IL2GasPriceOracle(gasOracle).l2BaseFee();
                      whitelistChecker = IL2GasPriceOracle(gasOracle).whitelist();
                  }
                  /*************************
                   * Public View Functions *
                   *************************/
                  /// @inheritdoc IL1MessageQueue
                  function estimateCrossDomainMessageFee(uint256 _gasLimit)
                      external
                      view
                      override(IL1MessageQueue, L1MessageQueue)
                      returns (uint256)
                  {
                      return _gasLimit * l2BaseFee;
                  }
                  /// @inheritdoc IL1MessageQueue
                  function calculateIntrinsicGasFee(bytes calldata _calldata)
                      public
                      pure
                      override(IL1MessageQueue, L1MessageQueue)
                      returns (uint256)
                  {
                      // no way this can overflow `uint256`
                      unchecked {
                          return INTRINSIC_GAS_TX + _calldata.length * APPROPRIATE_INTRINSIC_GAS_PER_BYTE;
                      }
                  }
                  /*****************************
                   * Public Mutating Functions *
                   *****************************/
                  /// @notice Allows whitelistCheckered caller to modify the l2 base fee.
                  /// @param _newL2BaseFee The new l2 base fee.
                  function setL2BaseFee(uint256 _newL2BaseFee) external {
                      if (!IWhitelist(whitelistChecker).isSenderAllowed(_msgSender())) {
                          revert ErrorNotWhitelistedSender();
                      }
                      uint256 _oldL2BaseFee = l2BaseFee;
                      l2BaseFee = _newL2BaseFee;
                      emit UpdateL2BaseFee(_oldL2BaseFee, _newL2BaseFee);
                  }
                  /************************
                   * Restricted Functions *
                   ************************/
                  /// @notice Update whitelist checker contract.
                  /// @dev This function can only called by contract owner.
                  /// @param _newWhitelistChecker The address of new whitelist checker contract.
                  function updateWhitelistChecker(address _newWhitelistChecker) external onlyOwner {
                      address _oldWhitelistChecker = whitelistChecker;
                      whitelistChecker = _newWhitelistChecker;
                      emit UpdateWhitelistChecker(_oldWhitelistChecker, _newWhitelistChecker);
                  }
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              library AddressAliasHelper {
                  /// @dev The offset added to the address in L1.
                  uint160 internal constant OFFSET = uint160(0x1111000000000000000000000000000000001111);
                  /// @notice Utility function that converts the address in the L1 that submitted a tx to
                  /// the inbox to the msg.sender viewed in the L2
                  /// @param l1Address the address in the L1 that triggered the tx to L2
                  /// @return l2Address L2 address as viewed in msg.sender
                  function applyL1ToL2Alias(address l1Address) internal pure returns (address l2Address) {
                      unchecked {
                          l2Address = address(uint160(l1Address) + OFFSET);
                      }
                  }
                  /// @notice Utility function that converts the msg.sender viewed in the L2 to the
                  /// address in the L1 that submitted a tx to the inbox
                  /// @param l2Address L2 address as viewed in msg.sender
                  /// @return l1Address the address in the L1 that triggered the tx to L2
                  function undoL1ToL2Alias(address l2Address) internal pure returns (address l1Address) {
                      unchecked {
                          l1Address = address(uint160(l2Address) - OFFSET);
                      }
                  }
              }
              // SPDX-License-Identifier: MIT
              pragma solidity ^0.8.16;
              interface IWhitelist {
                  /// @notice Check whether the sender is allowed to do something.
                  /// @param _sender The address of sender.
                  function isSenderAllowed(address _sender) external view returns (bool);
              }