ETH Price: $2,531.82 (+0.34%)

Transaction Decoder

Block:
22658848 at Jun-08-2025 09:02:47 AM +UTC
Transaction Fee:
0.000070417 ETH $0.18
Gas Used:
140,834 Gas / 0.5 Gwei

Emitted Events:

357 TransparentUpgradeableProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000002a3dd3eb832af982ec71669e178424b10dca2ede, 0x0000000000000000000000008cc267eea0585f2b1c0c4aef864edbde13e45186, 00000000000000000000000000000000000000000000000dd2d5fcf3bc9c0000 )
358 TransparentUpgradeableProxy.0x1df3f2a973a00d6635911755c260704e95e8a5876997546798770f76396fda4d( 0x1df3f2a973a00d6635911755c260704e95e8a5876997546798770f76396fda4d, 000000000000000000000000000000000000000000000000000000000000de53, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000009ee91f9f426fa633d227f7a9b000e28b9dfd8599, 0000000000000000000000008cc267eea0585f2b1c0c4aef864edbde13e45186, 00000000000000000000000000000000000000000000000dd2d5fcf3bc9c0000 )

Account State Difference:

  Address   Before After State Difference Code
0x2a3DD3EB...10Dca2EDe
(Polygon (Matic): zkEVM Bridge)
0x8CC267ee...E13e45186
0.00904966869264106 Eth
Nonce: 3255
0.00897925169264106 Eth
Nonce: 3256
0.000070417
(beaverbuild)
11.547565096430472935 Eth11.547565325063768551 Eth0.000000228633295616
0x9ee91F9f...b9dfd8599

Execution Trace

TransparentUpgradeableProxy.ccaa2d11( )
  • PolygonZkEVMBridgeV2.claimAsset( smtProofLocalExitRoot=[MUQbb5LYiH31CFYxuL2vvIZCUL0D2tx0Q4N2FqeHiDw=, P7T+gbwjCHKgFppIOkyohlkErfz2+kP0vgSoNn5fZGc=, pzCkn8UOc5vgN7k0rNmocgsN0V0SOqkP2EoIFUws6XQ=, J6epmsfoIh8ekMGOqkLQT2MFM4Jgb8pTCm6hEoz9hc8=, cU3sGlCiqTn/Jhvs4f+H+uYekh8OCyaC+Hw75pFdeug=, DrAev8ntJ1AM1N/JeSctHwkTzJ9mVA1+gAWBEQnhzy0=, FnehnCw01cS3CDNVAm2prRthjoZphGXJhG//LFBfhCQ=, /9cBV+SAY/wzyXoFD39kAjO/ZGzJjZUkxrkrzzq1b4M=, mGfMX38Za5O64eJ+YyB0JEXSkPImOCdJi1T+xTn3Vq8=, Aa8g9zfIW8wAdMeZaPo5FrlBpzb+UzoflxpO2fc8r3Y=, viacKuq9fHDTsPsjZg38JlSw04lyiEccmDdvbLmECX8=, CO7Q6KV85Bn0oGRf+w168Um8FvxaHFtDi3bCmDGekSU=, Ko5EXO+k75Io4fWFgZY56OdpKoX5qs16ulrZIrYr9DE=, wd+C2cS4dBPq4u8Ej5S001VM6nPZKw96+W4CccaR4rs=, LJqC0sOl6TBU3rRsuurZ/7+cSfTLB9CvJlHa5T4AzrA=, 1nMt/QAlsSWudnbHuzS1noe4OnKPzKvvqXPJGjpxzKo=, JzPlD1JuwvoZoisx6O1Q8jzR/flMkVTtOnYJovH/mB8=, 4dO1yAeygeRoPMbWMVz5W5rehkHe/LMjcvHBJuOY73o=, Wi3OCop/aLt0Vg+PcYN8LC67y/f/+0KuGJbxP3x0eaA=, tGootvVVQPiURPY94DeOPRIb4J4GzJ3tHCDmWHbTaqA=, xl6WRWRHhrYg4t0q1kjd/L9KflsaOk7P5/ZGZ6Pwt+I=, 9EGFiO01okWM/+s5uT0m8Y0qsTvc5q7ljnuZNZ7C39k=, WpwW3ADW7xi3kzpvjcZcy1VmcTh3b33qEBBw3IeW43c=, TfhPQK4MginQ1gaeXI85p8KZZ3oJ02f8ewXjvDgO5lI=, zccllfdMexBD0OH/urc0ZIyDjfsFJ9lxtgK8IWyWGe8=, Cr9ayXSh7Vf0BQqlEN2cdPUIJ3s515c7st/Mxe6wYY0=, uM10BG/zN/CnvyyOA+EPZCwYhnmNcYBqseiI2eXuh9A=, g4xWVcshxsuDMTtaYxF13/SWN3LM6RCBiLNKyHyBxB4=, Zi7k3S3XsrxweWGx5kbEBHZp3LZYTw2Ndw2vXX596y4=, OIqyDiVz0XGogQjnnYIOmPJsC4Sqiy9KpJaNu4GOoyI=, kyN8ULp17khfTCKt8vdBQAvfjWqcx99+yuV2IhZl1zU=, hEiBi7SuRWKEnpSeF6wW4L4WaI4Va1zxXgmMYnwAVqk=], smtProofRollupExitRoot=[Xl0aoSjZSjwWSz92y1SwL+wTh9JHtPUA/FYicscXQk0=, t0A2yD/US+E3ZD7OxXwPVz3dQdg0fnj6roL4LeL1wwo=, sgLU4hx6gO03oNlVmvdJi1ScggG9pjEQYPkKL0PPYvE=, 6A4Mf87EAyZ1ZVsrgsgq7ubjLN9m51pZP1eAl99ICuQ=, F7A5tIFvRT9ibT3ra1bV52ot8urve6Q952x65xmTQKc=, DrAev8ntJ1AM1N/JeSctHwkTzJ9mVA1+gAWBEQnhzy0=, iHwivYdQ00AWrDxmtf8QLazdc/awFOcQtR6AIq+aGWg=, /9cBV+SAY/wzyXoFD39kAjO/ZGzJjZUkxrkrzzq1b4M=, mGfMX38Za5O64eJ+YyB0JEXSkPImOCdJi1T+xTn3Vq8=, zvrU5QjAmLmn4dj+sZlV+wK6lnVYUHhxCWnTRA9QVOA=, +dw+f+AW4FDv8mAzTxil1P45HYIJIxn1lk8uLrfBw6U=, +LE6SeKC9gnDF6gz+42XbRFRfFcdEiGiZdJa93js+JI=, NJDGzutFCuzcguKCkwMdEMfXO/heV78EGpc2CqLF2Zw=, wd+C2cS4dBPq4u8Ej5S001VM6nPZKw96+W4CccaR4rs=, XGet18bK8wIlat7ferEU2grP6HDUSaOkifeB1lnovsw=, 2nvOn06GGLa9L0EyznmM3Hpg5+FGCnKZ48Y0KleWJtI=, JzPlD1JuwvoZoisx6O1Q8jzR/flMkVTtOnYJovH/mB8=, 4dO1yAeygeRoPMbWMVz5W5rehkHe/LMjcvHBJuOY73o=, Wi3OCop/aLt0Vg+PcYN8LC67y/f/+0KuGJbxP3x0eaA=, tGootvVVQPiURPY94DeOPRIb4J4GzJ3tHCDmWHbTaqA=, xl6WRWRHhrYg4t0q1kjd/L9KflsaOk7P5/ZGZ6Pwt+I=, 9EGFiO01okWM/+s5uT0m8Y0qsTvc5q7ljnuZNZ7C39k=, WpwW3ADW7xi3kzpvjcZcy1VmcTh3b33qEBBw3IeW43c=, TfhPQK4MginQ1gaeXI85p8KZZ3oJ02f8ewXjvDgO5lI=, zccllfdMexBD0OH/urc0ZIyDjfsFJ9lxtgK8IWyWGe8=, Cr9ayXSh7Vf0BQqlEN2cdPUIJ3s515c7st/Mxe6wYY0=, uM10BG/zN/CnvyyOA+EPZCwYhnmNcYBqseiI2eXuh9A=, g4xWVcshxsuDMTtaYxF13/SWN3LM6RCBiLNKyHyBxB4=, Zi7k3S3XsrxweWGx5kbEBHZp3LZYTw2Ndw2vXX596y4=, OIqyDiVz0XGogQjnnYIOmPJsC4Sqiy9KpJaNu4GOoyI=, kyN8ULp17khfTCKt8vdBQAvfjWqcx99+yuV2IhZl1zU=, hEiBi7SuRWKEnpSeF6wW4L4WaI4Va1zxXgmMYnwAVqk=], globalIndex=56915, mainnetExitRoot=6EC58AA072AD1ADFF1BAEC29FD5B23B8ADF1340931B9B06922531E7D0A5CB3DF, rollupExitRoot=5E18BD4F109E015AC042DB73FE91C01C7E2EE1B5DCBFAC4A3378B2E5077DBEDD, originNetwork=0, originTokenAddress=0x9ee91F9f426fA633d227f7a9b000E28b9dfd8599, destinationNetwork=0, destinationAddress=0x8CC267eea0585f2B1c0C4aef864edBdE13e45186, amount=255000000000000000000, metadata=0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A00000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000C5374616B6564204D415449430000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000773744D4154494300000000000000000000000000000000000000000000000000 )
    • TransparentUpgradeableProxy.257b3632( )
      • PolygonZkEVMGlobalExitRootV2.globalExitRootMap( 36BF3428CA962E6B7D0331F8E23E9D40CECDC6238FF0418144B0145227CF974E ) => ( 34321618541479523352104727807071231754278868161828029176162367547894603460318 )
      • TransparentUpgradeableProxy.a9059cbb( )
        • StMATIC.transfer( to=0x8CC267eea0585f2B1c0C4aef864edBdE13e45186, amount=255000000000000000000 ) => ( True )
          File 1 of 6: TransparentUpgradeableProxy
          // Sources flattened with hardhat v2.9.9 https://hardhat.org
          
          // File interfaces/IInterchainGasPaymaster.sol
          
          // SPDX-License-Identifier: MIT
          pragma solidity >=0.6.11;
          
          /**
           * @title IInterchainGasPaymaster
           * @notice Manages payments on a source chain to cover gas costs of relaying
           * messages to destination chains.
           */
          interface IInterchainGasPaymaster {
              function payForGas(
                  bytes32 _messageId,
                  uint32 _destinationDomain,
                  uint256 _gas,
                  address _refundAddress
              ) external payable;
          }
          
          
          // File interfaces/IInterchainSecurityModule.sol
          
          
          pragma solidity >=0.6.11;
          
          interface IInterchainSecurityModule {
              /**
               * @notice Returns an enum that represents the type of security model
               * encoded by this ISM.
               * @dev Relayers infer how to fetch and format metadata.
               */
              function moduleType() external view returns (uint8);
          
              /**
               * @notice Defines a security model responsible for verifying interchain
               * messages based on the provided metadata.
               * @param _metadata Off-chain metadata provided by a relayer, specific to
               * the security model encoded by the module (e.g. validator signatures)
               * @param _message Hyperlane encoded interchain message
               * @return True if the message was verified
               */
              function verify(bytes calldata _metadata, bytes calldata _message)
                  external
                  returns (bool);
          }
          
          interface ISpecifiesInterchainSecurityModule {
              function interchainSecurityModule()
                  external
                  view
                  returns (IInterchainSecurityModule);
          }
          
          
          // File interfaces/IMailbox.sol
          
          
          pragma solidity >=0.8.0;
          
          interface IMailbox {
              function localDomain() external view returns (uint32);
          
              function dispatch(
                  uint32 _destinationDomain,
                  bytes32 _recipientAddress,
                  bytes calldata _messageBody
              ) external returns (bytes32);
          
              function process(bytes calldata _metadata, bytes calldata _message)
                  external;
          
              function count() external view returns (uint32);
          
              function root() external view returns (bytes32);
          
              function latestCheckpoint() external view returns (bytes32, uint32);
          
              function recipientIsm(address _recipient)
                  external
                  view
                  returns (IInterchainSecurityModule);
          }
          
          
          // File @openzeppelin/contracts-upgradeable/utils/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
          
          pragma solidity ^0.8.1;
          
          /**
           * @dev Collection of functions related to the address type
           */
          library AddressUpgradeable {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
          
                  return account.code.length > 0;
              }
          
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
          
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
          
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return 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 Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
          
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
          
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          
          
          // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)
          
          pragma solidity ^0.8.2;
          
          /**
           * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
           * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
           * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
           * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
           *
           * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
           * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
           * case an upgrade adds a module that needs to be initialized.
           *
           * For example:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
          
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
          
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
          
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * 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 Internal function that returns the initialized version. Returns `_initialized`
               */
              function _getInitializedVersion() internal view returns (uint8) {
                  return _initialized;
              }
          
              /**
               * @dev Internal function that returns the initialized version. Returns `_initializing`
               */
              function _isInitializing() internal view returns (bool) {
                  return _initializing;
              }
          }
          
          
          // File @openzeppelin/contracts-upgradeable/utils/[email protected]
          
          
          // 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 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;
          }
          
          
          // File @openzeppelin/contracts-upgradeable/access/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
          
          pragma solidity ^0.8.0;
          
          
          /**
           * @dev Contract module which provides a basic access control mechanism, where
           * there is an account (an owner) that can be granted exclusive access to
           * specific functions.
           *
           * By default, the owner account will be the one that deploys the contract. This
           * can later be changed with {transferOwnership}.
           *
           * This module is used through inheritance. It will make available the modifier
           * `onlyOwner`, which can be applied to your functions to restrict their use to
           * the owner.
           */
          abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
              address private _owner;
          
              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          
              /**
               * @dev Initializes the contract setting the deployer as the initial owner.
               */
              function __Ownable_init() internal onlyInitializing {
                  __Ownable_init_unchained();
              }
          
              function __Ownable_init_unchained() internal onlyInitializing {
                  _transferOwnership(_msgSender());
              }
          
              /**
               * @dev Throws if called by any account other than the owner.
               */
              modifier onlyOwner() {
                  _checkOwner();
                  _;
              }
          
              /**
               * @dev Returns the address of the current owner.
               */
              function owner() public view virtual returns (address) {
                  return _owner;
              }
          
              /**
               * @dev Throws if the sender is not the owner.
               */
              function _checkOwner() internal view virtual {
                  require(owner() == _msgSender(), "Ownable: caller is not the owner");
              }
          
              /**
               * @dev Leaves the contract without owner. It will not be possible to call
               * `onlyOwner` functions anymore. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby removing any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
          
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                  _transferOwnership(newOwner);
              }
          
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Internal function without access restriction.
               */
              function _transferOwnership(address newOwner) internal virtual {
                  address oldOwner = _owner;
                  _owner = newOwner;
                  emit OwnershipTransferred(oldOwner, newOwner);
              }
          
              /**
               * @dev This empty reserved space is put in place to allow future versions to add new
               * variables without shifting down storage in the inheritance chain.
               * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
               */
              uint256[49] private __gap;
          }
          
          
          // File @openzeppelin/contracts/utils/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
          
          pragma solidity ^0.8.1;
          
          /**
           * @dev Collection of functions related to the address type
           */
          library Address {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
          
                  return account.code.length > 0;
              }
          
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
          
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
          
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, "Address: low-level call failed");
              }
          
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
          
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
          
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
          
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
          
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
          
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionDelegateCall(target, data, "Address: low-level delegate call failed");
              }
          
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a delegate call.
               *
               * _Available since v3.4._
               */
              function functionDelegateCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
          
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
          
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
          
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          
          
          // File contracts/HyperlaneConnectionClient.sol
          
          
          pragma solidity >=0.6.11;
          
          // ============ Internal Imports ============
          
          
          
          // ============ External Imports ============
          
          
          abstract contract HyperlaneConnectionClient is
              OwnableUpgradeable,
              ISpecifiesInterchainSecurityModule
          {
              // ============ Mutable Storage ============
          
              IMailbox public mailbox;
              // Interchain Gas Paymaster contract. The relayer associated with this contract
              // must be willing to relay messages dispatched from the current Mailbox contract,
              // otherwise payments made to the paymaster will not result in relayed messages.
              IInterchainGasPaymaster public interchainGasPaymaster;
          
              IInterchainSecurityModule public interchainSecurityModule;
          
              uint256[48] private __GAP; // gap for upgrade safety
          
              // ============ Events ============
              /**
               * @notice Emitted when a new mailbox is set.
               * @param mailbox The address of the mailbox contract
               */
              event MailboxSet(address indexed mailbox);
          
              /**
               * @notice Emitted when a new Interchain Gas Paymaster is set.
               * @param interchainGasPaymaster The address of the Interchain Gas Paymaster.
               */
              event InterchainGasPaymasterSet(address indexed interchainGasPaymaster);
          
              event InterchainSecurityModuleSet(address indexed module);
          
              // ============ Modifiers ============
          
              /**
               * @notice Only accept messages from an Hyperlane Mailbox contract
               */
              modifier onlyMailbox() {
                  require(msg.sender == address(mailbox), "!mailbox");
                  _;
              }
          
              /**
               * @notice Only accept addresses that at least have contract code
               */
              modifier onlyContract(address _contract) {
                  require(Address.isContract(_contract), "!contract");
                  _;
              }
          
              // ======== Initializer =========
          
              function __HyperlaneConnectionClient_initialize(address _mailbox)
                  internal
                  onlyInitializing
              {
                  _setMailbox(_mailbox);
                  __Ownable_init();
              }
          
              function __HyperlaneConnectionClient_initialize(
                  address _mailbox,
                  address _interchainGasPaymaster
              ) internal onlyInitializing {
                  _setInterchainGasPaymaster(_interchainGasPaymaster);
                  __HyperlaneConnectionClient_initialize(_mailbox);
              }
          
              function __HyperlaneConnectionClient_initialize(
                  address _mailbox,
                  address _interchainGasPaymaster,
                  address _interchainSecurityModule
              ) internal onlyInitializing {
                  _setInterchainSecurityModule(_interchainSecurityModule);
                  __HyperlaneConnectionClient_initialize(
                      _mailbox,
                      _interchainGasPaymaster
                  );
              }
          
              // ============ External functions ============
          
              /**
               * @notice Sets the address of the application's Mailbox.
               * @param _mailbox The address of the Mailbox contract.
               */
              function setMailbox(address _mailbox) external virtual onlyOwner {
                  _setMailbox(_mailbox);
              }
          
              /**
               * @notice Sets the address of the application's InterchainGasPaymaster.
               * @param _interchainGasPaymaster The address of the InterchainGasPaymaster contract.
               */
              function setInterchainGasPaymaster(address _interchainGasPaymaster)
                  external
                  virtual
                  onlyOwner
              {
                  _setInterchainGasPaymaster(_interchainGasPaymaster);
              }
          
              function setInterchainSecurityModule(address _module)
                  external
                  virtual
                  onlyOwner
              {
                  _setInterchainSecurityModule(_module);
              }
          
              // ============ Internal functions ============
          
              /**
               * @notice Sets the address of the application's InterchainGasPaymaster.
               * @param _interchainGasPaymaster The address of the InterchainGasPaymaster contract.
               */
              function _setInterchainGasPaymaster(address _interchainGasPaymaster)
                  internal
                  onlyContract(_interchainGasPaymaster)
              {
                  interchainGasPaymaster = IInterchainGasPaymaster(
                      _interchainGasPaymaster
                  );
                  emit InterchainGasPaymasterSet(_interchainGasPaymaster);
              }
          
              /**
               * @notice Modify the contract the Application uses to validate Mailbox contracts
               * @param _mailbox The address of the mailbox contract
               */
              function _setMailbox(address _mailbox) internal onlyContract(_mailbox) {
                  mailbox = IMailbox(_mailbox);
                  emit MailboxSet(_mailbox);
              }
          
              function _setInterchainSecurityModule(address _module)
                  internal
                  onlyContract(_module)
              {
                  interchainSecurityModule = IInterchainSecurityModule(_module);
                  emit InterchainSecurityModuleSet(_module);
              }
          }
          
          
          // File contracts/InterchainGasPaymaster.sol
          
          
          pragma solidity >=0.8.0;
          
          // ============ Internal Imports ============
          
          // ============ External Imports ============
          
          /**
           * @title InterchainGasPaymaster
           * @notice Manages payments on a source chain to cover gas costs of relaying
           * messages to destination chains.
           */
          contract InterchainGasPaymaster is IInterchainGasPaymaster, OwnableUpgradeable {
              // ============ Events ============
          
              /**
               * @notice Emitted when a payment is made for a message's gas costs.
               * @param messageId The ID of the message to pay for.
               * @param gasAmount The amount of destination gas paid for.
               * @param payment The amount of native tokens paid.
               */
              event GasPayment(
                  bytes32 indexed messageId,
                  uint256 gasAmount,
                  uint256 payment
              );
          
              // ============ Constructor ============
          
              // solhint-disable-next-line no-empty-blocks
              constructor() {
                  initialize(); // allows contract to be used without proxying
              }
          
              // ============ External Functions ============
          
              function initialize() public initializer {
                  __Ownable_init();
              }
          
              /**
               * @notice Deposits msg.value as a payment for the relaying of a message
               * to its destination chain.
               * @param _messageId The ID of the message to pay for.
               * @param _destinationDomain The domain of the message's destination chain.
               * @param _gasAmount The amount of destination gas to pay for. Currently unused.
               * @param _refundAddress The address to refund any overpayment to. Currently unused.
               */
              function payForGas(
                  bytes32 _messageId,
                  uint32 _destinationDomain,
                  uint256 _gasAmount,
                  address _refundAddress
              ) external payable override {
                  // Silence compiler warning. The NatSpec @param requires the parameter to be named.
                  // While not used at the moment, future versions of the paymaster have behavior specific
                  // to the destination domain and refund overpayments to the _refundAddress.
                  _destinationDomain;
                  _refundAddress;
          
                  emit GasPayment(_messageId, _gasAmount, msg.value);
              }
          
              /**
               * @notice Transfers the entire native token balance to the owner of the contract.
               * @dev The owner must be able to receive native tokens.
               */
              function claim() external {
                  // Transfer the entire balance to owner.
                  (bool success, ) = owner().call{value: address(this).balance}("");
                  require(success, "!transfer");
              }
          }
          
          
          // File @openzeppelin/contracts/utils/[email protected]
          
          
          // 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 @openzeppelin/contracts/access/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Contract module which provides a basic access control mechanism, where
           * there is an account (an owner) that can be granted exclusive access to
           * specific functions.
           *
           * By default, the owner account will be the one that deploys the contract. This
           * can later be changed with {transferOwnership}.
           *
           * This module is used through inheritance. It will make available the modifier
           * `onlyOwner`, which can be applied to your functions to restrict their use to
           * the owner.
           */
          abstract contract Ownable is Context {
              address private _owner;
          
              event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
          
              /**
               * @dev Initializes the contract setting the deployer as the initial owner.
               */
              constructor() {
                  _transferOwnership(_msgSender());
              }
          
              /**
               * @dev Throws if called by any account other than the owner.
               */
              modifier onlyOwner() {
                  _checkOwner();
                  _;
              }
          
              /**
               * @dev Returns the address of the current owner.
               */
              function owner() public view virtual returns (address) {
                  return _owner;
              }
          
              /**
               * @dev Throws if the sender is not the owner.
               */
              function _checkOwner() internal view virtual {
                  require(owner() == _msgSender(), "Ownable: caller is not the owner");
              }
          
              /**
               * @dev Leaves the contract without owner. It will not be possible to call
               * `onlyOwner` functions anymore. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby removing any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
          
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  require(newOwner != address(0), "Ownable: new owner is the zero address");
                  _transferOwnership(newOwner);
              }
          
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Internal function without access restriction.
               */
              function _transferOwnership(address newOwner) internal virtual {
                  address oldOwner = _owner;
                  _owner = newOwner;
                  emit OwnershipTransferred(oldOwner, newOwner);
              }
          }
          
          
          // File @openzeppelin/contracts/utils/math/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Standard math utilities missing in the Solidity language.
           */
          library Math {
              enum Rounding {
                  Down, // Toward negative infinity
                  Up, // Toward infinity
                  Zero // Toward zero
              }
          
              /**
               * @dev Returns the largest of two numbers.
               */
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
          
              /**
               * @dev Returns the smallest of two numbers.
               */
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
          
              /**
               * @dev Returns the average of two numbers. The result is rounded towards
               * zero.
               */
              function average(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b) / 2 can overflow.
                  return (a & b) + (a ^ b) / 2;
              }
          
              /**
               * @dev Returns the ceiling of the division of two numbers.
               *
               * This differs from standard division with `/` in that it rounds up instead
               * of rounding down.
               */
              function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b - 1) / b can overflow on addition, so we distribute.
                  return a == 0 ? 0 : (a - 1) / b + 1;
              }
          
              /**
               * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
               * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
               * with further edits by Uniswap Labs also under MIT license.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator
              ) internal pure returns (uint256 result) {
                  unchecked {
                      // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                      // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                      // variables such that product = prod1 * 2^256 + prod0.
                      uint256 prod0; // Least significant 256 bits of the product
                      uint256 prod1; // Most significant 256 bits of the product
                      assembly {
                          let mm := mulmod(x, y, not(0))
                          prod0 := mul(x, y)
                          prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                      }
          
                      // Handle non-overflow cases, 256 by 256 division.
                      if (prod1 == 0) {
                          return prod0 / denominator;
                      }
          
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1);
          
                      ///////////////////////////////////////////////
                      // 512 by 256 division.
                      ///////////////////////////////////////////////
          
                      // Make division exact by subtracting the remainder from [prod1 prod0].
                      uint256 remainder;
                      assembly {
                          // Compute remainder using mulmod.
                          remainder := mulmod(x, y, denominator)
          
                          // Subtract 256 bit number from 512 bit number.
                          prod1 := sub(prod1, gt(remainder, prod0))
                          prod0 := sub(prod0, remainder)
                      }
          
                      // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                      // See https://cs.stackexchange.com/q/138556/92363.
          
                      // Does not overflow because the denominator cannot be zero at this stage in the function.
                      uint256 twos = denominator & (~denominator + 1);
                      assembly {
                          // Divide denominator by twos.
                          denominator := div(denominator, twos)
          
                          // Divide [prod1 prod0] by twos.
                          prod0 := div(prod0, twos)
          
                          // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                          twos := add(div(sub(0, twos), twos), 1)
                      }
          
                      // Shift in bits from prod1 into prod0.
                      prod0 |= prod1 * twos;
          
                      // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                      // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                      // four bits. That is, denominator * inv = 1 mod 2^4.
                      uint256 inverse = (3 * denominator) ^ 2;
          
                      // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                      // in modular arithmetic, doubling the correct bits in each step.
                      inverse *= 2 - denominator * inverse; // inverse mod 2^8
                      inverse *= 2 - denominator * inverse; // inverse mod 2^16
                      inverse *= 2 - denominator * inverse; // inverse mod 2^32
                      inverse *= 2 - denominator * inverse; // inverse mod 2^64
                      inverse *= 2 - denominator * inverse; // inverse mod 2^128
                      inverse *= 2 - denominator * inverse; // inverse mod 2^256
          
                      // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                      // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                      // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                      // is no longer required.
                      result = prod0 * inverse;
                      return result;
                  }
              }
          
              /**
               * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator,
                  Rounding rounding
              ) internal pure returns (uint256) {
                  uint256 result = mulDiv(x, y, denominator);
                  if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                      result += 1;
                  }
                  return result;
              }
          
              /**
               * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
               *
               * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
               */
              function sqrt(uint256 a) internal pure returns (uint256) {
                  if (a == 0) {
                      return 0;
                  }
          
                  // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                  //
                  // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                  // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                  //
                  // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                  // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                  // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                  //
                  // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                  uint256 result = 1 << (log2(a) >> 1);
          
                  // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                  // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                  // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                  // into the expected uint128 result.
                  unchecked {
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      return min(result, a / result);
                  }
              }
          
              /**
               * @notice Calculates sqrt(a), following the selected rounding direction.
               */
              function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = sqrt(a);
                      return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                  }
              }
          
              /**
               * @dev Return the log in base 2, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 128;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 64;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 32;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 16;
                      }
                      if (value >> 8 > 0) {
                          value >>= 8;
                          result += 8;
                      }
                      if (value >> 4 > 0) {
                          value >>= 4;
                          result += 4;
                      }
                      if (value >> 2 > 0) {
                          value >>= 2;
                          result += 2;
                      }
                      if (value >> 1 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
          
              /**
               * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log2(value);
                      return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                  }
              }
          
              /**
               * @dev Return the log in base 10, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >= 10**64) {
                          value /= 10**64;
                          result += 64;
                      }
                      if (value >= 10**32) {
                          value /= 10**32;
                          result += 32;
                      }
                      if (value >= 10**16) {
                          value /= 10**16;
                          result += 16;
                      }
                      if (value >= 10**8) {
                          value /= 10**8;
                          result += 8;
                      }
                      if (value >= 10**4) {
                          value /= 10**4;
                          result += 4;
                      }
                      if (value >= 10**2) {
                          value /= 10**2;
                          result += 2;
                      }
                      if (value >= 10**1) {
                          result += 1;
                      }
                  }
                  return result;
              }
          
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log10(value);
                      return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
                  }
              }
          
              /**
               * @dev Return the log in base 256, rounded down, of a positive value.
               * Returns 0 if given 0.
               *
               * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
               */
              function log256(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 16;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 8;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 4;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 2;
                      }
                      if (value >> 8 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
          
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
                  }
              }
          }
          
          
          // File @openzeppelin/contracts/utils/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev String operations.
           */
          library Strings {
              bytes16 private constant _SYMBOLS = "0123456789abcdef";
              uint8 private constant _ADDRESS_LENGTH = 20;
          
              /**
               * @dev Converts a `uint256` to its ASCII `string` decimal representation.
               */
              function toString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      uint256 length = Math.log10(value) + 1;
                      string memory buffer = new string(length);
                      uint256 ptr;
                      /// @solidity memory-safe-assembly
                      assembly {
                          ptr := add(buffer, add(32, length))
                      }
                      while (true) {
                          ptr--;
                          /// @solidity memory-safe-assembly
                          assembly {
                              mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                          }
                          value /= 10;
                          if (value == 0) break;
                      }
                      return buffer;
                  }
              }
          
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
          
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  bytes memory buffer = new bytes(2 * length + 2);
                  buffer[0] = "0";
                  buffer[1] = "x";
                  for (uint256 i = 2 * length + 1; i > 1; --i) {
                      buffer[i] = _SYMBOLS[value & 0xf];
                      value >>= 4;
                  }
                  require(value == 0, "Strings: hex length insufficient");
                  return string(buffer);
              }
          
              /**
               * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
               */
              function toHexString(address addr) internal pure returns (string memory) {
                  return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
              }
          }
          
          
          // File @openzeppelin/contracts/utils/cryptography/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
           *
           * These functions can be used to verify that a message was signed by the holder
           * of the private keys of a given address.
           */
          library ECDSA {
              enum RecoverError {
                  NoError,
                  InvalidSignature,
                  InvalidSignatureLength,
                  InvalidSignatureS,
                  InvalidSignatureV // Deprecated in v4.8
              }
          
              function _throwError(RecoverError error) private pure {
                  if (error == RecoverError.NoError) {
                      return; // no error: do nothing
                  } else if (error == RecoverError.InvalidSignature) {
                      revert("ECDSA: invalid signature");
                  } else if (error == RecoverError.InvalidSignatureLength) {
                      revert("ECDSA: invalid signature length");
                  } else if (error == RecoverError.InvalidSignatureS) {
                      revert("ECDSA: invalid signature 's' value");
                  }
              }
          
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature` or error string. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               *
               * Documentation for signature generation:
               * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
               * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
               *
               * _Available since v4.3._
               */
              function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
                  if (signature.length == 65) {
                      bytes32 r;
                      bytes32 s;
                      uint8 v;
                      // ecrecover takes the signature parameters, and the only way to get them
                      // currently is to use assembly.
                      /// @solidity memory-safe-assembly
                      assembly {
                          r := mload(add(signature, 0x20))
                          s := mload(add(signature, 0x40))
                          v := byte(0, mload(add(signature, 0x60)))
                      }
                      return tryRecover(hash, v, r, s);
                  } else {
                      return (address(0), RecoverError.InvalidSignatureLength);
                  }
              }
          
              /**
               * @dev Returns the address that signed a hashed message (`hash`) with
               * `signature`. This address can then be used for verification purposes.
               *
               * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
               * this function rejects them by requiring the `s` value to be in the lower
               * half order, and the `v` value to be either 27 or 28.
               *
               * IMPORTANT: `hash` _must_ be the result of a hash operation for the
               * verification to be secure: it is possible to craft signatures that
               * recover to arbitrary addresses for non-hashed data. A safe way to ensure
               * this is by receiving a hash of the original message (which may otherwise
               * be too long), and then calling {toEthSignedMessageHash} on it.
               */
              function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, signature);
                  _throwError(error);
                  return recovered;
              }
          
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
               *
               * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
               *
               * _Available since v4.3._
               */
              function tryRecover(
                  bytes32 hash,
                  bytes32 r,
                  bytes32 vs
              ) internal pure returns (address, RecoverError) {
                  bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                  uint8 v = uint8((uint256(vs) >> 255) + 27);
                  return tryRecover(hash, v, r, s);
              }
          
              /**
               * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
               *
               * _Available since v4.2._
               */
              function recover(
                  bytes32 hash,
                  bytes32 r,
                  bytes32 vs
              ) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, r, vs);
                  _throwError(error);
                  return recovered;
              }
          
              /**
               * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
               * `r` and `s` signature fields separately.
               *
               * _Available since v4.3._
               */
              function tryRecover(
                  bytes32 hash,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) internal pure returns (address, RecoverError) {
                  // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                  // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                  // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                  // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                  //
                  // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                  // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                  // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                  // these malleable signatures as well.
                  if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                      return (address(0), RecoverError.InvalidSignatureS);
                  }
          
                  // If the signature is valid (and not malleable), return the signer address
                  address signer = ecrecover(hash, v, r, s);
                  if (signer == address(0)) {
                      return (address(0), RecoverError.InvalidSignature);
                  }
          
                  return (signer, RecoverError.NoError);
              }
          
              /**
               * @dev Overload of {ECDSA-recover} that receives the `v`,
               * `r` and `s` signature fields separately.
               */
              function recover(
                  bytes32 hash,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) internal pure returns (address) {
                  (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
                  _throwError(error);
                  return recovered;
              }
          
              /**
               * @dev Returns an Ethereum Signed Message, created from a `hash`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
                  // 32 is the length in bytes of hash,
                  // enforced by the type signature above
                  return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
              }
          
              /**
               * @dev Returns an Ethereum Signed Message, created from `s`. This
               * produces hash corresponding to the one signed with the
               * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
               * JSON-RPC method as part of EIP-191.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
              }
          
              /**
               * @dev Returns an Ethereum Signed Typed Data, created from a
               * `domainSeparator` and a `structHash`. This produces hash corresponding
               * to the one signed with the
               * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
               * JSON-RPC method as part of EIP-712.
               *
               * See {recover}.
               */
              function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
              }
          }
          
          
          // File @openzeppelin/contracts/utils/structs/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
          // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           *
           * [WARNING]
           * ====
           * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
           * unusable.
           * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
           *
           * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
           * array of EnumerableSet.
           * ====
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
          
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
          
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
          
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
          
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
          
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastValue = set._values[lastIndex];
          
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastValue;
                          // Update the index for the moved value
                          set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                      }
          
                      // Delete the slot where the moved value was stored
                      set._values.pop();
          
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
          
                      return true;
                  } else {
                      return false;
                  }
              }
          
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
          
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
          
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
          
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
          
              // Bytes32Set
          
              struct Bytes32Set {
                  Set _inner;
              }
          
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
          
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
          
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
          
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
          
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  bytes32[] memory result;
          
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
          
                  return result;
              }
          
              // AddressSet
          
              struct AddressSet {
                  Set _inner;
              }
          
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
          
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
          
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
          
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
          
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
          
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
          
                  return result;
              }
          
              // UintSet
          
              struct UintSet {
                  Set _inner;
              }
          
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
          
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
          
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
          
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
          
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
          
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
          
                  return result;
              }
          }
          
          
          // File interfaces/IMultisigIsm.sol
          
          
          pragma solidity >=0.6.0;
          
          interface IMultisigIsm is IInterchainSecurityModule {
              /**
               * @notice Returns the set of validators responsible for verifying _message
               * and the number of signatures required
               * @dev Can change based on the content of _message
               * @param _message Hyperlane formatted interchain message
               * @return validators The array of validator addresses
               * @return threshold The number of validator signatures needed
               */
              function validatorsAndThreshold(bytes calldata _message)
                  external
                  view
                  returns (address[] memory validators, uint8 threshold);
          }
          
          
          // File contracts/libs/TypeCasts.sol
          
          
          pragma solidity >=0.6.11;
          
          library TypeCasts {
              // treat it as a null-terminated string of max 32 bytes
              function coerceString(bytes32 _buf)
                  internal
                  pure
                  returns (string memory _newStr)
              {
                  uint8 _slen = 0;
                  while (_slen < 32 && _buf[_slen] != 0) {
                      _slen++;
                  }
          
                  // solhint-disable-next-line no-inline-assembly
                  assembly {
                      _newStr := mload(0x40)
                      mstore(0x40, add(_newStr, 0x40)) // may end up with extra
                      mstore(_newStr, _slen)
                      mstore(add(_newStr, 0x20), _buf)
                  }
              }
          
              // alignment preserving cast
              function addressToBytes32(address _addr) internal pure returns (bytes32) {
                  return bytes32(uint256(uint160(_addr)));
              }
          
              // alignment preserving cast
              function bytes32ToAddress(bytes32 _buf) internal pure returns (address) {
                  return address(uint160(uint256(_buf)));
              }
          }
          
          
          // File contracts/libs/Message.sol
          
          
          pragma solidity >=0.8.0;
          
          /**
           * @title Hyperlane Message Library
           * @notice Library for formatted messages used by Mailbox
           **/
          library Message {
              using TypeCasts for bytes32;
          
              uint256 private constant VERSION_OFFSET = 0;
              uint256 private constant NONCE_OFFSET = 1;
              uint256 private constant ORIGIN_OFFSET = 5;
              uint256 private constant SENDER_OFFSET = 9;
              uint256 private constant DESTINATION_OFFSET = 41;
              uint256 private constant RECIPIENT_OFFSET = 45;
              uint256 private constant BODY_OFFSET = 77;
          
              /**
               * @notice Returns formatted (packed) Hyperlane message with provided fields
               * @dev This function should only be used in memory message construction.
               * @param _version The version of the origin and destination Mailboxes
               * @param _nonce A nonce to uniquely identify the message on its origin chain
               * @param _originDomain Domain of origin chain
               * @param _sender Address of sender as bytes32
               * @param _destinationDomain Domain of destination chain
               * @param _recipient Address of recipient on destination chain as bytes32
               * @param _messageBody Raw bytes of message body
               * @return Formatted message
               */
              function formatMessage(
                  uint8 _version,
                  uint32 _nonce,
                  uint32 _originDomain,
                  bytes32 _sender,
                  uint32 _destinationDomain,
                  bytes32 _recipient,
                  bytes calldata _messageBody
              ) internal pure returns (bytes memory) {
                  return
                      abi.encodePacked(
                          _version,
                          _nonce,
                          _originDomain,
                          _sender,
                          _destinationDomain,
                          _recipient,
                          _messageBody
                      );
              }
          
              /**
               * @notice Returns the message ID.
               * @param _message ABI encoded Hyperlane message.
               * @return ID of `_message`
               */
              function id(bytes memory _message) internal pure returns (bytes32) {
                  return keccak256(_message);
              }
          
              /**
               * @notice Returns the message version.
               * @param _message ABI encoded Hyperlane message.
               * @return Version of `_message`
               */
              function version(bytes calldata _message) internal pure returns (uint8) {
                  return uint8(bytes1(_message[VERSION_OFFSET:NONCE_OFFSET]));
              }
          
              /**
               * @notice Returns the message nonce.
               * @param _message ABI encoded Hyperlane message.
               * @return Nonce of `_message`
               */
              function nonce(bytes calldata _message) internal pure returns (uint32) {
                  return uint32(bytes4(_message[NONCE_OFFSET:ORIGIN_OFFSET]));
              }
          
              /**
               * @notice Returns the message origin domain.
               * @param _message ABI encoded Hyperlane message.
               * @return Origin domain of `_message`
               */
              function origin(bytes calldata _message) internal pure returns (uint32) {
                  return uint32(bytes4(_message[ORIGIN_OFFSET:SENDER_OFFSET]));
              }
          
              /**
               * @notice Returns the message sender as bytes32.
               * @param _message ABI encoded Hyperlane message.
               * @return Sender of `_message` as bytes32
               */
              function sender(bytes calldata _message) internal pure returns (bytes32) {
                  return bytes32(_message[SENDER_OFFSET:DESTINATION_OFFSET]);
              }
          
              /**
               * @notice Returns the message sender as address.
               * @param _message ABI encoded Hyperlane message.
               * @return Sender of `_message` as address
               */
              function senderAddress(bytes calldata _message)
                  internal
                  pure
                  returns (address)
              {
                  return sender(_message).bytes32ToAddress();
              }
          
              /**
               * @notice Returns the message destination domain.
               * @param _message ABI encoded Hyperlane message.
               * @return Destination domain of `_message`
               */
              function destination(bytes calldata _message)
                  internal
                  pure
                  returns (uint32)
              {
                  return uint32(bytes4(_message[DESTINATION_OFFSET:RECIPIENT_OFFSET]));
              }
          
              /**
               * @notice Returns the message recipient as bytes32.
               * @param _message ABI encoded Hyperlane message.
               * @return Recipient of `_message` as bytes32
               */
              function recipient(bytes calldata _message)
                  internal
                  pure
                  returns (bytes32)
              {
                  return bytes32(_message[RECIPIENT_OFFSET:BODY_OFFSET]);
              }
          
              /**
               * @notice Returns the message recipient as address.
               * @param _message ABI encoded Hyperlane message.
               * @return Recipient of `_message` as address
               */
              function recipientAddress(bytes calldata _message)
                  internal
                  pure
                  returns (address)
              {
                  return recipient(_message).bytes32ToAddress();
              }
          
              /**
               * @notice Returns the message body.
               * @param _message ABI encoded Hyperlane message.
               * @return Body of `_message`
               */
              function body(bytes calldata _message)
                  internal
                  pure
                  returns (bytes calldata)
              {
                  return bytes(_message[BODY_OFFSET:]);
              }
          }
          
          
          // File contracts/libs/MultisigIsmMetadata.sol
          
          
          pragma solidity >=0.8.0;
          
          /**
           * Format of metadata:
           * [   0:  32] Merkle root
           * [  32:  36] Root index
           * [  36:  68] Origin mailbox address
           * [  68:1092] Merkle proof
           * [1092:1093] Threshold
           * [1093:????] Validator signatures, 65 bytes each, length == Threshold
           * [????:????] Addresses of the entire validator set, left padded to bytes32
           */
          library MultisigIsmMetadata {
              uint256 private constant MERKLE_ROOT_OFFSET = 0;
              uint256 private constant MERKLE_INDEX_OFFSET = 32;
              uint256 private constant ORIGIN_MAILBOX_OFFSET = 36;
              uint256 private constant MERKLE_PROOF_OFFSET = 68;
              uint256 private constant THRESHOLD_OFFSET = 1092;
              uint256 private constant SIGNATURES_OFFSET = 1093;
              uint256 private constant SIGNATURE_LENGTH = 65;
          
              /**
               * @notice Returns the merkle root of the signed checkpoint.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return Merkle root of the signed checkpoint
               */
              function root(bytes calldata _metadata) internal pure returns (bytes32) {
                  return bytes32(_metadata[MERKLE_ROOT_OFFSET:MERKLE_INDEX_OFFSET]);
              }
          
              /**
               * @notice Returns the index of the signed checkpoint.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return Index of the signed checkpoint
               */
              function index(bytes calldata _metadata) internal pure returns (uint32) {
                  return
                      uint32(
                          bytes4(_metadata[MERKLE_INDEX_OFFSET:ORIGIN_MAILBOX_OFFSET])
                      );
              }
          
              /**
               * @notice Returns the origin mailbox of the signed checkpoint as bytes32.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return Origin mailbox of the signed checkpoint as bytes32
               */
              function originMailbox(bytes calldata _metadata)
                  internal
                  pure
                  returns (bytes32)
              {
                  return bytes32(_metadata[ORIGIN_MAILBOX_OFFSET:MERKLE_PROOF_OFFSET]);
              }
          
              /**
               * @notice Returns the merkle proof branch of the message.
               * @dev This appears to be more gas efficient than returning a calldata
               * slice and using that.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return Merkle proof branch of the message.
               */
              function proof(bytes calldata _metadata)
                  internal
                  pure
                  returns (bytes32[32] memory)
              {
                  return
                      abi.decode(
                          _metadata[MERKLE_PROOF_OFFSET:THRESHOLD_OFFSET],
                          (bytes32[32])
                      );
              }
          
              /**
               * @notice Returns the number of required signatures. Verified against
               * the commitment stored in the module.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return The number of required signatures.
               */
              function threshold(bytes calldata _metadata) internal pure returns (uint8) {
                  return uint8(bytes1(_metadata[THRESHOLD_OFFSET:SIGNATURES_OFFSET]));
              }
          
              /**
               * @notice Returns the validator ECDSA signature at `_index`.
               * @dev Assumes signatures are sorted by validator
               * @dev Assumes `_metadata` encodes `threshold` signatures.
               * @dev Assumes `_index` is less than `threshold`
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @param _index The index of the signature to return.
               * @return The validator ECDSA signature at `_index`.
               */
              function signatureAt(bytes calldata _metadata, uint256 _index)
                  internal
                  pure
                  returns (bytes calldata)
              {
                  uint256 _start = SIGNATURES_OFFSET + (_index * SIGNATURE_LENGTH);
                  uint256 _end = _start + SIGNATURE_LENGTH;
                  return _metadata[_start:_end];
              }
          
              /**
               * @notice Returns the validator address at `_index`.
               * @dev Assumes `_index` is less than the number of validators
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @param _index The index of the validator to return.
               * @return The validator address at `_index`.
               */
              function validatorAt(bytes calldata _metadata, uint256 _index)
                  internal
                  pure
                  returns (address)
              {
                  // Validator addresses are left padded to bytes32 in order to match
                  // abi.encodePacked(address[]).
                  uint256 _start = _validatorsOffset(_metadata) + (_index * 32) + 12;
                  uint256 _end = _start + 20;
                  return address(bytes20(_metadata[_start:_end]));
              }
          
              /**
               * @notice Returns the validator set encoded as bytes. Verified against the
               * commitment stored in the module.
               * @dev Validator addresses are encoded as tightly packed array of bytes32,
               * sorted to match the enumerable set stored by the module.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return The validator set encoded as bytes.
               */
              function validators(bytes calldata _metadata)
                  internal
                  pure
                  returns (bytes calldata)
              {
                  return _metadata[_validatorsOffset(_metadata):];
              }
          
              /**
               * @notice Returns the size of the validator set encoded in the metadata
               * @dev Validator addresses are encoded as tightly packed array of bytes32,
               * sorted to match the enumerable set stored by the module.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return The size of the validator set encoded in the metadata
               */
              function commitment(bytes calldata _metadata)
                  internal
                  pure
                  returns (uint256)
              {
                  return (_metadata.length - _validatorsOffset(_metadata)) / 32;
              }
          
              /**
               * @notice Returns the size of the validator set encoded in the metadata
               * @dev Validator addresses are encoded as tightly packed array of bytes32,
               * sorted to match the enumerable set stored by the module.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return The size of the validator set encoded in the metadata
               */
              function validatorCount(bytes calldata _metadata)
                  internal
                  pure
                  returns (uint256)
              {
                  return (_metadata.length - _validatorsOffset(_metadata)) / 32;
              }
          
              /**
               * @notice Returns the offset in bytes of the list of validators within
               * `_metadata`.
               * @param _metadata ABI encoded Multisig ISM metadata.
               * @return The index at which the list of validators starts
               */
              function _validatorsOffset(bytes calldata _metadata)
                  private
                  pure
                  returns (uint256)
              {
                  return
                      SIGNATURES_OFFSET +
                      (uint256(threshold(_metadata)) * SIGNATURE_LENGTH);
              }
          }
          
          
          // File contracts/libs/Merkle.sol
          
          
          pragma solidity >=0.6.11;
          
          // work based on eth2 deposit contract, which is used under CC0-1.0
          
          /**
           * @title MerkleLib
           * @author Celo Labs Inc.
           * @notice An incremental merkle tree modeled on the eth2 deposit contract.
           **/
          library MerkleLib {
              uint256 internal constant TREE_DEPTH = 32;
              uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1;
          
              /**
               * @notice Struct representing incremental merkle tree. Contains current
               * branch and the number of inserted leaves in the tree.
               **/
              struct Tree {
                  bytes32[TREE_DEPTH] branch;
                  uint256 count;
              }
          
              /**
               * @notice Inserts `_node` into merkle tree
               * @dev Reverts if tree is full
               * @param _node Element to insert into tree
               **/
              function insert(Tree storage _tree, bytes32 _node) internal {
                  require(_tree.count < MAX_LEAVES, "merkle tree full");
          
                  _tree.count += 1;
                  uint256 size = _tree.count;
                  for (uint256 i = 0; i < TREE_DEPTH; i++) {
                      if ((size & 1) == 1) {
                          _tree.branch[i] = _node;
                          return;
                      }
                      _node = keccak256(abi.encodePacked(_tree.branch[i], _node));
                      size /= 2;
                  }
                  // As the loop should always end prematurely with the `return` statement,
                  // this code should be unreachable. We assert `false` just to be safe.
                  assert(false);
              }
          
              /**
               * @notice Calculates and returns`_tree`'s current root given array of zero
               * hashes
               * @param _zeroes Array of zero hashes
               * @return _current Calculated root of `_tree`
               **/
              function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes)
                  internal
                  view
                  returns (bytes32 _current)
              {
                  uint256 _index = _tree.count;
          
                  for (uint256 i = 0; i < TREE_DEPTH; i++) {
                      uint256 _ithBit = (_index >> i) & 0x01;
                      bytes32 _next = _tree.branch[i];
                      if (_ithBit == 1) {
                          _current = keccak256(abi.encodePacked(_next, _current));
                      } else {
                          _current = keccak256(abi.encodePacked(_current, _zeroes[i]));
                      }
                  }
              }
          
              /// @notice Calculates and returns`_tree`'s current root
              function root(Tree storage _tree) internal view returns (bytes32) {
                  return rootWithCtx(_tree, zeroHashes());
              }
          
              /// @notice Returns array of TREE_DEPTH zero hashes
              /// @return _zeroes Array of TREE_DEPTH zero hashes
              function zeroHashes()
                  internal
                  pure
                  returns (bytes32[TREE_DEPTH] memory _zeroes)
              {
                  _zeroes[0] = Z_0;
                  _zeroes[1] = Z_1;
                  _zeroes[2] = Z_2;
                  _zeroes[3] = Z_3;
                  _zeroes[4] = Z_4;
                  _zeroes[5] = Z_5;
                  _zeroes[6] = Z_6;
                  _zeroes[7] = Z_7;
                  _zeroes[8] = Z_8;
                  _zeroes[9] = Z_9;
                  _zeroes[10] = Z_10;
                  _zeroes[11] = Z_11;
                  _zeroes[12] = Z_12;
                  _zeroes[13] = Z_13;
                  _zeroes[14] = Z_14;
                  _zeroes[15] = Z_15;
                  _zeroes[16] = Z_16;
                  _zeroes[17] = Z_17;
                  _zeroes[18] = Z_18;
                  _zeroes[19] = Z_19;
                  _zeroes[20] = Z_20;
                  _zeroes[21] = Z_21;
                  _zeroes[22] = Z_22;
                  _zeroes[23] = Z_23;
                  _zeroes[24] = Z_24;
                  _zeroes[25] = Z_25;
                  _zeroes[26] = Z_26;
                  _zeroes[27] = Z_27;
                  _zeroes[28] = Z_28;
                  _zeroes[29] = Z_29;
                  _zeroes[30] = Z_30;
                  _zeroes[31] = Z_31;
              }
          
              /**
               * @notice Calculates and returns the merkle root for the given leaf
               * `_item`, a merkle branch, and the index of `_item` in the tree.
               * @param _item Merkle leaf
               * @param _branch Merkle proof
               * @param _index Index of `_item` in tree
               * @return _current Calculated merkle root
               **/
              function branchRoot(
                  bytes32 _item,
                  bytes32[TREE_DEPTH] memory _branch,
                  uint256 _index
              ) internal pure returns (bytes32 _current) {
                  _current = _item;
          
                  for (uint256 i = 0; i < TREE_DEPTH; i++) {
                      uint256 _ithBit = (_index >> i) & 0x01;
                      bytes32 _next = _branch[i];
                      if (_ithBit == 1) {
                          _current = keccak256(abi.encodePacked(_next, _current));
                      } else {
                          _current = keccak256(abi.encodePacked(_current, _next));
                      }
                  }
              }
          
              // keccak256 zero hashes
              bytes32 internal constant Z_0 =
                  hex"0000000000000000000000000000000000000000000000000000000000000000";
              bytes32 internal constant Z_1 =
                  hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5";
              bytes32 internal constant Z_2 =
                  hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30";
              bytes32 internal constant Z_3 =
                  hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85";
              bytes32 internal constant Z_4 =
                  hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344";
              bytes32 internal constant Z_5 =
                  hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d";
              bytes32 internal constant Z_6 =
                  hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968";
              bytes32 internal constant Z_7 =
                  hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83";
              bytes32 internal constant Z_8 =
                  hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af";
              bytes32 internal constant Z_9 =
                  hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0";
              bytes32 internal constant Z_10 =
                  hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5";
              bytes32 internal constant Z_11 =
                  hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892";
              bytes32 internal constant Z_12 =
                  hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c";
              bytes32 internal constant Z_13 =
                  hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb";
              bytes32 internal constant Z_14 =
                  hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc";
              bytes32 internal constant Z_15 =
                  hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2";
              bytes32 internal constant Z_16 =
                  hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f";
              bytes32 internal constant Z_17 =
                  hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a";
              bytes32 internal constant Z_18 =
                  hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0";
              bytes32 internal constant Z_19 =
                  hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0";
              bytes32 internal constant Z_20 =
                  hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2";
              bytes32 internal constant Z_21 =
                  hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9";
              bytes32 internal constant Z_22 =
                  hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377";
              bytes32 internal constant Z_23 =
                  hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652";
              bytes32 internal constant Z_24 =
                  hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef";
              bytes32 internal constant Z_25 =
                  hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d";
              bytes32 internal constant Z_26 =
                  hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0";
              bytes32 internal constant Z_27 =
                  hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e";
              bytes32 internal constant Z_28 =
                  hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e";
              bytes32 internal constant Z_29 =
                  hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322";
              bytes32 internal constant Z_30 =
                  hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735";
              bytes32 internal constant Z_31 =
                  hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9";
          }
          
          
          // File contracts/isms/MultisigIsm.sol
          
          
          pragma solidity >=0.8.0;
          
          // ============ External Imports ============
          
          
          
          // ============ Internal Imports ============
          
          
          
          
          /**
           * @title MultisigIsm
           * @notice Manages an ownable set of validators that ECDSA sign checkpoints to
           * reach a quorum.
           */
          contract MultisigIsm is IMultisigIsm, Ownable {
              // ============ Libraries ============
          
              using EnumerableSet for EnumerableSet.AddressSet;
              using Message for bytes;
              using MultisigIsmMetadata for bytes;
              using MerkleLib for MerkleLib.Tree;
          
              // ============ Constants ============
          
              uint8 public constant moduleType = 3;
          
              // ============ Mutable Storage ============
          
              /// @notice The validator threshold for each remote domain.
              mapping(uint32 => uint8) public threshold;
          
              /// @notice The validator set for each remote domain.
              mapping(uint32 => EnumerableSet.AddressSet) private validatorSet;
          
              /// @notice A succinct commitment to the validator set and threshold for each remote
              /// domain.
              mapping(uint32 => bytes32) public commitment;
          
              // ============ Events ============
          
              /**
               * @notice Emitted when a validator is enrolled in a validator set.
               * @param domain The remote domain of the validator set.
               * @param validator The address of the validator.
               * @param validatorCount The number of enrolled validators in the validator set.
               */
              event ValidatorEnrolled(
                  uint32 indexed domain,
                  address indexed validator,
                  uint256 validatorCount
              );
          
              /**
               * @notice Emitted when a validator is unenrolled from a validator set.
               * @param domain The remote domain of the validator set.
               * @param validator The address of the validator.
               * @param validatorCount The number of enrolled validators in the validator set.
               */
              event ValidatorUnenrolled(
                  uint32 indexed domain,
                  address indexed validator,
                  uint256 validatorCount
              );
          
              /**
               * @notice Emitted when the quorum threshold is set.
               * @param domain The remote domain of the validator set.
               * @param threshold The new quorum threshold.
               */
              event ThresholdSet(uint32 indexed domain, uint8 threshold);
          
              /**
               * @notice Emitted when the validator set or threshold changes.
               * @param domain The remote domain of the validator set.
               * @param commitment A commitment to the validator set and threshold.
               */
              event CommitmentUpdated(uint32 domain, bytes32 commitment);
          
              // ============ Constructor ============
          
              // solhint-disable-next-line no-empty-blocks
              constructor() Ownable() {}
          
              // ============ External Functions ============
          
              /**
               * @notice Enrolls multiple validators into a validator set.
               * @dev Reverts if `_validator` is already in the validator set.
               * @param _domains The remote domains of the validator sets.
               * @param _validators The validators to add to the validator sets.
               * @dev _validators[i] are the validators to enroll for _domains[i].
               */
              function enrollValidators(
                  uint32[] calldata _domains,
                  address[][] calldata _validators
              ) external onlyOwner {
                  require(_domains.length == _validators.length, "!length");
                  for (uint256 i = 0; i < _domains.length; i += 1) {
                      address[] calldata _domainValidators = _validators[i];
                      for (uint256 j = 0; j < _domainValidators.length; j += 1) {
                          _enrollValidator(_domains[i], _domainValidators[j]);
                      }
                      _updateCommitment(_domains[i]);
                  }
              }
          
              /**
               * @notice Enrolls a validator into a validator set.
               * @dev Reverts if `_validator` is already in the validator set.
               * @param _domain The remote domain of the validator set.
               * @param _validator The validator to add to the validator set.
               */
              function enrollValidator(uint32 _domain, address _validator)
                  external
                  onlyOwner
              {
                  _enrollValidator(_domain, _validator);
                  _updateCommitment(_domain);
              }
          
              /**
               * @notice Unenrolls a validator from a validator set.
               * @dev Reverts if `_validator` is not in the validator set.
               * @param _domain The remote domain of the validator set.
               * @param _validator The validator to remove from the validator set.
               */
              function unenrollValidator(uint32 _domain, address _validator)
                  external
                  onlyOwner
              {
                  require(validatorSet[_domain].remove(_validator), "!enrolled");
                  uint256 _validatorCount = validatorCount(_domain);
                  require(
                      _validatorCount >= threshold[_domain],
                      "violates quorum threshold"
                  );
                  _updateCommitment(_domain);
                  emit ValidatorUnenrolled(_domain, _validator, _validatorCount);
              }
          
              /**
               * @notice Sets the quorum threshold for multiple domains.
               * @param _domains The remote domains of the validator sets.
               * @param _thresholds The new quorum thresholds.
               */
              function setThresholds(
                  uint32[] calldata _domains,
                  uint8[] calldata _thresholds
              ) external onlyOwner {
                  require(_domains.length == _thresholds.length, "!length");
                  for (uint256 i = 0; i < _domains.length; i += 1) {
                      setThreshold(_domains[i], _thresholds[i]);
                  }
              }
          
              /**
               * @notice Returns whether an address is enrolled in a validator set.
               * @param _domain The remote domain of the validator set.
               * @param _address The address to test for set membership.
               * @return True if the address is enrolled, false otherwise.
               */
              function isEnrolled(uint32 _domain, address _address)
                  external
                  view
                  returns (bool)
              {
                  EnumerableSet.AddressSet storage _validatorSet = validatorSet[_domain];
                  return _validatorSet.contains(_address);
              }
          
              // ============ Public Functions ============
          
              /**
               * @notice Sets the quorum threshold.
               * @param _domain The remote domain of the validator set.
               * @param _threshold The new quorum threshold.
               */
              function setThreshold(uint32 _domain, uint8 _threshold) public onlyOwner {
                  require(
                      _threshold > 0 && _threshold <= validatorCount(_domain),
                      "!range"
                  );
                  threshold[_domain] = _threshold;
                  emit ThresholdSet(_domain, _threshold);
          
                  _updateCommitment(_domain);
              }
          
              /**
               * @notice Verifies that a quorum of the origin domain's validators signed
               * a checkpoint, and verifies the merkle proof of `_message` against that
               * checkpoint.
               * @param _metadata ABI encoded module metadata (see MultisigIsmMetadata.sol)
               * @param _message Formatted Hyperlane message (see Message.sol).
               */
              function verify(bytes calldata _metadata, bytes calldata _message)
                  public
                  view
                  returns (bool)
              {
                  require(_verifyMerkleProof(_metadata, _message), "!merkle");
                  require(_verifyValidatorSignatures(_metadata, _message), "!sigs");
                  return true;
              }
          
              /**
               * @notice Gets the current validator set
               * @param _domain The remote domain of the validator set.
               * @return The addresses of the validator set.
               */
              function validators(uint32 _domain) public view returns (address[] memory) {
                  EnumerableSet.AddressSet storage _validatorSet = validatorSet[_domain];
                  uint256 _validatorCount = _validatorSet.length();
                  address[] memory _validators = new address[](_validatorCount);
                  for (uint256 i = 0; i < _validatorCount; i++) {
                      _validators[i] = _validatorSet.at(i);
                  }
                  return _validators;
              }
          
              /**
               * @notice Returns the set of validators responsible for verifying _message
               * and the number of signatures required
               * @dev Can change based on the content of _message
               * @param _message Hyperlane formatted interchain message
               * @return validators The array of validator addresses
               * @return threshold The number of validator signatures needed
               */
              function validatorsAndThreshold(bytes calldata _message)
                  external
                  view
                  returns (address[] memory, uint8)
              {
                  uint32 _origin = _message.origin();
                  address[] memory _validators = validators(_origin);
                  uint8 _threshold = threshold[_origin];
                  return (_validators, _threshold);
              }
          
              /**
               * @notice Returns the number of validators enrolled in the validator set.
               * @param _domain The remote domain of the validator set.
               * @return The number of validators enrolled in the validator set.
               */
              function validatorCount(uint32 _domain) public view returns (uint256) {
                  return validatorSet[_domain].length();
              }
          
              // ============ Internal Functions ============
          
              /**
               * @notice Enrolls a validator into a validator set.
               * @dev Reverts if `_validator` is already in the validator set.
               * @param _domain The remote domain of the validator set.
               * @param _validator The validator to add to the validator set.
               */
              function _enrollValidator(uint32 _domain, address _validator) internal {
                  require(_validator != address(0), "zero address");
                  require(validatorSet[_domain].add(_validator), "already enrolled");
                  emit ValidatorEnrolled(_domain, _validator, validatorCount(_domain));
              }
          
              /**
               * @notice Updates the commitment to the validator set for `_domain`.
               * @param _domain The remote domain of the validator set.
               * @return The commitment to the validator set for `_domain`.
               */
              function _updateCommitment(uint32 _domain) internal returns (bytes32) {
                  address[] memory _validators = validators(_domain);
                  uint8 _threshold = threshold[_domain];
                  bytes32 _commitment = keccak256(
                      abi.encodePacked(_threshold, _validators)
                  );
                  commitment[_domain] = _commitment;
                  emit CommitmentUpdated(_domain, _commitment);
                  return _commitment;
              }
          
              /**
               * @notice Verifies the merkle proof of `_message` against the provided
               * checkpoint.
               * @param _metadata ABI encoded module metadata (see MultisigIsmMetadata.sol)
               * @param _message Formatted Hyperlane message (see Message.sol).
               */
              function _verifyMerkleProof(
                  bytes calldata _metadata,
                  bytes calldata _message
              ) internal pure returns (bool) {
                  // calculate the expected root based on the proof
                  bytes32 _calculatedRoot = MerkleLib.branchRoot(
                      _message.id(),
                      _metadata.proof(),
                      _message.nonce()
                  );
                  return _calculatedRoot == _metadata.root();
              }
          
              /**
               * @notice Verifies that a quorum of the origin domain's validators signed
               * the provided checkpoint.
               * @param _metadata ABI encoded module metadata (see MultisigIsmMetadata.sol)
               * @param _message Formatted Hyperlane message (see Message.sol).
               */
              function _verifyValidatorSignatures(
                  bytes calldata _metadata,
                  bytes calldata _message
              ) internal view returns (bool) {
                  uint8 _threshold = _metadata.threshold();
                  bytes32 _digest;
                  {
                      uint32 _origin = _message.origin();
          
                      bytes32 _commitment = keccak256(
                          abi.encodePacked(_threshold, _metadata.validators())
                      );
                      // Ensures the validator set encoded in the metadata matches
                      // what we've stored on chain.
                      // NB: An empty validator set in `_metadata` will result in a
                      // non-zero computed commitment, and this check will fail
                      // as the commitment in storage will be zero.
                      require(_commitment == commitment[_origin], "!commitment");
                      _digest = _getCheckpointDigest(_metadata, _origin);
                  }
                  uint256 _validatorCount = _metadata.validatorCount();
                  uint256 _validatorIndex = 0;
                  // Assumes that signatures are ordered by validator
                  for (uint256 i = 0; i < _threshold; ++i) {
                      address _signer = ECDSA.recover(_digest, _metadata.signatureAt(i));
                      // Loop through remaining validators until we find a match
                      for (
                          ;
                          _validatorIndex < _validatorCount &&
                              _signer != _metadata.validatorAt(_validatorIndex);
                          ++_validatorIndex
                      ) {}
                      // Fail if we never found a match
                      require(_validatorIndex < _validatorCount, "!threshold");
                      ++_validatorIndex;
                  }
                  return true;
              }
          
              /**
               * @notice Returns the domain hash that validators are expected to use
               * when signing checkpoints.
               * @param _origin The origin domain of the checkpoint.
               * @param _originMailbox The address of the origin mailbox as bytes32.
               * @return The domain hash.
               */
              function _getDomainHash(uint32 _origin, bytes32 _originMailbox)
                  internal
                  pure
                  returns (bytes32)
              {
                  // Including the origin mailbox address in the signature allows the slashing
                  // protocol to enroll multiple mailboxes. Otherwise, a valid signature for
                  // mailbox A would be indistinguishable from a fraudulent signature for mailbox
                  // B.
                  // The slashing protocol should slash if validators sign attestations for
                  // anything other than a whitelisted mailbox.
                  return
                      keccak256(abi.encodePacked(_origin, _originMailbox, "HYPERLANE"));
              }
          
              /**
               * @notice Returns the digest validators are expected to sign when signing checkpoints.
               * @param _metadata ABI encoded module metadata (see MultisigIsmMetadata.sol)
               * @param _origin The origin domain of the checkpoint.
               * @return The digest of the checkpoint.
               */
              function _getCheckpointDigest(bytes calldata _metadata, uint32 _origin)
                  internal
                  pure
                  returns (bytes32)
              {
                  bytes32 _domainHash = _getDomainHash(
                      _origin,
                      _metadata.originMailbox()
                  );
                  return
                      ECDSA.toEthSignedMessageHash(
                          keccak256(
                              abi.encodePacked(
                                  _domainHash,
                                  _metadata.root(),
                                  _metadata.index()
                              )
                          )
                      );
              }
          }
          
          
          // File @openzeppelin/contracts/utils/structs/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableMap.sol)
          // This file was procedurally generated from scripts/generate/templates/EnumerableMap.js.
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Library for managing an enumerable variant of Solidity's
           * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
           * type.
           *
           * Maps have the following properties:
           *
           * - Entries are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Entries are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```
           * contract Example {
           *     // Add the library methods
           *     using EnumerableMap for EnumerableMap.UintToAddressMap;
           *
           *     // Declare a set state variable
           *     EnumerableMap.UintToAddressMap private myMap;
           * }
           * ```
           *
           * The following map types are supported:
           *
           * - `uint256 -> address` (`UintToAddressMap`) since v3.0.0
           * - `address -> uint256` (`AddressToUintMap`) since v4.6.0
           * - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0
           * - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0
           * - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0
           *
           * [WARNING]
           * ====
           * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
           * unusable.
           * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
           *
           * In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
           * array of EnumerableMap.
           * ====
           */
          library EnumerableMap {
              using EnumerableSet for EnumerableSet.Bytes32Set;
          
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Map type with
              // bytes32 keys and values.
              // The Map implementation uses private functions, and user-facing
              // implementations (such as Uint256ToAddressMap) are just wrappers around
              // the underlying Map.
              // This means that we can only create new EnumerableMaps for types that fit
              // in bytes32.
          
              struct Bytes32ToBytes32Map {
                  // Storage of keys
                  EnumerableSet.Bytes32Set _keys;
                  mapping(bytes32 => bytes32) _values;
              }
          
              /**
               * @dev Adds a key-value pair to a map, or updates the value for an existing
               * key. O(1).
               *
               * Returns true if the key was added to the map, that is if it was not
               * already present.
               */
              function set(
                  Bytes32ToBytes32Map storage map,
                  bytes32 key,
                  bytes32 value
              ) internal returns (bool) {
                  map._values[key] = value;
                  return map._keys.add(key);
              }
          
              /**
               * @dev Removes a key-value pair from a map. O(1).
               *
               * Returns true if the key was removed from the map, that is if it was present.
               */
              function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
                  delete map._values[key];
                  return map._keys.remove(key);
              }
          
              /**
               * @dev Returns true if the key is in the map. O(1).
               */
              function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
                  return map._keys.contains(key);
              }
          
              /**
               * @dev Returns the number of key-value pairs in the map. O(1).
               */
              function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
                  return map._keys.length();
              }
          
              /**
               * @dev Returns the key-value pair stored at position `index` in the map. O(1).
               *
               * Note that there are no guarantees on the ordering of entries inside the
               * array, and it may change when more entries are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
                  bytes32 key = map._keys.at(index);
                  return (key, map._values[key]);
              }
          
              /**
               * @dev Tries to returns the value associated with `key`. O(1).
               * Does not revert if `key` is not in the map.
               */
              function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32) {
                  bytes32 value = map._values[key];
                  if (value == bytes32(0)) {
                      return (contains(map, key), bytes32(0));
                  } else {
                      return (true, value);
                  }
              }
          
              /**
               * @dev Returns the value associated with `key`. O(1).
               *
               * Requirements:
               *
               * - `key` must be in the map.
               */
              function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
                  bytes32 value = map._values[key];
                  require(value != 0 || contains(map, key), "EnumerableMap: nonexistent key");
                  return value;
              }
          
              /**
               * @dev Same as {get}, with a custom error message when `key` is not in the map.
               *
               * CAUTION: This function is deprecated because it requires allocating memory for the error
               * message unnecessarily. For custom revert reasons use {tryGet}.
               */
              function get(
                  Bytes32ToBytes32Map storage map,
                  bytes32 key,
                  string memory errorMessage
              ) internal view returns (bytes32) {
                  bytes32 value = map._values[key];
                  require(value != 0 || contains(map, key), errorMessage);
                  return value;
              }
          
              // UintToUintMap
          
              struct UintToUintMap {
                  Bytes32ToBytes32Map _inner;
              }
          
              /**
               * @dev Adds a key-value pair to a map, or updates the value for an existing
               * key. O(1).
               *
               * Returns true if the key was added to the map, that is if it was not
               * already present.
               */
              function set(
                  UintToUintMap storage map,
                  uint256 key,
                  uint256 value
              ) internal returns (bool) {
                  return set(map._inner, bytes32(key), bytes32(value));
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the key was removed from the map, that is if it was present.
               */
              function remove(UintToUintMap storage map, uint256 key) internal returns (bool) {
                  return remove(map._inner, bytes32(key));
              }
          
              /**
               * @dev Returns true if the key is in the map. O(1).
               */
              function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) {
                  return contains(map._inner, bytes32(key));
              }
          
              /**
               * @dev Returns the number of elements in the map. O(1).
               */
              function length(UintToUintMap storage map) internal view returns (uint256) {
                  return length(map._inner);
              }
          
              /**
               * @dev Returns the element stored at position `index` in the set. O(1).
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) {
                  (bytes32 key, bytes32 value) = at(map._inner, index);
                  return (uint256(key), uint256(value));
              }
          
              /**
               * @dev Tries to returns the value associated with `key`. O(1).
               * Does not revert if `key` is not in the map.
               */
              function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool, uint256) {
                  (bool success, bytes32 value) = tryGet(map._inner, bytes32(key));
                  return (success, uint256(value));
              }
          
              /**
               * @dev Returns the value associated with `key`. O(1).
               *
               * Requirements:
               *
               * - `key` must be in the map.
               */
              function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {
                  return uint256(get(map._inner, bytes32(key)));
              }
          
              /**
               * @dev Same as {get}, with a custom error message when `key` is not in the map.
               *
               * CAUTION: This function is deprecated because it requires allocating memory for the error
               * message unnecessarily. For custom revert reasons use {tryGet}.
               */
              function get(
                  UintToUintMap storage map,
                  uint256 key,
                  string memory errorMessage
              ) internal view returns (uint256) {
                  return uint256(get(map._inner, bytes32(key), errorMessage));
              }
          
              // UintToAddressMap
          
              struct UintToAddressMap {
                  Bytes32ToBytes32Map _inner;
              }
          
              /**
               * @dev Adds a key-value pair to a map, or updates the value for an existing
               * key. O(1).
               *
               * Returns true if the key was added to the map, that is if it was not
               * already present.
               */
              function set(
                  UintToAddressMap storage map,
                  uint256 key,
                  address value
              ) internal returns (bool) {
                  return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the key was removed from the map, that is if it was present.
               */
              function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
                  return remove(map._inner, bytes32(key));
              }
          
              /**
               * @dev Returns true if the key is in the map. O(1).
               */
              function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
                  return contains(map._inner, bytes32(key));
              }
          
              /**
               * @dev Returns the number of elements in the map. O(1).
               */
              function length(UintToAddressMap storage map) internal view returns (uint256) {
                  return length(map._inner);
              }
          
              /**
               * @dev Returns the element stored at position `index` in the set. O(1).
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
                  (bytes32 key, bytes32 value) = at(map._inner, index);
                  return (uint256(key), address(uint160(uint256(value))));
              }
          
              /**
               * @dev Tries to returns the value associated with `key`. O(1).
               * Does not revert if `key` is not in the map.
               */
              function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
                  (bool success, bytes32 value) = tryGet(map._inner, bytes32(key));
                  return (success, address(uint160(uint256(value))));
              }
          
              /**
               * @dev Returns the value associated with `key`. O(1).
               *
               * Requirements:
               *
               * - `key` must be in the map.
               */
              function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
                  return address(uint160(uint256(get(map._inner, bytes32(key)))));
              }
          
              /**
               * @dev Same as {get}, with a custom error message when `key` is not in the map.
               *
               * CAUTION: This function is deprecated because it requires allocating memory for the error
               * message unnecessarily. For custom revert reasons use {tryGet}.
               */
              function get(
                  UintToAddressMap storage map,
                  uint256 key,
                  string memory errorMessage
              ) internal view returns (address) {
                  return address(uint160(uint256(get(map._inner, bytes32(key), errorMessage))));
              }
          
              // AddressToUintMap
          
              struct AddressToUintMap {
                  Bytes32ToBytes32Map _inner;
              }
          
              /**
               * @dev Adds a key-value pair to a map, or updates the value for an existing
               * key. O(1).
               *
               * Returns true if the key was added to the map, that is if it was not
               * already present.
               */
              function set(
                  AddressToUintMap storage map,
                  address key,
                  uint256 value
              ) internal returns (bool) {
                  return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the key was removed from the map, that is if it was present.
               */
              function remove(AddressToUintMap storage map, address key) internal returns (bool) {
                  return remove(map._inner, bytes32(uint256(uint160(key))));
              }
          
              /**
               * @dev Returns true if the key is in the map. O(1).
               */
              function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
                  return contains(map._inner, bytes32(uint256(uint160(key))));
              }
          
              /**
               * @dev Returns the number of elements in the map. O(1).
               */
              function length(AddressToUintMap storage map) internal view returns (uint256) {
                  return length(map._inner);
              }
          
              /**
               * @dev Returns the element stored at position `index` in the set. O(1).
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) {
                  (bytes32 key, bytes32 value) = at(map._inner, index);
                  return (address(uint160(uint256(key))), uint256(value));
              }
          
              /**
               * @dev Tries to returns the value associated with `key`. O(1).
               * Does not revert if `key` is not in the map.
               */
              function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) {
                  (bool success, bytes32 value) = tryGet(map._inner, bytes32(uint256(uint160(key))));
                  return (success, uint256(value));
              }
          
              /**
               * @dev Returns the value associated with `key`. O(1).
               *
               * Requirements:
               *
               * - `key` must be in the map.
               */
              function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
                  return uint256(get(map._inner, bytes32(uint256(uint160(key)))));
              }
          
              /**
               * @dev Same as {get}, with a custom error message when `key` is not in the map.
               *
               * CAUTION: This function is deprecated because it requires allocating memory for the error
               * message unnecessarily. For custom revert reasons use {tryGet}.
               */
              function get(
                  AddressToUintMap storage map,
                  address key,
                  string memory errorMessage
              ) internal view returns (uint256) {
                  return uint256(get(map._inner, bytes32(uint256(uint160(key))), errorMessage));
              }
          
              // Bytes32ToUintMap
          
              struct Bytes32ToUintMap {
                  Bytes32ToBytes32Map _inner;
              }
          
              /**
               * @dev Adds a key-value pair to a map, or updates the value for an existing
               * key. O(1).
               *
               * Returns true if the key was added to the map, that is if it was not
               * already present.
               */
              function set(
                  Bytes32ToUintMap storage map,
                  bytes32 key,
                  uint256 value
              ) internal returns (bool) {
                  return set(map._inner, key, bytes32(value));
              }
          
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the key was removed from the map, that is if it was present.
               */
              function remove(Bytes32ToUintMap storage map, bytes32 key) internal returns (bool) {
                  return remove(map._inner, key);
              }
          
              /**
               * @dev Returns true if the key is in the map. O(1).
               */
              function contains(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool) {
                  return contains(map._inner, key);
              }
          
              /**
               * @dev Returns the number of elements in the map. O(1).
               */
              function length(Bytes32ToUintMap storage map) internal view returns (uint256) {
                  return length(map._inner);
              }
          
              /**
               * @dev Returns the element stored at position `index` in the set. O(1).
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32ToUintMap storage map, uint256 index) internal view returns (bytes32, uint256) {
                  (bytes32 key, bytes32 value) = at(map._inner, index);
                  return (key, uint256(value));
              }
          
              /**
               * @dev Tries to returns the value associated with `key`. O(1).
               * Does not revert if `key` is not in the map.
               */
              function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool, uint256) {
                  (bool success, bytes32 value) = tryGet(map._inner, key);
                  return (success, uint256(value));
              }
          
              /**
               * @dev Returns the value associated with `key`. O(1).
               *
               * Requirements:
               *
               * - `key` must be in the map.
               */
              function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) {
                  return uint256(get(map._inner, key));
              }
          
              /**
               * @dev Same as {get}, with a custom error message when `key` is not in the map.
               *
               * CAUTION: This function is deprecated because it requires allocating memory for the error
               * message unnecessarily. For custom revert reasons use {tryGet}.
               */
              function get(
                  Bytes32ToUintMap storage map,
                  bytes32 key,
                  string memory errorMessage
              ) internal view returns (uint256) {
                  return uint256(get(map._inner, key, errorMessage));
              }
          }
          
          
          // File contracts/libs/EnumerableMapExtended.sol
          
          
          pragma solidity >=0.6.11;
          
          // ============ External Imports ============
          
          // extends EnumerableMap with uint256 => bytes32 type
          // modelled after https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.0/contracts/utils/structs/EnumerableMap.sol
          library EnumerableMapExtended {
              using EnumerableMap for EnumerableMap.Bytes32ToBytes32Map;
          
              struct UintToBytes32Map {
                  EnumerableMap.Bytes32ToBytes32Map _inner;
              }
          
              // ============ Library Functions ============
              function keys(UintToBytes32Map storage map)
                  internal
                  view
                  returns (bytes32[] storage)
              {
                  return map._inner._keys._inner._values;
              }
          
              function set(
                  UintToBytes32Map storage map,
                  uint256 key,
                  bytes32 value
              ) internal {
                  map._inner.set(bytes32(key), value);
              }
          
              function get(UintToBytes32Map storage map, uint256 key)
                  internal
                  view
                  returns (bytes32)
              {
                  return map._inner.get(bytes32(key));
              }
          
              function remove(UintToBytes32Map storage map, uint256 key)
                  internal
                  returns (bool)
              {
                  return map._inner.remove(bytes32(key));
              }
          
              function contains(UintToBytes32Map storage map, uint256 key)
                  internal
                  view
                  returns (bool)
              {
                  return map._inner.contains(bytes32(key));
              }
          
              function length(UintToBytes32Map storage map)
                  internal
                  view
                  returns (uint256)
              {
                  return map._inner.length();
              }
          
              function at(UintToBytes32Map storage map, uint256 index)
                  internal
                  view
                  returns (uint256, bytes32)
              {
                  (bytes32 key, bytes32 value) = map._inner.at(index);
                  return (uint256(key), value);
              }
          }
          
          
          // File contracts/upgrade/Versioned.sol
          
          
          pragma solidity >=0.6.11;
          
          /**
           * @title Versioned
           * @notice Version getter for contracts
           **/
          contract Versioned {
              uint8 public constant VERSION = 0;
          }
          
          
          // File interfaces/IMessageRecipient.sol
          
          
          pragma solidity >=0.6.11;
          
          interface IMessageRecipient {
              function handle(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes calldata _message
              ) external;
          }
          
          
          // File contracts/PausableReentrancyGuard.sol
          
          
          pragma solidity >=0.8.0;
          
          // adapted from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
          abstract contract PausableReentrancyGuardUpgradeable is Initializable {
              uint256 private constant _NOT_ENTERED = 1;
              uint256 private constant _ENTERED = 2;
              uint256 private constant _PAUSED = 3;
          
              uint256 private _status;
          
              /**
               * @dev MUST be called for `nonReentrant` to not always revert
               */
              function __PausableReentrancyGuard_init() internal onlyInitializing {
                  _status = _NOT_ENTERED;
              }
          
              function _isPaused() internal view returns (bool) {
                  return _status == _PAUSED;
              }
          
              function _pause() internal notPaused {
                  _status = _PAUSED;
              }
          
              function _unpause() internal {
                  require(_isPaused(), "!paused");
                  _status = _NOT_ENTERED;
              }
          
              /**
               * @dev Prevents a contract from being entered when paused.
               */
              modifier notPaused() {
                  require(!_isPaused(), "paused");
                  _;
              }
          
              /**
               * @dev Prevents a contract from calling itself, directly or indirectly.
               * Calling a `nonReentrant` function from another `nonReentrant`
               * function is not supported. It is possible to prevent this from happening
               * by making the `nonReentrant` function external, and making it call a
               * `private` function that does the actual work.
               */
              modifier nonReentrantAndNotPaused() {
                  // status must have been initialized
                  require(_status == _NOT_ENTERED, "reentrant call (or paused)");
          
                  // Any calls to nonReentrant after this point will fail
                  _status = _ENTERED;
          
                  _;
          
                  // By storing the original value once again, a refund is triggered (see
                  // https://eips.ethereum.org/EIPS/eip-2200)
                  _status = _NOT_ENTERED;
              }
          
              /**
               * @dev This empty reserved space is put in place to allow future versions to add new
               * variables without shifting down storage in the inheritance chain.
               * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
               */
              uint256[49] private __gap;
          }
          
          
          // File contracts/Mailbox.sol
          
          
          pragma solidity >=0.8.0;
          
          // ============ Internal Imports ============
          
          
          
          
          
          
          
          
          // ============ External Imports ============
          
          
          contract Mailbox is
              IMailbox,
              OwnableUpgradeable,
              PausableReentrancyGuardUpgradeable,
              Versioned
          {
              // ============ Libraries ============
          
              using MerkleLib for MerkleLib.Tree;
              using Message for bytes;
              using TypeCasts for bytes32;
              using TypeCasts for address;
          
              // ============ Constants ============
          
              // Maximum bytes per message = 2 KiB (somewhat arbitrarily set to begin)
              uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10;
              // Domain of chain on which the contract is deployed
              uint32 public immutable localDomain;
          
              // ============ Public Storage ============
          
              // The default ISM, used if the recipient fails to specify one.
              IInterchainSecurityModule public defaultIsm;
              // An incremental merkle tree used to store outbound message IDs.
              MerkleLib.Tree public tree;
              // Mapping of message ID to whether or not that message has been delivered.
              mapping(bytes32 => bool) public delivered;
          
              // ============ Upgrade Gap ============
          
              // gap for upgrade safety
              uint256[47] private __GAP;
          
              // ============ Events ============
          
              /**
               * @notice Emitted when the default ISM is updated
               * @param module The new default ISM
               */
              event DefaultIsmSet(address indexed module);
          
              /**
               * @notice Emitted when a new message is dispatched via Hyperlane
               * @param sender The address that dispatched the message
               * @param destination The destination domain of the message
               * @param recipient The message recipient address on `destination`
               * @param message Raw bytes of message
               */
              event Dispatch(
                  address indexed sender,
                  uint32 indexed destination,
                  bytes32 indexed recipient,
                  bytes message
              );
          
              /**
               * @notice Emitted when a new message is dispatched via Hyperlane
               * @param messageId The unique message identifier
               */
              event DispatchId(bytes32 indexed messageId);
          
              /**
               * @notice Emitted when a Hyperlane message is processed
               * @param messageId The unique message identifier
               */
              event ProcessId(bytes32 indexed messageId);
          
              /**
               * @notice Emitted when a Hyperlane message is delivered
               * @param origin The origin domain of the message
               * @param sender The message sender address on `origin`
               * @param recipient The address that handled the message
               */
              event Process(
                  uint32 indexed origin,
                  bytes32 indexed sender,
                  address indexed recipient
              );
          
              /**
               * @notice Emitted when Mailbox is paused
               */
              event Paused();
          
              /**
               * @notice Emitted when Mailbox is unpaused
               */
              event Unpaused();
          
              // ============ Constructor ============
          
              // solhint-disable-next-line no-empty-blocks
              constructor(uint32 _localDomain) {
                  localDomain = _localDomain;
              }
          
              // ============ Initializers ============
          
              function initialize(address _owner, address _defaultIsm)
                  external
                  initializer
              {
                  __PausableReentrancyGuard_init();
                  __Ownable_init();
                  transferOwnership(_owner);
                  _setDefaultIsm(_defaultIsm);
              }
          
              // ============ External Functions ============
          
              /**
               * @notice Sets the default ISM for the Mailbox.
               * @param _module The new default ISM. Must be a contract.
               */
              function setDefaultIsm(address _module) external onlyOwner {
                  _setDefaultIsm(_module);
              }
          
              /**
               * @notice Dispatches a message to the destination domain & recipient.
               * @param _destinationDomain Domain of destination chain
               * @param _recipientAddress Address of recipient on destination chain as bytes32
               * @param _messageBody Raw bytes content of message body
               * @return The message ID inserted into the Mailbox's merkle tree
               */
              function dispatch(
                  uint32 _destinationDomain,
                  bytes32 _recipientAddress,
                  bytes calldata _messageBody
              ) external override notPaused returns (bytes32) {
                  require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long");
                  // Format the message into packed bytes.
                  bytes memory _message = Message.formatMessage(
                      VERSION,
                      count(),
                      localDomain,
                      msg.sender.addressToBytes32(),
                      _destinationDomain,
                      _recipientAddress,
                      _messageBody
                  );
          
                  // Insert the message ID into the merkle tree.
                  bytes32 _id = _message.id();
                  tree.insert(_id);
                  emit Dispatch(
                      msg.sender,
                      _destinationDomain,
                      _recipientAddress,
                      _message
                  );
                  emit DispatchId(_id);
                  return _id;
              }
          
              /**
               * @notice Attempts to deliver `_message` to its recipient. Verifies
               * `_message` via the recipient's ISM using the provided `_metadata`.
               * @param _metadata Metadata used by the ISM to verify `_message`.
               * @param _message Formatted Hyperlane message (refer to Message.sol).
               */
              function process(bytes calldata _metadata, bytes calldata _message)
                  external
                  override
                  nonReentrantAndNotPaused
              {
                  // Check that the message was intended for this mailbox.
                  require(_message.version() == VERSION, "!version");
                  require(_message.destination() == localDomain, "!destination");
          
                  // Check that the message hasn't already been delivered.
                  bytes32 _id = _message.id();
                  require(delivered[_id] == false, "delivered");
                  delivered[_id] = true;
          
                  // Verify the message via the ISM.
                  IInterchainSecurityModule _ism = IInterchainSecurityModule(
                      recipientIsm(_message.recipientAddress())
                  );
                  require(_ism.verify(_metadata, _message), "!module");
          
                  // Deliver the message to the recipient.
                  uint32 origin = _message.origin();
                  bytes32 sender = _message.sender();
                  address recipient = _message.recipientAddress();
                  IMessageRecipient(recipient).handle(origin, sender, _message.body());
                  emit Process(origin, sender, recipient);
                  emit ProcessId(_id);
              }
          
              // ============ Public Functions ============
          
              /**
               * @notice Calculates and returns tree's current root
               */
              function root() public view returns (bytes32) {
                  return tree.root();
              }
          
              /**
               * @notice Returns the number of inserted leaves in the tree
               */
              function count() public view returns (uint32) {
                  // count cannot exceed 2**TREE_DEPTH, see MerkleLib.sol
                  return uint32(tree.count);
              }
          
              /**
               * @notice Returns a checkpoint representing the current merkle tree.
               * @return root The root of the Mailbox's merkle tree.
               * @return index The index of the last element in the tree.
               */
              function latestCheckpoint() public view returns (bytes32, uint32) {
                  return (root(), count() - 1);
              }
          
              /**
               * @notice Pauses mailbox and prevents further dispatch/process calls
               * @dev Only `owner` can pause the mailbox.
               */
              function pause() external onlyOwner {
                  _pause();
                  emit Paused();
              }
          
              /**
               * @notice Unpauses mailbox and allows for message processing.
               * @dev Only `owner` can unpause the mailbox.
               */
              function unpause() external onlyOwner {
                  _unpause();
                  emit Unpaused();
              }
          
              /**
               * @notice Returns whether mailbox is paused.
               */
              function isPaused() external view returns (bool) {
                  return _isPaused();
              }
          
              /**
               * @notice Returns the ISM to use for the recipient, defaulting to the
               * default ISM if none is specified.
               * @param _recipient The message recipient whose ISM should be returned.
               * @return The ISM to use for `_recipient`.
               */
              function recipientIsm(address _recipient)
                  public
                  view
                  returns (IInterchainSecurityModule)
              {
                  // Use a default interchainSecurityModule if one is not specified by the
                  // recipient.
                  // This is useful for backwards compatibility and for convenience as
                  // recipients are not mandated to specify an ISM.
                  try
                      ISpecifiesInterchainSecurityModule(_recipient)
                          .interchainSecurityModule()
                  returns (IInterchainSecurityModule _val) {
                      // If the recipient specifies a zero address, use the default ISM.
                      if (address(_val) != address(0)) {
                          return _val;
                      }
                  } catch {}
                  return defaultIsm;
              }
          
              // ============ Internal Functions ============
          
              /**
               * @notice Sets the default ISM for the Mailbox.
               * @param _module The new default ISM. Must be a contract.
               */
              function _setDefaultIsm(address _module) internal {
                  require(Address.isContract(_module), "!contract");
                  defaultIsm = IInterchainSecurityModule(_module);
                  emit DefaultIsmSet(_module);
              }
          }
          
          
          // File contracts/Call.sol
          
          
          pragma solidity ^0.8.13;
          
          struct Call {
              address to;
              bytes data;
          }
          
          
          // File contracts/OwnableMulticall.sol
          
          
          pragma solidity ^0.8.13;
          
          // ============ External Imports ============
          
          
          /*
           * @title OwnableMulticall
           * @dev Allows only only address to execute calls to other contracts
           */
          contract OwnableMulticall is OwnableUpgradeable {
              constructor() {
                  _transferOwnership(msg.sender);
              }
          
              function initialize() external initializer {
                  _transferOwnership(msg.sender);
              }
          
              function proxyCalls(Call[] calldata calls) external onlyOwner {
                  for (uint256 i = 0; i < calls.length; i += 1) {
                      (bool success, bytes memory returnData) = calls[i].to.call(
                          calls[i].data
                      );
                      if (!success) {
                          assembly {
                              revert(add(returnData, 32), returnData)
                          }
                      }
                  }
              }
          
              function _call(Call[] memory calls, bytes[] memory callbacks)
                  internal
                  returns (bytes[] memory resolveCalls)
              {
                  resolveCalls = new bytes[](callbacks.length);
                  for (uint256 i = 0; i < calls.length; i++) {
                      (bool success, bytes memory returnData) = calls[i].to.call(
                          calls[i].data
                      );
                      require(success, "Multicall: call failed");
                      resolveCalls[i] = bytes.concat(callbacks[i], returnData);
                  }
              }
          
              // TODO: deduplicate
              function proxyCallBatch(address to, bytes[] memory calls) internal {
                  for (uint256 i = 0; i < calls.length; i += 1) {
                      (bool success, bytes memory returnData) = to.call(calls[i]);
                      if (!success) {
                          assembly {
                              revert(add(returnData, 32), returnData)
                          }
                      }
                  }
              }
          }
          
          
          // File contracts/Router.sol
          
          
          pragma solidity >=0.6.11;
          
          // ============ Internal Imports ============
          
          
          
          
          
          abstract contract Router is HyperlaneConnectionClient, IMessageRecipient {
              using EnumerableMapExtended for EnumerableMapExtended.UintToBytes32Map;
          
              string constant NO_ROUTER_ENROLLED_REVERT_MESSAGE =
                  "No router enrolled for domain. Did you specify the right domain ID?";
          
              // ============ Mutable Storage ============
              EnumerableMapExtended.UintToBytes32Map internal _routers;
              uint256[49] private __GAP; // gap for upgrade safety
          
              // ============ Events ============
          
              /**
               * @notice Emitted when a router is set.
               * @param domain The domain of the new router
               * @param router The address of the new router
               */
              event RemoteRouterEnrolled(uint32 indexed domain, bytes32 indexed router);
          
              // ============ Modifiers ============
              /**
               * @notice Only accept messages from a remote Router contract
               * @param _origin The domain the message is coming from
               * @param _router The address the message is coming from
               */
              modifier onlyRemoteRouter(uint32 _origin, bytes32 _router) {
                  require(
                      _isRemoteRouter(_origin, _router),
                      NO_ROUTER_ENROLLED_REVERT_MESSAGE
                  );
                  _;
              }
          
              // ======== Initializer =========
              function __Router_initialize(address _mailbox) internal onlyInitializing {
                  __HyperlaneConnectionClient_initialize(_mailbox);
              }
          
              function __Router_initialize(
                  address _mailbox,
                  address _interchainGasPaymaster
              ) internal onlyInitializing {
                  __HyperlaneConnectionClient_initialize(
                      _mailbox,
                      _interchainGasPaymaster
                  );
              }
          
              function __Router_initialize(
                  address _mailbox,
                  address _interchainGasPaymaster,
                  address _interchainSecurityModule
              ) internal onlyInitializing {
                  __HyperlaneConnectionClient_initialize(
                      _mailbox,
                      _interchainGasPaymaster,
                      _interchainSecurityModule
                  );
              }
          
              // ============ External functions ============
              function domains() external view returns (uint32[] memory) {
                  bytes32[] storage rawKeys = _routers.keys();
                  uint32[] memory keys = new uint32[](rawKeys.length);
                  for (uint256 i = 0; i < rawKeys.length; i++) {
                      keys[i] = uint32(uint256(rawKeys[i]));
                  }
                  return keys;
              }
          
              function routers(uint32 _domain) public view returns (bytes32) {
                  if (_routers.contains(_domain)) {
                      return _routers.get(_domain);
                  } else {
                      return bytes32(0); // for backwards compatibility with storage mapping
                  }
              }
          
              /**
               * @notice Register the address of a Router contract for the same Application on a remote chain
               * @param _domain The domain of the remote Application Router
               * @param _router The address of the remote Application Router
               */
              function enrollRemoteRouter(uint32 _domain, bytes32 _router)
                  external
                  virtual
                  onlyOwner
              {
                  _enrollRemoteRouter(_domain, _router);
              }
          
              /**
               * @notice Batch version of `enrollRemoteRouter`
               * @param _domains The domaisn of the remote Application Routers
               * @param _addresses The addresses of the remote Application Routers
               */
              function enrollRemoteRouters(
                  uint32[] calldata _domains,
                  bytes32[] calldata _addresses
              ) external virtual onlyOwner {
                  require(_domains.length == _addresses.length, "!length");
                  for (uint256 i = 0; i < _domains.length; i += 1) {
                      _enrollRemoteRouter(_domains[i], _addresses[i]);
                  }
              }
          
              /**
               * @notice Handles an incoming message
               * @param _origin The origin domain
               * @param _sender The sender address
               * @param _message The message
               */
              function handle(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes calldata _message
              ) external virtual override onlyMailbox onlyRemoteRouter(_origin, _sender) {
                  // TODO: callbacks on success/failure
                  _handle(_origin, _sender, _message);
              }
          
              // ============ Virtual functions ============
              function _handle(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes calldata _message
              ) internal virtual;
          
              // ============ Internal functions ============
          
              /**
               * @notice Set the router for a given domain
               * @param _domain The domain
               * @param _address The new router
               */
              function _enrollRemoteRouter(uint32 _domain, bytes32 _address) internal {
                  _routers.set(_domain, _address);
                  emit RemoteRouterEnrolled(_domain, _address);
              }
          
              /**
               * @notice Return true if the given domain / router is the address of a remote Application Router
               * @param _domain The domain of the potential remote Application Router
               * @param _address The address of the potential remote Application Router
               */
              function _isRemoteRouter(uint32 _domain, bytes32 _address)
                  internal
                  view
                  returns (bool)
              {
                  return routers(_domain) == _address;
              }
          
              /**
               * @notice Assert that the given domain has a Application Router registered and return its address
               * @param _domain The domain of the chain for which to get the Application Router
               * @return _router The address of the remote Application Router on _domain
               */
              function _mustHaveRemoteRouter(uint32 _domain)
                  internal
                  view
                  returns (bytes32 _router)
              {
                  _router = routers(_domain);
                  require(_router != bytes32(0), NO_ROUTER_ENROLLED_REVERT_MESSAGE);
              }
          
              /**
               * @notice Dispatches a message to an enrolled router via the local router's Mailbox
               * and pays for it to be relayed to the destination.
               * @dev Reverts if there is no enrolled router for _destinationDomain.
               * @param _destinationDomain The domain of the chain to which to send the message.
               * @param _messageBody Raw bytes content of message.
               * @param _gasAmount The amount of destination gas for the message that is requested via the InterchainGasPaymaster.
               * @param _gasPayment The amount of native tokens to pay for the message to be relayed.
               * @param _gasPaymentRefundAddress The address to refund any gas overpayment to.
               */
              function _dispatchWithGas(
                  uint32 _destinationDomain,
                  bytes memory _messageBody,
                  uint256 _gasAmount,
                  uint256 _gasPayment,
                  address _gasPaymentRefundAddress
              ) internal returns (bytes32 _messageId) {
                  _messageId = _dispatch(_destinationDomain, _messageBody);
                  // Call the IGP even if the gas payment is zero. This is to support on-chain
                  // fee quoting in IGPs, which should always revert if gas payment is insufficient.
                  interchainGasPaymaster.payForGas{value: _gasPayment}(
                      _messageId,
                      _destinationDomain,
                      _gasAmount,
                      _gasPaymentRefundAddress
                  );
              }
          
              /**
               * @notice Dispatches a message to an enrolled router via the provided Mailbox.
               * @dev Does not pay interchain gas.
               * @dev Reverts if there is no enrolled router for _destinationDomain.
               * @param _destinationDomain The domain of the chain to which to send the message.
               * @param _messageBody Raw bytes content of message.
               */
              function _dispatch(uint32 _destinationDomain, bytes memory _messageBody)
                  internal
                  virtual
                  returns (bytes32)
              {
                  // Ensure that destination chain has an enrolled router.
                  bytes32 _router = _mustHaveRemoteRouter(_destinationDomain);
                  return mailbox.dispatch(_destinationDomain, _router, _messageBody);
              }
          }
          
          
          // File interfaces/IInterchainAccountRouter.sol
          
          
          pragma solidity >=0.6.11;
          
          interface IInterchainAccountRouter {
              function dispatch(uint32 _destinationDomain, Call[] calldata calls)
                  external
                  returns (bytes32);
          
              function dispatch(
                  uint32 _destinationDomain,
                  address target,
                  bytes calldata data
              ) external returns (bytes32);
          
              function getInterchainAccount(uint32 _originDomain, address _sender)
                  external
                  view
                  returns (address);
          }
          
          
          // File contracts/libs/MinimalProxy.sol
          
          
          pragma solidity >=0.6.11;
          
          // Library for building bytecode of minimal proxies (see https://eips.ethereum.org/EIPS/eip-1167)
          library MinimalProxy {
              bytes20 constant PREFIX = hex"3d602d80600a3d3981f3363d3d373d3d3d363d73";
              bytes15 constant SUFFIX = hex"5af43d82803e903d91602b57fd5bf3";
          
              function bytecode(address implementation)
                  internal
                  pure
                  returns (bytes memory)
              {
                  return abi.encodePacked(PREFIX, bytes20(implementation), SUFFIX);
              }
          }
          
          
          // File @openzeppelin/contracts/utils/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/Create2.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
           * `CREATE2` can be used to compute in advance the address where a smart
           * contract will be deployed, which allows for interesting new mechanisms known
           * as 'counterfactual interactions'.
           *
           * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
           * information.
           */
          library Create2 {
              /**
               * @dev Deploys a contract using `CREATE2`. The address where the contract
               * will be deployed can be known in advance via {computeAddress}.
               *
               * The bytecode for a contract can be obtained from Solidity with
               * `type(contractName).creationCode`.
               *
               * Requirements:
               *
               * - `bytecode` must not be empty.
               * - `salt` must have not been used for `bytecode` already.
               * - the factory must have a balance of at least `amount`.
               * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
               */
              function deploy(
                  uint256 amount,
                  bytes32 salt,
                  bytes memory bytecode
              ) internal returns (address addr) {
                  require(address(this).balance >= amount, "Create2: insufficient balance");
                  require(bytecode.length != 0, "Create2: bytecode length is zero");
                  /// @solidity memory-safe-assembly
                  assembly {
                      addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
                  }
                  require(addr != address(0), "Create2: Failed on deploy");
              }
          
              /**
               * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
               * `bytecodeHash` or `salt` will result in a new destination address.
               */
              function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
                  return computeAddress(salt, bytecodeHash, address(this));
              }
          
              /**
               * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
               * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
               */
              function computeAddress(
                  bytes32 salt,
                  bytes32 bytecodeHash,
                  address deployer
              ) internal pure returns (address addr) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      let ptr := mload(0x40) // Get free memory pointer
          
                      // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
                      // |-------------------|---------------------------------------------------------------------------|
                      // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
                      // | salt              |                                      BBBBBBBBBBBBB...BB                   |
                      // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
                      // | 0xFF              |            FF                                                             |
                      // |-------------------|---------------------------------------------------------------------------|
                      // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
                      // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
          
                      mstore(add(ptr, 0x40), bytecodeHash)
                      mstore(add(ptr, 0x20), salt)
                      mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
                      let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
                      mstore8(start, 0xff)
                      addr := keccak256(start, 85)
                  }
              }
          }
          
          
          // File contracts/middleware/InterchainAccountRouter.sol
          
          
          pragma solidity ^0.8.13;
          
          // ============ Internal Imports ============
          
          
          
          
          // ============ External Imports ============
          
          
          
          /*
           * @title The Hello World App
           * @dev You can use this simple app as a starting point for your own application.
           */
          contract InterchainAccountRouter is Router, IInterchainAccountRouter {
              address immutable implementation;
              bytes32 immutable bytecodeHash;
          
              event InterchainAccountCreated(
                  uint32 indexed origin,
                  address sender,
                  address account
              );
          
              constructor() {
                  implementation = address(new OwnableMulticall());
                  // cannot be stored immutably because it is dynamically sized
                  bytes memory bytecode = MinimalProxy.bytecode(implementation);
                  bytecodeHash = keccak256(bytecode);
              }
          
              function initialize(
                  address _mailbox,
                  address _interchainGasPaymaster,
                  address _interchainSecurityModule
              ) public initializer {
                  // Transfer ownership of the contract to `msg.sender`
                  __Router_initialize(
                      _mailbox,
                      _interchainGasPaymaster,
                      _interchainSecurityModule
                  );
              }
          
              function initialize(address _mailbox, address _interchainGasPaymaster)
                  public
                  initializer
              {
                  // Transfer ownership of the contract to `msg.sender`
                  __Router_initialize(_mailbox, _interchainGasPaymaster);
              }
          
              function dispatch(uint32 _destinationDomain, Call[] calldata calls)
                  external
                  returns (bytes32)
              {
                  return _dispatch(_destinationDomain, abi.encode(msg.sender, calls));
              }
          
              function dispatch(
                  uint32 _destinationDomain,
                  address target,
                  bytes calldata data
              ) external returns (bytes32) {
                  Call[] memory calls = new Call[](1);
                  calls[0] = Call({to: target, data: data});
                  return _dispatch(_destinationDomain, abi.encode(msg.sender, calls));
              }
          
              function getInterchainAccount(uint32 _origin, address _sender)
                  public
                  view
                  returns (address)
              {
                  return _getInterchainAccount(_salt(_origin, _sender));
              }
          
              function getDeployedInterchainAccount(uint32 _origin, address _sender)
                  public
                  returns (OwnableMulticall)
              {
                  bytes32 salt = _salt(_origin, _sender);
                  address interchainAccount = _getInterchainAccount(salt);
                  if (!Address.isContract(interchainAccount)) {
                      bytes memory bytecode = MinimalProxy.bytecode(implementation);
                      interchainAccount = Create2.deploy(0, salt, bytecode);
                      OwnableMulticall(interchainAccount).initialize();
                      emit InterchainAccountCreated(_origin, _sender, interchainAccount);
                  }
                  return OwnableMulticall(interchainAccount);
              }
          
              function _salt(uint32 _origin, address _sender)
                  internal
                  pure
                  returns (bytes32)
              {
                  return bytes32(abi.encodePacked(_origin, _sender));
              }
          
              function _getInterchainAccount(bytes32 salt)
                  internal
                  view
                  returns (address)
              {
                  return Create2.computeAddress(salt, bytecodeHash);
              }
          
              function _handle(
                  uint32 _origin,
                  bytes32, // router sender
                  bytes calldata _message
              ) internal override {
                  (address sender, Call[] memory calls) = abi.decode(
                      _message,
                      (address, Call[])
                  );
                  getDeployedInterchainAccount(_origin, sender).proxyCalls(calls);
              }
          }
          
          
          // File interfaces/IInterchainQueryRouter.sol
          
          
          pragma solidity >=0.6.11;
          
          interface IInterchainQueryRouter {
              function query(
                  uint32 _destinationDomain,
                  address target,
                  bytes calldata queryData,
                  bytes calldata callback
              ) external returns (bytes32);
          
              function query(
                  uint32 _destinationDomain,
                  Call calldata call,
                  bytes calldata callback
              ) external returns (bytes32);
          
              function query(
                  uint32 _destinationDomain,
                  Call[] calldata calls,
                  bytes[] calldata callbacks
              ) external returns (bytes32);
          }
          
          
          // File contracts/middleware/InterchainQueryRouter.sol
          
          
          pragma solidity ^0.8.13;
          
          // ============ Internal Imports ============
          
          
          
          // ============ External Imports ============
          
          
          
          contract InterchainQueryRouter is
              Router,
              OwnableMulticall,
              IInterchainQueryRouter
          {
              enum Action {
                  DISPATCH,
                  RESOLVE
              }
          
              event QueryDispatched(
                  uint32 indexed destinationDomain,
                  address indexed sender
              );
              event QueryReturned(uint32 indexed originDomain, address indexed sender);
              event QueryResolved(
                  uint32 indexed destinationDomain,
                  address indexed sender
              );
          
              function initialize(
                  address _mailbox,
                  address _interchainGasPaymaster,
                  address _interchainSecurityModule
              ) public initializer {
                  // Transfer ownership of the contract to `msg.sender`
                  __Router_initialize(
                      _mailbox,
                      _interchainGasPaymaster,
                      _interchainSecurityModule
                  );
              }
          
              function initialize(address _mailbox, address _interchainGasPaymaster)
                  public
                  initializer
              {
                  // Transfer ownership of the contract to `msg.sender`
                  __Router_initialize(_mailbox, _interchainGasPaymaster);
              }
          
              /**
               * @param _destinationDomain Domain of destination chain
               * @param target The address of the contract to query on destination chain.
               * @param queryData The calldata of the view call to make on the destination chain.
               * @param callback Callback function selector on `msg.sender` and optionally abi-encoded prefix arguments.
               */
              function query(
                  uint32 _destinationDomain,
                  address target,
                  bytes calldata queryData,
                  bytes calldata callback
              ) external returns (bytes32 messageId) {
                  // TODO: fix this ugly arrayification
                  Call[] memory calls = new Call[](1);
                  calls[0] = Call({to: target, data: queryData});
                  bytes[] memory callbacks = new bytes[](1);
                  callbacks[0] = callback;
                  messageId = query(_destinationDomain, calls, callbacks);
              }
          
              /**
               * @param _destinationDomain Domain of destination chain
               * @param call Call (to and data packed struct) to be made on destination chain.
               * @param callback Callback function selector on `msg.sender` and optionally abi-encoded prefix arguments.
               */
              function query(
                  uint32 _destinationDomain,
                  Call calldata call,
                  bytes calldata callback
              ) external returns (bytes32 messageId) {
                  // TODO: fix this ugly arrayification
                  Call[] memory calls = new Call[](1);
                  calls[0] = call;
                  bytes[] memory callbacks = new bytes[](1);
                  callbacks[0] = callback;
                  messageId = query(_destinationDomain, calls, callbacks);
              }
          
              /**
               * @param _destinationDomain Domain of destination chain
               * @param calls Array of calls (to and data packed struct) to be made on destination chain in sequence.
               * @param callbacks Array of callback function selectors on `msg.sender` and optionally abi-encoded prefix arguments.
               */
              function query(
                  uint32 _destinationDomain,
                  Call[] memory calls,
                  bytes[] memory callbacks
              ) public returns (bytes32 messageId) {
                  require(
                      calls.length == callbacks.length,
                      "InterchainQueryRouter: calls and callbacks must be same length"
                  );
                  messageId = _dispatch(
                      _destinationDomain,
                      abi.encode(Action.DISPATCH, msg.sender, calls, callbacks)
                  );
                  emit QueryDispatched(_destinationDomain, msg.sender);
              }
          
              // TODO: add REJECT behavior ala NodeJS Promise API
              function _handle(
                  uint32 _origin,
                  bytes32, // router sender
                  bytes calldata _message
              ) internal override {
                  // TODO: fix double ABI decoding with calldata slices
                  Action action = abi.decode(_message, (Action));
                  if (action == Action.DISPATCH) {
                      (
                          ,
                          address sender,
                          Call[] memory calls,
                          bytes[] memory callbacks
                      ) = abi.decode(_message, (Action, address, Call[], bytes[]));
                      bytes[] memory resolveCallbacks = _call(calls, callbacks);
                      _dispatch(
                          _origin,
                          abi.encode(Action.RESOLVE, sender, resolveCallbacks)
                      );
                      emit QueryReturned(_origin, sender);
                  } else if (action == Action.RESOLVE) {
                      (, address sender, bytes[] memory resolveCallbacks) = abi.decode(
                          _message,
                          (Action, address, bytes[])
                      );
                      proxyCallBatch(sender, resolveCallbacks);
                      emit QueryResolved(_origin, sender);
                  }
              }
          }
          
          
          // File contracts/middleware/liquidity-layer/interfaces/circle/ICircleBridge.sol
          
          
          pragma solidity ^0.8.13;
          
          interface ICircleBridge {
              event MessageSent(bytes message);
          
              /**
               * @notice Deposits and burns tokens from sender to be minted on destination domain.
               * Emits a `DepositForBurn` event.
               * @dev reverts if:
               * - given burnToken is not supported
               * - given destinationDomain has no CircleBridge registered
               * - transferFrom() reverts. For example, if sender's burnToken balance or approved allowance
               * to this contract is less than `amount`.
               * - burn() reverts. For example, if `amount` is 0.
               * - MessageTransmitter returns false or reverts.
               * @param _amount amount of tokens to burn
               * @param _destinationDomain destination domain (ETH = 0, AVAX = 1)
               * @param _mintRecipient address of mint recipient on destination domain
               * @param _burnToken address of contract to burn deposited tokens, on local domain
               * @return _nonce unique nonce reserved by message
               */
              function depositForBurn(
                  uint256 _amount,
                  uint32 _destinationDomain,
                  bytes32 _mintRecipient,
                  address _burnToken
              ) external returns (uint64 _nonce);
          
              /**
               * @notice Deposits and burns tokens from sender to be minted on destination domain. The mint
               * on the destination domain must be called by `_destinationCaller`.
               * WARNING: if the `_destinationCaller` does not represent a valid address as bytes32, then it will not be possible
               * to broadcast the message on the destination domain. This is an advanced feature, and the standard
               * depositForBurn() should be preferred for use cases where a specific destination caller is not required.
               * Emits a `DepositForBurn` event.
               * @dev reverts if:
               * - given destinationCaller is zero address
               * - given burnToken is not supported
               * - given destinationDomain has no CircleBridge registered
               * - transferFrom() reverts. For example, if sender's burnToken balance or approved allowance
               * to this contract is less than `amount`.
               * - burn() reverts. For example, if `amount` is 0.
               * - MessageTransmitter returns false or reverts.
               * @param _amount amount of tokens to burn
               * @param _destinationDomain destination domain
               * @param _mintRecipient address of mint recipient on destination domain
               * @param _burnToken address of contract to burn deposited tokens, on local domain
               * @param _destinationCaller caller on the destination domain, as bytes32
               * @return _nonce unique nonce reserved by message
               */
              function depositForBurnWithCaller(
                  uint256 _amount,
                  uint32 _destinationDomain,
                  bytes32 _mintRecipient,
                  address _burnToken,
                  bytes32 _destinationCaller
              ) external returns (uint64 _nonce);
          }
          
          
          // File contracts/middleware/liquidity-layer/interfaces/circle/ICircleMessageTransmitter.sol
          
          
          pragma solidity ^0.8.13;
          
          interface ICircleMessageTransmitter {
              /**
               * @notice Receive a message. Messages with a given nonce
               * can only be broadcast once for a (sourceDomain, destinationDomain)
               * pair. The message body of a valid message is passed to the
               * specified recipient for further processing.
               *
               * @dev Attestation format:
               * A valid attestation is the concatenated 65-byte signature(s) of exactly
               * `thresholdSignature` signatures, in increasing order of attester address.
               * ***If the attester addresses recovered from signatures are not in
               * increasing order, signature verification will fail.***
               * If incorrect number of signatures or duplicate signatures are supplied,
               * signature verification will fail.
               *
               * Message format:
               * Field Bytes Type Index
               * version 4 uint32 0
               * sourceDomain 4 uint32 4
               * destinationDomain 4 uint32 8
               * nonce 8 uint64 12
               * sender 32 bytes32 20
               * recipient 32 bytes32 52
               * messageBody dynamic bytes 84
               * @param _message Message bytes
               * @param _attestation Concatenated 65-byte signature(s) of `_message`, in increasing order
               * of the attester address recovered from signatures.
               * @return success bool, true if successful
               */
              function receiveMessage(bytes memory _message, bytes calldata _attestation)
                  external
                  returns (bool success);
          
              function usedNonces(bytes32 _nonceId) external view returns (bool);
          }
          
          
          // File contracts/middleware/liquidity-layer/interfaces/ILiquidityLayerAdapter.sol
          
          
          pragma solidity ^0.8.13;
          
          interface ILiquidityLayerAdapter {
              function sendTokens(
                  uint32 _destinationDomain,
                  bytes32 _recipientAddress,
                  address _token,
                  uint256 _amount
              ) external returns (bytes memory _adapterData);
          
              function receiveTokens(
                  uint32 _originDomain, // Hyperlane domain
                  address _recipientAddress,
                  uint256 _amount,
                  bytes calldata _adapterData // The adapter data from the message
              ) external returns (address, uint256);
          }
          
          
          // File @openzeppelin/contracts/token/ERC20/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20 {
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
          
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
          
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
          
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
          
              /**
               * @dev Moves `amount` tokens from the caller's account to `to`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address to, uint256 amount) external returns (bool);
          
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
          
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
          
              /**
               * @dev Moves `amount` tokens from `from` to `to` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) external returns (bool);
          }
          
          
          // File contracts/middleware/liquidity-layer/adapters/CircleBridgeAdapter.sol
          
          
          pragma solidity ^0.8.13;
          
          
          
          contract CircleBridgeAdapter is ILiquidityLayerAdapter, Router {
              /// @notice The CircleBridge contract.
              ICircleBridge public circleBridge;
          
              /// @notice The Circle MessageTransmitter contract.
              ICircleMessageTransmitter public circleMessageTransmitter;
          
              /// @notice The LiquidityLayerRouter contract.
              address public liquidityLayerRouter;
          
              /// @notice Hyperlane domain => Circle domain.
              /// ATM, known Circle domains are Ethereum = 0 and Avalanche = 1.
              /// Note this could result in ambiguity between the Circle domain being
              /// Ethereum or unknown. TODO fix?
              mapping(uint32 => uint32) public hyperlaneDomainToCircleDomain;
          
              /// @notice Token symbol => address of token on local chain.
              mapping(string => IERC20) public tokenSymbolToAddress;
          
              /// @notice Local chain token address => token symbol.
              mapping(address => string) public tokenAddressToSymbol;
          
              /**
               * @notice Emits the nonce of the Circle message when a token is bridged.
               * @param nonce The nonce of the Circle message.
               */
              event BridgedToken(uint64 nonce);
          
              /**
               * @notice Emitted when the Hyperlane domain to Circle domain mapping is updated.
               * @param hyperlaneDomain The Hyperlane domain.
               * @param circleDomain The Circle domain.
               */
              event DomainAdded(uint32 indexed hyperlaneDomain, uint32 circleDomain);
          
              /**
               * @notice Emitted when a local token and its token symbol have been added.
               */
              event TokenAdded(address indexed token, string indexed symbol);
          
              /**
               * @notice Emitted when a local token and its token symbol have been removed.
               */
              event TokenRemoved(address indexed token, string indexed symbol);
          
              modifier onlyLiquidityLayerRouter() {
                  require(msg.sender == liquidityLayerRouter, "!liquidityLayerRouter");
                  _;
              }
          
              /**
               * @param _owner The new owner.
               * @param _circleBridge The CircleBridge contract.
               * @param _circleMessageTransmitter The Circle MessageTransmitter contract.
               * @param _liquidityLayerRouter The LiquidityLayerRouter contract.
               */
              function initialize(
                  address _owner,
                  address _circleBridge,
                  address _circleMessageTransmitter,
                  address _liquidityLayerRouter
              ) public initializer {
                  // Transfer ownership of the contract to deployer
                  _transferOwnership(_owner);
          
                  circleBridge = ICircleBridge(_circleBridge);
                  circleMessageTransmitter = ICircleMessageTransmitter(
                      _circleMessageTransmitter
                  );
                  liquidityLayerRouter = _liquidityLayerRouter;
              }
          
              function sendTokens(
                  uint32 _destinationDomain,
                  bytes32, // _recipientAddress, unused
                  address _token,
                  uint256 _amount
              ) external onlyLiquidityLayerRouter returns (bytes memory) {
                  string memory _tokenSymbol = tokenAddressToSymbol[_token];
                  require(
                      bytes(_tokenSymbol).length > 0,
                      "CircleBridgeAdapter: Unknown token"
                  );
          
                  uint32 _circleDomain = hyperlaneDomainToCircleDomain[
                      _destinationDomain
                  ];
                  bytes32 _remoteRouter = routers(_destinationDomain);
                  require(
                      _remoteRouter != bytes32(0),
                      "CircleBridgeAdapter: No router for domain"
                  );
          
                  // Approve the token to Circle. We assume that the LiquidityLayerRouter
                  // has already transferred the token to this contract.
                  require(
                      IERC20(_token).approve(address(circleBridge), _amount),
                      "!approval"
                  );
          
                  uint64 _nonce = circleBridge.depositForBurn(
                      _amount,
                      _circleDomain,
                      _remoteRouter, // Mint to the remote router
                      _token
                  );
          
                  emit BridgedToken(_nonce);
                  return abi.encode(_nonce, _tokenSymbol);
              }
          
              // Returns the token and amount sent
              function receiveTokens(
                  uint32 _originDomain, // Hyperlane domain
                  address _recipient,
                  uint256 _amount,
                  bytes calldata _adapterData // The adapter data from the message
              ) external onlyLiquidityLayerRouter returns (address, uint256) {
                  // The origin Circle domain
                  uint32 _originCircleDomain = hyperlaneDomainToCircleDomain[
                      _originDomain
                  ];
                  // Get the token symbol and nonce of the transfer from the _adapterData
                  (uint64 _nonce, string memory _tokenSymbol) = abi.decode(
                      _adapterData,
                      (uint64, string)
                  );
          
                  // Require the circle message to have been processed
                  bytes32 _nonceId = _circleNonceId(_originCircleDomain, _nonce);
                  require(
                      circleMessageTransmitter.usedNonces(_nonceId),
                      "Circle message not processed yet"
                  );
          
                  IERC20 _token = tokenSymbolToAddress[_tokenSymbol];
                  require(
                      address(_token) != address(0),
                      "CircleBridgeAdapter: Unknown token"
                  );
          
                  // Transfer the token out to the recipient
                  // TODO: use safeTransfer
                  // Circle doesn't charge any fee, so we can safely transfer out the
                  // exact amount that was bridged over.
                  require(_token.transfer(_recipient, _amount), "!transfer out");
          
                  return (address(_token), _amount);
              }
          
              // This contract is only a Router to be aware of remote router addresses,
              // and doesn't actually send/handle Hyperlane messages directly
              function _handle(
                  uint32, // origin
                  bytes32, // sender
                  bytes calldata // message
              ) internal pure override {
                  revert("No messages expected");
              }
          
              function addDomain(uint32 _hyperlaneDomain, uint32 _circleDomain)
                  external
                  onlyOwner
              {
                  hyperlaneDomainToCircleDomain[_hyperlaneDomain] = _circleDomain;
          
                  emit DomainAdded(_hyperlaneDomain, _circleDomain);
              }
          
              function addToken(address _token, string calldata _tokenSymbol)
                  external
                  onlyOwner
              {
                  require(
                      _token != address(0) && bytes(_tokenSymbol).length > 0,
                      "Cannot add default values"
                  );
          
                  // Require the token and token symbol to be unset.
                  address _existingToken = address(tokenSymbolToAddress[_tokenSymbol]);
                  require(_existingToken == address(0), "token symbol already has token");
          
                  string memory _existingSymbol = tokenAddressToSymbol[_token];
                  require(
                      bytes(_existingSymbol).length == 0,
                      "token already has token symbol"
                  );
          
                  tokenAddressToSymbol[_token] = _tokenSymbol;
                  tokenSymbolToAddress[_tokenSymbol] = IERC20(_token);
          
                  emit TokenAdded(_token, _tokenSymbol);
              }
          
              function removeToken(address _token, string calldata _tokenSymbol)
                  external
                  onlyOwner
              {
                  // Require the provided token and token symbols match what's in storage.
                  address _existingToken = address(tokenSymbolToAddress[_tokenSymbol]);
                  require(_existingToken == _token, "Token mismatch");
          
                  string memory _existingSymbol = tokenAddressToSymbol[_token];
                  require(
                      keccak256(bytes(_existingSymbol)) == keccak256(bytes(_tokenSymbol)),
                      "Token symbol mismatch"
                  );
          
                  // Delete them from storage.
                  delete tokenSymbolToAddress[_tokenSymbol];
                  delete tokenAddressToSymbol[_token];
          
                  emit TokenRemoved(_token, _tokenSymbol);
              }
          
              /**
               * @notice Gets the Circle nonce ID by hashing _originCircleDomain and _nonce.
               * @param _originCircleDomain Domain of chain where the transfer originated
               * @param _nonce The unique identifier for the message from source to
                        destination
               * @return hash of source and nonce
               */
              function _circleNonceId(uint32 _originCircleDomain, uint64 _nonce)
                  internal
                  pure
                  returns (bytes32)
              {
                  // The hash is of a uint256 nonce, not a uint64 one.
                  return
                      keccak256(abi.encodePacked(_originCircleDomain, uint256(_nonce)));
              }
          }
          
          
          // File interfaces/ILiquidityLayerRouter.sol
          
          
          pragma solidity >=0.6.11;
          
          interface ILiquidityLayerRouter {
              function dispatchWithTokens(
                  uint32 _destinationDomain,
                  bytes32 _recipientAddress,
                  bytes calldata _messageBody,
                  address _token,
                  uint256 _amount,
                  string calldata _bridge
              ) external payable returns (bytes32);
          }
          
          
          // File interfaces/ILiquidityLayerMessageRecipient.sol
          
          
          pragma solidity ^0.8.13;
          
          interface ILiquidityLayerMessageRecipient {
              function handleWithTokens(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes calldata _message,
                  address _token,
                  uint256 _amount
              ) external;
          }
          
          
          // File contracts/middleware/liquidity-layer/LiquidityLayerRouter.sol
          
          
          pragma solidity ^0.8.13;
          
          
          
          
          
          contract LiquidityLayerRouter is Router, ILiquidityLayerRouter {
              // Token bridge => adapter address
              mapping(string => address) public liquidityLayerAdapters;
          
              event LiquidityLayerAdapterSet(string indexed bridge, address adapter);
          
              function initialize(
                  address _mailbox,
                  address _interchainGasPaymaster,
                  address _interchainSecurityModule
              ) public initializer {
                  // Transfer ownership of the contract to `msg.sender`
                  __Router_initialize(
                      _mailbox,
                      _interchainGasPaymaster,
                      _interchainSecurityModule
                  );
              }
          
              function initialize(address _mailbox, address _interchainGasPaymaster)
                  public
                  initializer
              {
                  // Transfer ownership of the contract to `msg.sender`
                  __Router_initialize(_mailbox, _interchainGasPaymaster);
              }
          
              function dispatchWithTokens(
                  uint32 _destinationDomain,
                  bytes32 _recipientAddress,
                  bytes calldata _messageBody,
                  address _token,
                  uint256 _amount,
                  string calldata _bridge
              ) external payable returns (bytes32) {
                  ILiquidityLayerAdapter _adapter = _getAdapter(_bridge);
          
                  // Transfer the tokens to the adapter
                  // TODO: use safeTransferFrom
                  // TODO: Are there scenarios where a transferFrom fails and it doesn't revert?
                  require(
                      IERC20(_token).transferFrom(msg.sender, address(_adapter), _amount),
                      "!transfer in"
                  );
          
                  // Reverts if the bridge was unsuccessful.
                  // Gets adapter-specific data that is encoded into the message
                  // ultimately sent via Hyperlane.
                  bytes memory _adapterData = _adapter.sendTokens(
                      _destinationDomain,
                      _recipientAddress,
                      _token,
                      _amount
                  );
          
                  // The user's message "wrapped" with metadata required by this middleware
                  bytes memory _messageWithMetadata = abi.encode(
                      TypeCasts.addressToBytes32(msg.sender),
                      _recipientAddress, // The "user" recipient
                      _amount, // The amount of the tokens sent over the bridge
                      _bridge, // The destination token bridge ID
                      _adapterData, // The adapter-specific data
                      _messageBody // The "user" message
                  );
          
                  // Dispatch the _messageWithMetadata to the destination's LiquidityLayerRouter.
                  return
                      _dispatchWithGas(
                          _destinationDomain,
                          _messageWithMetadata,
                          0, // TODO eventually accommodate gas amounts
                          msg.value,
                          msg.sender
                      );
              }
          
              // Handles a message from an enrolled remote LiquidityLayerRouter
              function _handle(
                  uint32 _origin,
                  bytes32, // _sender, unused
                  bytes calldata _message
              ) internal override {
                  // Decode the message with metadata, "unwrapping" the user's message body
                  (
                      bytes32 _originalSender,
                      bytes32 _userRecipientAddress,
                      uint256 _amount,
                      string memory _bridge,
                      bytes memory _adapterData,
                      bytes memory _userMessageBody
                  ) = abi.decode(
                          _message,
                          (bytes32, bytes32, uint256, string, bytes, bytes)
                      );
          
                  ILiquidityLayerMessageRecipient _userRecipient = ILiquidityLayerMessageRecipient(
                          TypeCasts.bytes32ToAddress(_userRecipientAddress)
                      );
          
                  // Reverts if the adapter hasn't received the bridged tokens yet
                  (address _token, uint256 _receivedAmount) = _getAdapter(_bridge)
                      .receiveTokens(
                          _origin,
                          address(_userRecipient),
                          _amount,
                          _adapterData
                      );
          
                  _userRecipient.handleWithTokens(
                      _origin,
                      _originalSender,
                      _userMessageBody,
                      _token,
                      _receivedAmount
                  );
              }
          
              function setLiquidityLayerAdapter(string calldata _bridge, address _adapter)
                  external
                  onlyOwner
              {
                  liquidityLayerAdapters[_bridge] = _adapter;
                  emit LiquidityLayerAdapterSet(_bridge, _adapter);
              }
          
              function _getAdapter(string memory _bridge)
                  internal
                  view
                  returns (ILiquidityLayerAdapter _adapter)
              {
                  _adapter = ILiquidityLayerAdapter(liquidityLayerAdapters[_bridge]);
                  // Require the adapter to have been set
                  require(address(_adapter) != address(0), "No adapter found for bridge");
              }
          }
          
          
          // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20Upgradeable {
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
          
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
          
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
          
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
          
              /**
               * @dev Moves `amount` tokens from the caller's account to `to`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address to, uint256 amount) external returns (bool);
          
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
          
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
          
              /**
               * @dev Moves `amount` tokens from `from` to `to` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) external returns (bool);
          }
          
          
          // File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
          
          
          // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Interface for the optional metadata functions from the ERC20 standard.
           *
           * _Available since v4.1._
           */
          interface IERC20MetadataUpgradeable is IERC20Upgradeable {
              /**
               * @dev Returns the name of the token.
               */
              function name() external view returns (string memory);
          
              /**
               * @dev Returns the symbol of the token.
               */
              function symbol() external view returns (string memory);
          
              /**
               * @dev Returns the decimals places of the token.
               */
              function decimals() external view returns (uint8);
          }
          
          
          // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
          
          pragma solidity ^0.8.0;
          
          
          
          
          /**
           * @dev Implementation of the {IERC20} interface.
           *
           * This implementation is agnostic to the way tokens are created. This means
           * that a supply mechanism has to be added in a derived contract using {_mint}.
           * For a generic mechanism see {ERC20PresetMinterPauser}.
           *
           * TIP: For a detailed writeup see our guide
           * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
           * to implement supply mechanisms].
           *
           * We have followed general OpenZeppelin Contracts guidelines: functions revert
           * instead returning `false` on failure. This behavior is nonetheless
           * conventional and does not conflict with the expectations of ERC20
           * applications.
           *
           * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
           * This allows applications to reconstruct the allowance for all accounts just
           * by listening to said events. Other implementations of the EIP may not emit
           * these events, as it isn't required by the specification.
           *
           * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
           * functions have been added to mitigate the well-known issues around setting
           * allowances. See {IERC20-approve}.
           */
          contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
              mapping(address => uint256) private _balances;
          
              mapping(address => mapping(address => uint256)) private _allowances;
          
              uint256 private _totalSupply;
          
              string private _name;
              string private _symbol;
          
              /**
               * @dev Sets the values for {name} and {symbol}.
               *
               * The default value of {decimals} is 18. To select a different value for
               * {decimals} you should overload it.
               *
               * All two of these values are immutable: they can only be set once during
               * construction.
               */
              function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
                  __ERC20_init_unchained(name_, symbol_);
              }
          
              function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
                  _name = name_;
                  _symbol = symbol_;
              }
          
              /**
               * @dev Returns the name of the token.
               */
              function name() public view virtual override returns (string memory) {
                  return _name;
              }
          
              /**
               * @dev Returns the symbol of the token, usually a shorter version of the
               * name.
               */
              function symbol() public view virtual override returns (string memory) {
                  return _symbol;
              }
          
              /**
               * @dev Returns the number of decimals used to get its user representation.
               * For example, if `decimals` equals `2`, a balance of `505` tokens should
               * be displayed to a user as `5.05` (`505 / 10 ** 2`).
               *
               * Tokens usually opt for a value of 18, imitating the relationship between
               * Ether and Wei. This is the value {ERC20} uses, unless this function is
               * overridden;
               *
               * NOTE: This information is only used for _display_ purposes: it in
               * no way affects any of the arithmetic of the contract, including
               * {IERC20-balanceOf} and {IERC20-transfer}.
               */
              function decimals() public view virtual override returns (uint8) {
                  return 18;
              }
          
              /**
               * @dev See {IERC20-totalSupply}.
               */
              function totalSupply() public view virtual override returns (uint256) {
                  return _totalSupply;
              }
          
              /**
               * @dev See {IERC20-balanceOf}.
               */
              function balanceOf(address account) public view virtual override returns (uint256) {
                  return _balances[account];
              }
          
              /**
               * @dev See {IERC20-transfer}.
               *
               * Requirements:
               *
               * - `to` cannot be the zero address.
               * - the caller must have a balance of at least `amount`.
               */
              function transfer(address to, uint256 amount) public virtual override returns (bool) {
                  address owner = _msgSender();
                  _transfer(owner, to, amount);
                  return true;
              }
          
              /**
               * @dev See {IERC20-allowance}.
               */
              function allowance(address owner, address spender) public view virtual override returns (uint256) {
                  return _allowances[owner][spender];
              }
          
              /**
               * @dev See {IERC20-approve}.
               *
               * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
               * `transferFrom`. This is semantically equivalent to an infinite approval.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function approve(address spender, uint256 amount) public virtual override returns (bool) {
                  address owner = _msgSender();
                  _approve(owner, spender, amount);
                  return true;
              }
          
              /**
               * @dev See {IERC20-transferFrom}.
               *
               * Emits an {Approval} event indicating the updated allowance. This is not
               * required by the EIP. See the note at the beginning of {ERC20}.
               *
               * NOTE: Does not update the allowance if the current allowance
               * is the maximum `uint256`.
               *
               * Requirements:
               *
               * - `from` and `to` cannot be the zero address.
               * - `from` must have a balance of at least `amount`.
               * - the caller must have allowance for ``from``'s tokens of at least
               * `amount`.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) public virtual override returns (bool) {
                  address spender = _msgSender();
                  _spendAllowance(from, spender, amount);
                  _transfer(from, to, amount);
                  return true;
              }
          
              /**
               * @dev Atomically increases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                  address owner = _msgSender();
                  _approve(owner, spender, allowance(owner, spender) + addedValue);
                  return true;
              }
          
              /**
               * @dev Atomically decreases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               * - `spender` must have allowance for the caller of at least
               * `subtractedValue`.
               */
              function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                  address owner = _msgSender();
                  uint256 currentAllowance = allowance(owner, spender);
                  require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                  unchecked {
                      _approve(owner, spender, currentAllowance - subtractedValue);
                  }
          
                  return true;
              }
          
              /**
               * @dev Moves `amount` of tokens from `from` to `to`.
               *
               * This internal function is equivalent to {transfer}, and can be used to
               * e.g. implement automatic token fees, slashing mechanisms, etc.
               *
               * Emits a {Transfer} event.
               *
               * Requirements:
               *
               * - `from` cannot be the zero address.
               * - `to` cannot be the zero address.
               * - `from` must have a balance of at least `amount`.
               */
              function _transfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {
                  require(from != address(0), "ERC20: transfer from the zero address");
                  require(to != address(0), "ERC20: transfer to the zero address");
          
                  _beforeTokenTransfer(from, to, amount);
          
                  uint256 fromBalance = _balances[from];
                  require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                  unchecked {
                      _balances[from] = fromBalance - amount;
                      // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                      // decrementing then incrementing.
                      _balances[to] += amount;
                  }
          
                  emit Transfer(from, to, amount);
          
                  _afterTokenTransfer(from, to, amount);
              }
          
              /** @dev Creates `amount` tokens and assigns them to `account`, increasing
               * the total supply.
               *
               * Emits a {Transfer} event with `from` set to the zero address.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               */
              function _mint(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: mint to the zero address");
          
                  _beforeTokenTransfer(address(0), account, amount);
          
                  _totalSupply += amount;
                  unchecked {
                      // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                      _balances[account] += amount;
                  }
                  emit Transfer(address(0), account, amount);
          
                  _afterTokenTransfer(address(0), account, amount);
              }
          
              /**
               * @dev Destroys `amount` tokens from `account`, reducing the
               * total supply.
               *
               * Emits a {Transfer} event with `to` set to the zero address.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               * - `account` must have at least `amount` tokens.
               */
              function _burn(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: burn from the zero address");
          
                  _beforeTokenTransfer(account, address(0), amount);
          
                  uint256 accountBalance = _balances[account];
                  require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                  unchecked {
                      _balances[account] = accountBalance - amount;
                      // Overflow not possible: amount <= accountBalance <= totalSupply.
                      _totalSupply -= amount;
                  }
          
                  emit Transfer(account, address(0), amount);
          
                  _afterTokenTransfer(account, address(0), amount);
              }
          
              /**
               * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
               *
               * This internal function is equivalent to `approve`, and can be used to
               * e.g. set automatic allowances for certain subsystems, etc.
               *
               * Emits an {Approval} event.
               *
               * Requirements:
               *
               * - `owner` cannot be the zero address.
               * - `spender` cannot be the zero address.
               */
              function _approve(
                  address owner,
                  address spender,
                  uint256 amount
              ) internal virtual {
                  require(owner != address(0), "ERC20: approve from the zero address");
                  require(spender != address(0), "ERC20: approve to the zero address");
          
                  _allowances[owner][spender] = amount;
                  emit Approval(owner, spender, amount);
              }
          
              /**
               * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
               *
               * Does not update the allowance amount in case of infinite allowance.
               * Revert if not enough allowance is available.
               *
               * Might emit an {Approval} event.
               */
              function _spendAllowance(
                  address owner,
                  address spender,
                  uint256 amount
              ) internal virtual {
                  uint256 currentAllowance = allowance(owner, spender);
                  if (currentAllowance != type(uint256).max) {
                      require(currentAllowance >= amount, "ERC20: insufficient allowance");
                      unchecked {
                          _approve(owner, spender, currentAllowance - amount);
                      }
                  }
              }
          
              /**
               * @dev Hook that is called before any transfer of tokens. This includes
               * minting and burning.
               *
               * Calling conditions:
               *
               * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
               * will be transferred to `to`.
               * - when `from` is zero, `amount` tokens will be minted for `to`.
               * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
               * - `from` and `to` are never both zero.
               *
               * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
               */
              function _beforeTokenTransfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {}
          
              /**
               * @dev Hook that is called after any transfer of tokens. This includes
               * minting and burning.
               *
               * Calling conditions:
               *
               * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
               * has been transferred to `to`.
               * - when `from` is zero, `amount` tokens have been minted for `to`.
               * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
               * - `from` and `to` are never both zero.
               *
               * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
               */
              function _afterTokenTransfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {}
          
              /**
               * @dev This empty reserved space is put in place to allow future versions to add new
               * variables without shifting down storage in the inheritance chain.
               * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
               */
              uint256[45] private __gap;
          }
          
          
          // File contracts/mock/MockToken.sol
          
          
          pragma solidity ^0.8.13;
          
          contract MockToken is ERC20Upgradeable {
              function mint(address account, uint256 amount) external {
                  _mint(account, amount);
              }
          
              function burn(uint256 _amount) external {
                  _burn(msg.sender, _amount);
              }
          }
          
          
          // File contracts/mock/MockCircleBridge.sol
          
          
          pragma solidity ^0.8.13;
          
          
          contract MockCircleBridge is ICircleBridge {
              uint64 public nextNonce = 0;
              MockToken token;
          
              constructor(MockToken _token) {
                  token = _token;
              }
          
              function depositForBurn(
                  uint256 _amount,
                  uint32,
                  bytes32,
                  address _burnToken
              ) external returns (uint64 _nonce) {
                  nextNonce = nextNonce + 1;
                  _nonce = nextNonce;
                  require(address(token) == _burnToken);
                  token.transferFrom(msg.sender, address(this), _amount);
                  token.burn(_amount);
              }
          
              function depositForBurnWithCaller(
                  uint256,
                  uint32,
                  bytes32,
                  address,
                  bytes32
              ) external returns (uint64 _nonce) {
                  nextNonce = nextNonce + 1;
                  _nonce = nextNonce;
              }
          }
          
          
          // File contracts/mock/MockCircleMessageTransmitter.sol
          
          
          pragma solidity ^0.8.13;
          
          
          contract MockCircleMessageTransmitter is ICircleMessageTransmitter {
              mapping(bytes32 => bool) processedNonces;
              MockToken token;
          
              constructor(MockToken _token) {
                  token = _token;
              }
          
              function receiveMessage(bytes memory, bytes calldata)
                  external
                  pure
                  returns (bool success)
              {
                  success = true;
              }
          
              function hashSourceAndNonce(uint32 _source, uint256 _nonce)
                  public
                  pure
                  returns (bytes32)
              {
                  return keccak256(abi.encodePacked(_source, _nonce));
              }
          
              function process(
                  bytes32 _nonceId,
                  address _recipient,
                  uint256 _amount
              ) public {
                  processedNonces[_nonceId] = true;
                  token.mint(_recipient, _amount);
              }
          
              function usedNonces(bytes32 _nonceId) external view returns (bool) {
                  return processedNonces[_nonceId];
              }
          }
          
          
          // File contracts/mock/MockMailbox.sol
          
          
          pragma solidity ^0.8.0;
          
          
          contract MockMailbox {
              using TypeCasts for address;
              using TypeCasts for bytes32;
              // Domain of chain on which the contract is deployed
              uint32 public immutable domain;
              uint32 public immutable version = 0;
          
              uint256 public outboundNonce = 0;
              uint256 public inboundUnprocessedNonce = 0;
              uint256 public inboundProcessedNonce = 0;
              mapping(uint32 => MockMailbox) public remoteMailboxes;
              mapping(uint256 => Message) public inboundMessages;
          
              struct Message {
                  uint32 origin;
                  address sender;
                  address recipient;
                  bytes body;
              }
          
              constructor(uint32 _domain) {
                  domain = _domain;
              }
          
              function addRemoteMailbox(uint32 _domain, MockMailbox _mailbox) external {
                  remoteMailboxes[_domain] = _mailbox;
              }
          
              function dispatch(
                  uint32 _destinationDomain,
                  bytes32 _recipientAddress,
                  bytes calldata _messageBody
              ) external returns (bytes32) {
                  MockMailbox _destinationMailbox = remoteMailboxes[_destinationDomain];
                  require(
                      address(_destinationMailbox) != address(0),
                      "Missing remote mailbox"
                  );
                  _destinationMailbox.addInboundMessage(
                      domain,
                      msg.sender,
                      _recipientAddress.bytes32ToAddress(),
                      _messageBody
                  );
                  outboundNonce++;
                  return bytes32(0);
              }
          
              function addInboundMessage(
                  uint32 _origin,
                  address _sender,
                  address _recipient,
                  bytes calldata _body
              ) external {
                  inboundMessages[inboundUnprocessedNonce] = Message(
                      _origin,
                      _sender,
                      _recipient,
                      _body
                  );
                  inboundUnprocessedNonce++;
              }
          
              function processNextInboundMessage() public {
                  Message memory _message = inboundMessages[inboundProcessedNonce];
                  IMessageRecipient(_message.recipient).handle(
                      _message.origin,
                      _message.sender.addressToBytes32(),
                      _message.body
                  );
                  inboundProcessedNonce++;
              }
          }
          
          
          // File contracts/test/TestIsm.sol
          
          
          pragma solidity >=0.8.0;
          
          contract TestIsm is IInterchainSecurityModule {
              uint8 public constant moduleType = 0;
              bool public accept;
          
              function setAccept(bool _val) external {
                  accept = _val;
              }
          
              function verify(bytes calldata, bytes calldata)
                  external
                  view
                  returns (bool)
              {
                  return accept;
              }
          }
          
          
          // File contracts/mock/MockHyperlaneEnvironment.sol
          
          
          pragma solidity ^0.8.13;
          
          
          
          
          contract MockHyperlaneEnvironment {
              uint32 originDomain;
              uint32 destinationDomain;
          
              mapping(uint32 => MockMailbox) public mailboxes;
              mapping(uint32 => InterchainGasPaymaster) public igps;
              mapping(uint32 => IInterchainSecurityModule) public isms;
              mapping(uint32 => InterchainQueryRouter) public queryRouters;
          
              constructor(uint32 _originDomain, uint32 _destinationDomain) {
                  originDomain = _originDomain;
                  destinationDomain = _destinationDomain;
          
                  MockMailbox originMailbox = new MockMailbox(_originDomain);
                  MockMailbox destinationMailbox = new MockMailbox(_destinationDomain);
          
                  originMailbox.addRemoteMailbox(_destinationDomain, destinationMailbox);
                  destinationMailbox.addRemoteMailbox(_originDomain, originMailbox);
          
                  igps[originDomain] = new InterchainGasPaymaster();
                  igps[destinationDomain] = new InterchainGasPaymaster();
          
                  isms[originDomain] = new TestIsm();
                  isms[destinationDomain] = new TestIsm();
          
                  mailboxes[_originDomain] = originMailbox;
                  mailboxes[_destinationDomain] = destinationMailbox;
          
                  InterchainQueryRouter originQueryRouter = new InterchainQueryRouter();
                  InterchainQueryRouter destinationQueryRouter = new InterchainQueryRouter();
          
                  originQueryRouter.initialize(
                      address(originMailbox),
                      address(igps[originDomain]),
                      address(isms[originDomain])
                  );
                  destinationQueryRouter.initialize(
                      address(destinationMailbox),
                      address(igps[destinationDomain]),
                      address(isms[destinationDomain])
                  );
          
                  originQueryRouter.enrollRemoteRouter(
                      _destinationDomain,
                      TypeCasts.addressToBytes32(address(destinationQueryRouter))
                  );
                  destinationQueryRouter.enrollRemoteRouter(
                      _originDomain,
                      TypeCasts.addressToBytes32(address(originQueryRouter))
                  );
          
                  queryRouters[_originDomain] = originQueryRouter;
                  queryRouters[_destinationDomain] = destinationQueryRouter;
              }
          
              function processNextPendingMessage() public {
                  mailboxes[destinationDomain].processNextInboundMessage();
              }
          
              function processNextPendingMessageFromDestination() public {
                  mailboxes[originDomain].processNextInboundMessage();
              }
          }
          
          
          // File contracts/mock/MockInterchainAccountRouter.sol
          
          
          pragma solidity ^0.8.13;
          
          
          /*
           * @title The Hello World App
           * @dev You can use this simple app as a starting point for your own application.
           */
          contract MockInterchainAccountRouter is InterchainAccountRouter {
              struct PendingCall {
                  uint32 originDomain;
                  bytes senderAndCalls;
              }
          
              uint32 public originDomain;
          
              mapping(uint256 => PendingCall) pendingCalls;
              uint256 totalCalls = 0;
              uint256 callsProcessed = 0;
          
              constructor(uint32 _originDomain) InterchainAccountRouter() {
                  originDomain = _originDomain;
              }
          
              function _dispatch(uint32, bytes memory _messageBody)
                  internal
                  override
                  returns (bytes32)
              {
                  pendingCalls[totalCalls] = PendingCall(originDomain, _messageBody);
                  totalCalls += 1;
                  return keccak256(abi.encodePacked(totalCalls));
              }
          
              function processNextPendingCall() public {
                  PendingCall memory pendingCall = pendingCalls[callsProcessed];
                  (address sender, Call[] memory calls) = abi.decode(
                      pendingCall.senderAndCalls,
                      (address, Call[])
                  );
          
                  getDeployedInterchainAccount(originDomain, sender).proxyCalls(calls);
          
                  callsProcessed += 1;
              }
          }
          
          
          // File contracts/test/bad-recipient/BadRecipient1.sol
          
          
          pragma solidity >=0.8.0;
          
          contract BadRecipient1 is IMessageRecipient {
              function handle(
                  uint32,
                  bytes32,
                  bytes calldata
              ) external pure override {
                  assembly {
                      revert(0, 0)
                  }
              }
          }
          
          
          // File contracts/test/bad-recipient/BadRecipient3.sol
          
          
          pragma solidity >=0.8.0;
          
          contract BadRecipient3 is IMessageRecipient {
              function handle(
                  uint32,
                  bytes32,
                  bytes calldata
              ) external pure override {
                  assembly {
                      mstore(0, 0xabcdef)
                      revert(0, 32)
                  }
              }
          }
          
          
          // File contracts/test/bad-recipient/BadRecipient5.sol
          
          
          pragma solidity >=0.8.0;
          
          contract BadRecipient5 is IMessageRecipient {
              function handle(
                  uint32,
                  bytes32,
                  bytes calldata
              ) external pure override {
                  require(false, "no can do");
              }
          }
          
          
          // File contracts/test/bad-recipient/BadRecipient6.sol
          
          
          pragma solidity >=0.8.0;
          
          contract BadRecipient6 is IMessageRecipient {
              function handle(
                  uint32,
                  bytes32,
                  bytes calldata
              ) external pure override {
                  require(false); // solhint-disable-line reason-string
              }
          }
          
          
          // File contracts/test/TestHyperlaneConnectionClient.sol
          
          
          pragma solidity >=0.6.11;
          
          
          contract TestHyperlaneConnectionClient is HyperlaneConnectionClient {
              function initialize(address _mailbox) external initializer {
                  __HyperlaneConnectionClient_initialize(_mailbox);
              }
          
              function localDomain() external view returns (uint32) {
                  return mailbox.localDomain();
              }
          }
          
          
          // File contracts/test/TestLiquidityLayerMessageRecipient.sol
          
          
          pragma solidity ^0.8.13;
          
          contract TestLiquidityLayerMessageRecipient is ILiquidityLayerMessageRecipient {
              event HandledWithTokens(
                  uint32 origin,
                  bytes32 sender,
                  bytes message,
                  address token,
                  uint256 amount
              );
          
              function handleWithTokens(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes calldata _message,
                  address _token,
                  uint256 _amount
              ) external {
                  emit HandledWithTokens(_origin, _sender, _message, _token, _amount);
              }
          }
          
          
          // File contracts/test/TestMailbox.sol
          
          
          pragma solidity >=0.8.0;
          
          
          
          
          contract TestMailbox is Mailbox {
              using TypeCasts for bytes32;
          
              constructor(uint32 _localDomain) Mailbox(_localDomain) {} // solhint-disable-line no-empty-blocks
          
              function proof() external view returns (bytes32[32] memory) {
                  bytes32[32] memory _zeroes = MerkleLib.zeroHashes();
                  uint256 _index = tree.count - 1;
                  bytes32[32] memory _proof;
          
                  for (uint256 i = 0; i < 32; i++) {
                      uint256 _ithBit = (_index >> i) & 0x01;
                      if (_ithBit == 1) {
                          _proof[i] = tree.branch[i];
                      } else {
                          _proof[i] = _zeroes[i];
                      }
                  }
                  return _proof;
              }
          
              function testHandle(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes32 _recipient,
                  bytes calldata _body
              ) external {
                  IMessageRecipient(_recipient.bytes32ToAddress()).handle(
                      _origin,
                      _sender,
                      _body
                  );
              }
          }
          
          
          // File contracts/test/TestMerkle.sol
          
          
          pragma solidity >=0.8.0;
          
          contract TestMerkle {
              using MerkleLib for MerkleLib.Tree;
          
              MerkleLib.Tree public tree;
          
              // solhint-disable-next-line no-empty-blocks
              constructor() {}
          
              function insert(bytes32 _node) external {
                  tree.insert(_node);
              }
          
              function branchRoot(
                  bytes32 _leaf,
                  bytes32[32] calldata _proof,
                  uint256 _index
              ) external pure returns (bytes32 _node) {
                  return MerkleLib.branchRoot(_leaf, _proof, _index);
              }
          
              /**
               * @notice Returns the number of inserted leaves in the tree
               */
              function count() public view returns (uint256) {
                  return tree.count;
              }
          
              function root() public view returns (bytes32) {
                  return tree.root();
              }
          }
          
          
          // File contracts/test/TestMessage.sol
          
          
          pragma solidity >=0.6.11;
          
          contract TestMessage {
              using Message for bytes;
          
              function version(bytes calldata _message)
                  external
                  pure
                  returns (uint32 _version)
              {
                  return _message.version();
              }
          
              function nonce(bytes calldata _message)
                  external
                  pure
                  returns (uint256 _nonce)
              {
                  return _message.nonce();
              }
          
              function body(bytes calldata _message)
                  external
                  pure
                  returns (bytes calldata _body)
              {
                  return _message.body();
              }
          
              function origin(bytes calldata _message)
                  external
                  pure
                  returns (uint32 _origin)
              {
                  return _message.origin();
              }
          
              function sender(bytes calldata _message)
                  external
                  pure
                  returns (bytes32 _sender)
              {
                  return _message.sender();
              }
          
              function destination(bytes calldata _message)
                  external
                  pure
                  returns (uint32 _destination)
              {
                  return _message.destination();
              }
          
              function recipient(bytes calldata _message)
                  external
                  pure
                  returns (bytes32 _recipient)
              {
                  return _message.recipient();
              }
          
              function recipientAddress(bytes calldata _message)
                  external
                  pure
                  returns (address _recipient)
              {
                  return _message.recipientAddress();
              }
          
              function id(bytes calldata _message) external pure returns (bytes32) {
                  return _message.id();
              }
          }
          
          
          // File contracts/test/TestMultisigIsm.sol
          
          
          pragma solidity >=0.8.0;
          
          // ============ Internal Imports ============
          
          contract TestMultisigIsm is MultisigIsm {
              function getDomainHash(uint32 _origin, bytes32 _originMailbox)
                  external
                  pure
                  returns (bytes32)
              {
                  return _getDomainHash(_origin, _originMailbox);
              }
          
              function getCheckpointDigest(bytes calldata _metadata, uint32 _origin)
                  external
                  pure
                  returns (bytes32)
              {
                  return _getCheckpointDigest(_metadata, _origin);
              }
          }
          
          
          // File contracts/test/TestQuery.sol
          
          
          pragma solidity ^0.8.13;
          
          
          
          contract TestQuery {
              InterchainQueryRouter public router;
          
              event Owner(uint256, address);
          
              constructor(address _router) {
                  router = InterchainQueryRouter(_router);
              }
          
              /**
               * @dev Fetches owner of InterchainQueryRouter on provided domain and passes along with provided secret to `this.receiveRouterOwner`
               */
              function queryRouterOwner(uint32 domain, uint256 secret) external {
                  Call memory call = Call({
                      to: TypeCasts.bytes32ToAddress(router.routers(domain)),
                      data: abi.encodeWithSignature("owner()")
                  });
                  bytes memory callback = bytes.concat(
                      this.receiveRouterOwer.selector,
                      bytes32(secret)
                  );
                  router.query(domain, call, callback);
              }
          
              /**
               * @dev `msg.sender` must be restricted to `this.router` to prevent any local account from spoofing query data.
               */
              function receiveRouterOwer(uint256 secret, address owner) external {
                  require(msg.sender == address(router), "TestQuery: not from router");
                  emit Owner(secret, owner);
              }
          }
          
          
          // File contracts/test/TestQuerySender.sol
          
          
          pragma solidity >=0.8.0;
          
          
          contract TestQuerySender is Initializable {
              IInterchainQueryRouter queryRouter;
          
              address public lastAddressResult;
              uint256 public lastUint256Result;
              bytes32 public lastBytes32Result;
          
              event ReceivedAddressResult(address result);
              event ReceivedUint256Result(uint256 result);
              event ReceivedBytes32Result(bytes32 result);
          
              function initialize(address _queryRouterAddress) public initializer {
                  queryRouter = IInterchainQueryRouter(_queryRouterAddress);
              }
          
              function queryAddress(
                  uint32 _destinationDomain,
                  address _target,
                  bytes calldata _targetData
              ) public {
                  queryRouter.query(
                      _destinationDomain,
                      Call({to: _target, data: _targetData}),
                      abi.encodePacked(this.handleQueryAddressResult.selector)
                  );
              }
          
              function handleQueryAddressResult(address _result) public {
                  emit ReceivedAddressResult(_result);
                  lastAddressResult = _result;
              }
          
              function queryUint256(
                  uint32 _destinationDomain,
                  address _target,
                  bytes calldata _targetData
              ) public {
                  queryRouter.query(
                      _destinationDomain,
                      Call({to: _target, data: _targetData}),
                      abi.encodePacked(this.handleQueryUint256Result.selector)
                  );
              }
          
              function handleQueryUint256Result(uint256 _result) public {
                  emit ReceivedUint256Result(_result);
                  lastUint256Result = _result;
              }
          
              function queryBytes32(
                  uint32 _destinationDomain,
                  address _target,
                  bytes calldata _targetData
              ) public {
                  queryRouter.query(
                      _destinationDomain,
                      Call({to: _target, data: _targetData}),
                      abi.encodePacked(this.handleQueryBytes32Result.selector)
                  );
              }
          
              function handleQueryBytes32Result(bytes32 _result) public {
                  emit ReceivedBytes32Result(_result);
                  lastBytes32Result = _result;
              }
          }
          
          
          // File contracts/test/TestRecipient.sol
          
          
          pragma solidity >=0.8.0;
          
          
          contract TestRecipient is
              IMessageRecipient,
              ISpecifiesInterchainSecurityModule
          {
              IInterchainSecurityModule public interchainSecurityModule;
              bytes32 public lastSender;
              bytes public lastData;
          
              address public lastCaller;
              string public lastCallMessage;
          
              event ReceivedMessage(
                  uint32 indexed origin,
                  bytes32 indexed sender,
                  string message
              );
          
              event ReceivedCall(address indexed caller, uint256 amount, string message);
          
              function setInterchainSecurityModule(address _ism) external {
                  interchainSecurityModule = IInterchainSecurityModule(_ism);
              }
          
              function handle(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes calldata _data
              ) external override {
                  emit ReceivedMessage(_origin, _sender, string(_data));
                  lastSender = _sender;
                  lastData = _data;
              }
          
              function fooBar(uint256 amount, string calldata message) external {
                  emit ReceivedCall(msg.sender, amount, message);
                  lastCaller = msg.sender;
                  lastCallMessage = message;
              }
          }
          
          
          // File contracts/test/TestRouter.sol
          
          
          pragma solidity >=0.6.11;
          
          contract TestRouter is Router {
              event InitializeOverload();
          
              function initialize(address _mailbox) external initializer {
                  __Router_initialize(_mailbox);
                  emit InitializeOverload();
              }
          
              function _handle(
                  uint32,
                  bytes32,
                  bytes calldata
              ) internal pure override {}
          
              function isRemoteRouter(uint32 _domain, bytes32 _potentialRemoteRouter)
                  external
                  view
                  returns (bool)
              {
                  return _isRemoteRouter(_domain, _potentialRemoteRouter);
              }
          
              function mustHaveRemoteRouter(uint32 _domain)
                  external
                  view
                  returns (bytes32)
              {
                  return _mustHaveRemoteRouter(_domain);
              }
          
              function dispatch(uint32 _destination, bytes memory _msg) external {
                  _dispatch(_destination, _msg);
              }
          
              function dispatchWithGas(
                  uint32 _destinationDomain,
                  bytes memory _messageBody,
                  uint256 _gasAmount,
                  uint256 _gasPayment,
                  address _gasPaymentRefundAddress
              ) external payable {
                  _dispatchWithGas(
                      _destinationDomain,
                      _messageBody,
                      _gasAmount,
                      _gasPayment,
                      _gasPaymentRefundAddress
                  );
              }
          }
          
          
          // File contracts/test/TestSendReceiver.sol
          
          
          pragma solidity >=0.8.0;
          
          
          
          contract TestSendReceiver is IMessageRecipient {
              using TypeCasts for address;
          
              uint256 public constant HANDLE_GAS_AMOUNT = 50_000;
          
              event Handled(bytes32 blockHash);
          
              function dispatchToSelf(
                  IMailbox _mailbox,
                  IInterchainGasPaymaster _paymaster,
                  uint32 _destinationDomain,
                  bytes calldata _messageBody
              ) external payable {
                  bytes32 _messageId = _mailbox.dispatch(
                      _destinationDomain,
                      address(this).addressToBytes32(),
                      _messageBody
                  );
                  uint256 _blockHashNum = uint256(previousBlockHash());
                  uint256 _value = msg.value;
                  if (_blockHashNum % 5 == 0) {
                      // Pay in two separate calls, resulting in 2 distinct events
                      uint256 _halfPayment = _value / 2;
                      uint256 _halfGasAmount = HANDLE_GAS_AMOUNT / 2;
                      _paymaster.payForGas{value: _halfPayment}(
                          _messageId,
                          _destinationDomain,
                          _halfGasAmount,
                          msg.sender
                      );
                      _paymaster.payForGas{value: _value - _halfPayment}(
                          _messageId,
                          _destinationDomain,
                          HANDLE_GAS_AMOUNT - _halfGasAmount,
                          msg.sender
                      );
                  } else {
                      // Pay the entire msg.value in one call
                      _paymaster.payForGas{value: _value}(
                          _messageId,
                          _destinationDomain,
                          HANDLE_GAS_AMOUNT,
                          msg.sender
                      );
                  }
              }
          
              function handle(
                  uint32,
                  bytes32,
                  bytes calldata
              ) external override {
                  bytes32 blockHash = previousBlockHash();
                  bool isBlockHashEven = uint256(blockHash) % 2 == 0;
                  require(isBlockHashEven, "block hash is odd");
                  emit Handled(blockHash);
              }
          
              function previousBlockHash() internal view returns (bytes32) {
                  return blockhash(block.number - 1);
              }
          }
          
          
          // File contracts/test/TestTokenRecipient.sol
          
          
          pragma solidity >=0.8.0;
          
          contract TestTokenRecipient is ILiquidityLayerMessageRecipient {
              bytes32 public lastSender;
              bytes public lastData;
              address public lastToken;
              uint256 public lastAmount;
          
              address public lastCaller;
              string public lastCallMessage;
          
              event ReceivedMessage(
                  uint32 indexed origin,
                  bytes32 indexed sender,
                  string message,
                  address token,
                  uint256 amount
              );
          
              event ReceivedCall(address indexed caller, uint256 amount, string message);
          
              function handleWithTokens(
                  uint32 _origin,
                  bytes32 _sender,
                  bytes calldata _data,
                  address _token,
                  uint256 _amount
              ) external override {
                  emit ReceivedMessage(_origin, _sender, string(_data), _token, _amount);
                  lastSender = _sender;
                  lastData = _data;
                  lastToken = _token;
                  lastAmount = _amount;
              }
          
              function fooBar(uint256 amount, string calldata message) external {
                  emit ReceivedCall(msg.sender, amount, message);
                  lastCaller = msg.sender;
                  lastCallMessage = message;
              }
          }
          
          
          // File @openzeppelin/contracts/proxy/[email protected]
          
          
          // 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 {}
          }
          
          
          // File @openzeppelin/contracts/proxy/beacon/[email protected]
          
          
          // 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);
          }
          
          
          // File @openzeppelin/contracts/interfaces/[email protected]
          
          
          // 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);
          }
          
          
          // File @openzeppelin/contracts/utils/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev Library for reading and writing primitive types to specific storage slots.
           *
           * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
           * This library helps with reading and writing to such slots without the need for inline assembly.
           *
           * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
           *
           * Example usage to set ERC1967 implementation slot:
           * ```
           * contract ERC1967 {
           *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
           *
           *     function _getImplementation() internal view returns (address) {
           *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
           *     }
           *
           *     function _setImplementation(address newImplementation) internal {
           *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
           *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
           *     }
           * }
           * ```
           *
           * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
          
              struct BooleanSlot {
                  bool value;
              }
          
              struct Bytes32Slot {
                  bytes32 value;
              }
          
              struct Uint256Slot {
                  uint256 value;
              }
          
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  /// @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
                  }
              }
          }
          
          
          // File @openzeppelin/contracts/proxy/ERC1967/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
          
          pragma solidity ^0.8.2;
          
          
          
          
          /**
           * @dev This abstract contract provides getters and event emitting update functions for
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
           *
           * _Available since v4.1._
           *
           * @custom:oz-upgrades-unsafe-allow delegatecall
           */
          abstract contract ERC1967Upgrade {
              // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
              bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
          
              /**
               * @dev Storage slot with the address of the current implementation.
               * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
          
              /**
               * @dev Emitted when the implementation is upgraded.
               */
              event Upgraded(address indexed implementation);
          
              /**
               * @dev Returns the current implementation address.
               */
              function _getImplementation() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
              }
          
              /**
               * @dev Stores a new address in the EIP1967 implementation slot.
               */
              function _setImplementation(address newImplementation) private {
                  require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                  StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
              }
          
              /**
               * @dev Perform implementation upgrade
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeTo(address newImplementation) internal {
                  _setImplementation(newImplementation);
                  emit Upgraded(newImplementation);
              }
          
              /**
               * @dev Perform implementation upgrade with additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCall(
                  address newImplementation,
                  bytes memory data,
                  bool forceCall
              ) internal {
                  _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 Emitted when the admin account has changed.
               */
              event AdminChanged(address previousAdmin, address newAdmin);
          
              /**
               * @dev Returns the current admin.
               */
              function _getAdmin() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
              }
          
              /**
               * @dev Stores a new address in the EIP1967 admin slot.
               */
              function _setAdmin(address newAdmin) private {
                  require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                  StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
              }
          
              /**
               * @dev Changes the admin of the proxy.
               *
               * Emits an {AdminChanged} event.
               */
              function _changeAdmin(address newAdmin) internal {
                  emit AdminChanged(_getAdmin(), newAdmin);
                  _setAdmin(newAdmin);
              }
          
              /**
               * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
               * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
               */
              bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
          
              /**
               * @dev Emitted when the beacon is upgraded.
               */
              event BeaconUpgraded(address indexed beacon);
          
              /**
               * @dev Returns the current beacon.
               */
              function _getBeacon() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
              }
          
              /**
               * @dev Stores a new beacon in the EIP1967 beacon slot.
               */
              function _setBeacon(address newBeacon) private {
                  require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                  require(
                      Address.isContract(IBeacon(newBeacon).implementation()),
                      "ERC1967: beacon implementation is not a contract"
                  );
                  StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
              }
          
              /**
               * @dev 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);
                  }
              }
          }
          
          
          // File @openzeppelin/contracts/proxy/ERC1967/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
          
          pragma solidity ^0.8.0;
          
          
          /**
           * @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();
              }
          }
          
          
          // File @openzeppelin/contracts/proxy/transparent/[email protected]
          
          
          // OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
          
          pragma solidity ^0.8.0;
          
          /**
           * @dev This contract implements a proxy that is upgradeable by an admin.
           *
           * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
           * clashing], which can potentially be used in an attack, this contract uses the
           * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
           * things that go hand in hand:
           *
           * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
           * that call matches one of the admin functions exposed by the proxy itself.
           * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
           * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
           * "admin cannot fallback to proxy target".
           *
           * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
           * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
           * to sudden errors when trying to call a function from the proxy implementation.
           *
           * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
           * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
           */
          contract TransparentUpgradeableProxy is ERC1967Proxy {
              /**
               * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
               * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
               */
              constructor(
                  address _logic,
                  address admin_,
                  bytes memory _data
              ) payable ERC1967Proxy(_logic, _data) {
                  _changeAdmin(admin_);
              }
          
              /**
               * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
               */
              modifier ifAdmin() {
                  if (msg.sender == _getAdmin()) {
                      _;
                  } else {
                      _fallback();
                  }
              }
          
              /**
               * @dev Returns the current admin.
               *
               * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
               *
               * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
               * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
               * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
               */
              function admin() external ifAdmin returns (address admin_) {
                  admin_ = _getAdmin();
              }
          
              /**
               * @dev Returns the current implementation.
               *
               * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
               *
               * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
               * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
               * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
               */
              function implementation() external ifAdmin returns (address implementation_) {
                  implementation_ = _implementation();
              }
          
              /**
               * @dev Changes the admin of the proxy.
               *
               * Emits an {AdminChanged} event.
               *
               * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
               */
              function changeAdmin(address newAdmin) external virtual ifAdmin {
                  _changeAdmin(newAdmin);
              }
          
              /**
               * @dev Upgrade the implementation of the proxy.
               *
               * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
               */
              function upgradeTo(address newImplementation) external ifAdmin {
                  _upgradeToAndCall(newImplementation, bytes(""), false);
              }
          
              /**
               * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
               * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
               * proxied contract.
               *
               * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
               */
              function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
                  _upgradeToAndCall(newImplementation, data, true);
              }
          
              /**
               * @dev Returns the current admin.
               */
              function _admin() internal view virtual returns (address) {
                  return _getAdmin();
              }
          
              /**
               * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
               */
              function _beforeFallback() internal virtual override {
                  require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                  super._beforeFallback();
              }
          }
          
          
          // File @openzeppelin/contracts/proxy/transparent/[email protected]
          
          
          // OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol)
          
          pragma solidity ^0.8.0;
          
          
          /**
           * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
           * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
           */
          contract ProxyAdmin is Ownable {
              /**
               * @dev Returns the current implementation of `proxy`.
               *
               * Requirements:
               *
               * - This contract must be the admin of `proxy`.
               */
              function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                  // We need to manually run the static call since the getter cannot be flagged as view
                  // bytes4(keccak256("implementation()")) == 0x5c60da1b
                  (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
                  require(success);
                  return abi.decode(returndata, (address));
              }
          
              /**
               * @dev Returns the current admin of `proxy`.
               *
               * Requirements:
               *
               * - This contract must be the admin of `proxy`.
               */
              function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                  // We need to manually run the static call since the getter cannot be flagged as view
                  // bytes4(keccak256("admin()")) == 0xf851a440
                  (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
                  require(success);
                  return abi.decode(returndata, (address));
              }
          
              /**
               * @dev Changes the admin of `proxy` to `newAdmin`.
               *
               * Requirements:
               *
               * - This contract must be the current admin of `proxy`.
               */
              function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
                  proxy.changeAdmin(newAdmin);
              }
          
              /**
               * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
               *
               * Requirements:
               *
               * - This contract must be the admin of `proxy`.
               */
              function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
                  proxy.upgradeTo(implementation);
              }
          
              /**
               * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
               * {TransparentUpgradeableProxy-upgradeToAndCall}.
               *
               * Requirements:
               *
               * - This contract must be the admin of `proxy`.
               */
              function upgradeAndCall(
                  TransparentUpgradeableProxy proxy,
                  address implementation,
                  bytes memory data
              ) public payable virtual onlyOwner {
                  proxy.upgradeToAndCall{value: msg.value}(implementation, data);
              }
          }
          
          
          // File contracts/upgrade/ProxyAdmin.sol
          
          
          // OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol)
          
          pragma solidity ^0.8.0;
          
          
          // File contracts/upgrade/TransparentUpgradeableProxy.sol
          
          
          // OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
          
          pragma solidity ^0.8.0;
          
          
          // File contracts/Create2Factory.sol
          
          
          // Copied from https://github.com/axelarnetwork/axelar-utils-solidity/commits/main/contracts/ConstAddressDeployer.sol
          
          pragma solidity ^0.8.0;
          
          contract Create2Factory {
              error EmptyBytecode();
              error FailedDeploy();
              error FailedInit();
          
              event Deployed(
                  bytes32 indexed bytecodeHash,
                  bytes32 indexed salt,
                  address indexed deployedAddress
              );
          
              /**
               * @dev Deploys a contract using `CREATE2`. The address where the contract
               * will be deployed can be known in advance via {deployedAddress}.
               *
               * The bytecode for a contract can be obtained from Solidity with
               * `type(contractName).creationCode`.
               *
               * Requirements:
               *
               * - `bytecode` must not be empty.
               * - `salt` must have not been used for `bytecode` already by the same `msg.sender`.
               */
              function deploy(bytes memory bytecode, bytes32 salt)
                  external
                  returns (address deployedAddress_)
              {
                  deployedAddress_ = _deploy(
                      bytecode,
                      keccak256(abi.encode(msg.sender, salt))
                  );
              }
          
              /**
               * @dev Deploys a contract using `CREATE2` and initialize it. The address where the contract
               * will be deployed can be known in advance via {deployedAddress}.
               *
               * The bytecode for a contract can be obtained from Solidity with
               * `type(contractName).creationCode`.
               *
               * Requirements:
               *
               * - `bytecode` must not be empty.
               * - `salt` must have not been used for `bytecode` already by the same `msg.sender`.
               * - `init` is used to initialize the deployed contract
               *    as an option to not have the constructor args affect the address derived by `CREATE2`.
               */
              function deployAndInit(
                  bytes memory bytecode,
                  bytes32 salt,
                  bytes calldata init
              ) external returns (address deployedAddress_) {
                  deployedAddress_ = _deploy(
                      bytecode,
                      keccak256(abi.encode(msg.sender, salt))
                  );
          
                  // solhint-disable-next-line avoid-low-level-calls
                  (bool success, ) = deployedAddress_.call(init);
                  if (!success) revert FailedInit();
              }
          
              /**
               * @dev Returns the address where a contract will be stored if deployed via {deploy} or {deployAndInit} by `sender`.
               * Any change in the `bytecode`, `sender`, or `salt` will result in a new destination address.
               */
              function deployedAddress(
                  bytes calldata bytecode,
                  address sender,
                  bytes32 salt
              ) external view returns (address deployedAddress_) {
                  bytes32 newSalt = keccak256(abi.encode(sender, salt));
                  deployedAddress_ = address(
                      uint160(
                          uint256(
                              keccak256(
                                  abi.encodePacked(
                                      hex"ff",
                                      address(this),
                                      newSalt,
                                      keccak256(bytecode) // init code hash
                                  )
                              )
                          )
                      )
                  );
              }
          
              function _deploy(bytes memory bytecode, bytes32 salt)
                  internal
                  returns (address deployedAddress_)
              {
                  if (bytecode.length == 0) revert EmptyBytecode();
          
                  // solhint-disable-next-line no-inline-assembly
                  assembly {
                      deployedAddress_ := create2(
                          0,
                          add(bytecode, 32),
                          mload(bytecode),
                          salt
                      )
                  }
          
                  if (deployedAddress_ == address(0)) revert FailedDeploy();
          
                  emit Deployed(keccak256(bytecode), salt, deployedAddress_);
              }
          }
          
          
          // File contracts/test/bad-recipient/BadRecipient2.sol
          
          
          pragma solidity >=0.8.0;
          
          contract BadRecipient2 {
              function handle(uint32, bytes32) external pure {} // solhint-disable-line no-empty-blocks
          }
          

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

          File 3 of 6: PolygonZkEVMBridgeV2
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
          pragma solidity ^0.8.2;
          import "../../utils/AddressUpgradeable.sol";
          /**
           * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
           * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
           * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
           * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
           *
           * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
           * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
           * case an upgrade adds a module that needs to be initialized.
           *
           * For example:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * 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.8.0) (security/ReentrancyGuard.sol)
          pragma solidity ^0.8.0;
          import "../proxy/utils/Initializable.sol";
          /**
           * @dev Contract module that helps prevent reentrant calls to a function.
           *
           * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
           * available, which can be applied to functions to make sure there are no nested
           * (reentrant) calls to them.
           *
           * Note that because there is a single `nonReentrant` guard, functions marked as
           * `nonReentrant` may not call one another. This can be worked around by making
           * those functions `private`, and then adding `external` `nonReentrant` entry
           * points to them.
           *
           * TIP: If you would like to learn more about reentrancy and alternative ways
           * to protect against it, check out our blog post
           * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
           */
          abstract contract ReentrancyGuardUpgradeable is Initializable {
              // Booleans are more expensive than uint256 or any type that takes up a full
              // word because each write operation emits an extra SLOAD to first read the
              // slot's contents, replace the bits taken up by the boolean, and then write
              // back. This is the compiler's defense against contract upgrades and
              // pointer aliasing, and it cannot be disabled.
              // The values being non-zero value makes deployment a bit more expensive,
              // but in exchange the refund on every call to nonReentrant will be lower in
              // amount. Since refunds are capped to a percentage of the total
              // transaction's gas, it is best to keep them low in cases like this one, to
              // increase the likelihood of the full refund coming into effect.
              uint256 private constant _NOT_ENTERED = 1;
              uint256 private constant _ENTERED = 2;
              uint256 private _status;
              function __ReentrancyGuard_init() internal onlyInitializing {
                  __ReentrancyGuard_init_unchained();
              }
              function __ReentrancyGuard_init_unchained() internal onlyInitializing {
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev Prevents a contract from calling itself, directly or indirectly.
               * Calling a `nonReentrant` function from another `nonReentrant`
               * function is not supported. It is possible to prevent this from happening
               * by making the `nonReentrant` function external, and making it call a
               * `private` function that does the actual work.
               */
              modifier nonReentrant() {
                  _nonReentrantBefore();
                  _;
                  _nonReentrantAfter();
              }
              function _nonReentrantBefore() private {
                  // On the first call to nonReentrant, _status will be _NOT_ENTERED
                  require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                  // Any calls to nonReentrant after this point will fail
                  _status = _ENTERED;
              }
              function _nonReentrantAfter() private {
                  // By storing the original value once again, a refund is triggered (see
                  // https://eips.ethereum.org/EIPS/eip-2200)
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev This empty reserved space is put in place to allow future versions to add new
               * variables without shifting down storage in the inheritance chain.
               * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
               */
              uint256[49] private __gap;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
           * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
           *
           * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
           * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
           * need to send a transaction, and thus is not required to hold Ether at all.
           */
          interface IERC20PermitUpgradeable {
              /**
               * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
               * given ``owner``'s signed approval.
               *
               * IMPORTANT: The same issues {IERC20-approve} has related to transaction
               * ordering also apply here.
               *
               * Emits an {Approval} event.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               * - `deadline` must be a timestamp in the future.
               * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
               * over the EIP712-formatted function arguments.
               * - the signature must use ``owner``'s current nonce (see {nonces}).
               *
               * For more information on the signature format, see the
               * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
               * section].
               */
              function permit(
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) external;
              /**
               * @dev Returns the current nonce for `owner`. This value must be
               * included whenever a signature is generated for {permit}.
               *
               * Every successful call to {permit} increases ``owner``'s nonce by one. This
               * prevents a signature from being used multiple times.
               */
              function nonces(address owner) external view returns (uint256);
              /**
               * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
               */
              // solhint-disable-next-line func-name-mixedcase
              function DOMAIN_SEPARATOR() external view returns (bytes32);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
          pragma solidity ^0.8.0;
          import "../IERC20Upgradeable.sol";
          /**
           * @dev Interface for the optional metadata functions from the ERC20 standard.
           *
           * _Available since v4.1._
           */
          interface IERC20MetadataUpgradeable is IERC20Upgradeable {
              /**
               * @dev Returns the name of the token.
               */
              function name() external view returns (string memory);
              /**
               * @dev Returns the symbol of the token.
               */
              function symbol() external view returns (string memory);
              /**
               * @dev Returns the decimals places of the token.
               */
              function decimals() external view returns (uint8);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20Upgradeable {
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
              /**
               * @dev Moves `amount` tokens from the caller's account to `to`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address to, uint256 amount) external returns (bool);
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
              /**
               * @dev Moves `amount` tokens from `from` to `to` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) external returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
          pragma solidity ^0.8.0;
          import "../IERC20Upgradeable.sol";
          import "../extensions/draft-IERC20PermitUpgradeable.sol";
          import "../../../utils/AddressUpgradeable.sol";
          /**
           * @title SafeERC20
           * @dev Wrappers around ERC20 operations that throw on failure (when the token
           * contract returns false). Tokens that return no value (and instead revert or
           * throw on failure) are also supported, non-reverting calls are assumed to be
           * successful.
           * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
           * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
           */
          library SafeERC20Upgradeable {
              using AddressUpgradeable for address;
              function safeTransfer(
                  IERC20Upgradeable token,
                  address to,
                  uint256 value
              ) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
              }
              function safeTransferFrom(
                  IERC20Upgradeable token,
                  address from,
                  address to,
                  uint256 value
              ) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
              }
              /**
               * @dev Deprecated. This function has issues similar to the ones found in
               * {IERC20-approve}, and its usage is discouraged.
               *
               * Whenever possible, use {safeIncreaseAllowance} and
               * {safeDecreaseAllowance} instead.
               */
              function safeApprove(
                  IERC20Upgradeable token,
                  address spender,
                  uint256 value
              ) internal {
                  // safeApprove should only be called when setting an initial allowance,
                  // or when resetting it to zero. To increase and decrease it, use
                  // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                  require(
                      (value == 0) || (token.allowance(address(this), spender) == 0),
                      "SafeERC20: approve from non-zero to non-zero allowance"
                  );
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
              }
              function safeIncreaseAllowance(
                  IERC20Upgradeable token,
                  address spender,
                  uint256 value
              ) internal {
                  uint256 newAllowance = token.allowance(address(this), spender) + value;
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
              }
              function safeDecreaseAllowance(
                  IERC20Upgradeable token,
                  address spender,
                  uint256 value
              ) internal {
                  unchecked {
                      uint256 oldAllowance = token.allowance(address(this), spender);
                      require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                      uint256 newAllowance = oldAllowance - value;
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                  }
              }
              function safePermit(
                  IERC20PermitUpgradeable token,
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) internal {
                  uint256 nonceBefore = token.nonces(owner);
                  token.permit(owner, spender, value, deadline, v, r, s);
                  uint256 nonceAfter = token.nonces(owner);
                  require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
              }
              /**
               * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
               * on the return value: the return value is optional (but if data is returned, it must not be false).
               * @param token The token targeted by the call.
               * @param data The call data (encoded using abi.encode or one of its variants).
               */
              function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
                  // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                  // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                  // the target address contains contract code and also asserts for success in the low-level call.
                  bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                  if (returndata.length > 0) {
                      // Return data is optional
                      require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library AddressUpgradeable {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return 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 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.8.0) (token/ERC20/ERC20.sol)
          pragma solidity ^0.8.0;
          import "./IERC20.sol";
          import "./extensions/IERC20Metadata.sol";
          import "../../utils/Context.sol";
          /**
           * @dev Implementation of the {IERC20} interface.
           *
           * This implementation is agnostic to the way tokens are created. This means
           * that a supply mechanism has to be added in a derived contract using {_mint}.
           * For a generic mechanism see {ERC20PresetMinterPauser}.
           *
           * TIP: For a detailed writeup see our guide
           * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
           * to implement supply mechanisms].
           *
           * We have followed general OpenZeppelin Contracts guidelines: functions revert
           * instead returning `false` on failure. This behavior is nonetheless
           * conventional and does not conflict with the expectations of ERC20
           * applications.
           *
           * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
           * This allows applications to reconstruct the allowance for all accounts just
           * by listening to said events. Other implementations of the EIP may not emit
           * these events, as it isn't required by the specification.
           *
           * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
           * functions have been added to mitigate the well-known issues around setting
           * allowances. See {IERC20-approve}.
           */
          contract ERC20 is Context, IERC20, IERC20Metadata {
              mapping(address => uint256) private _balances;
              mapping(address => mapping(address => uint256)) private _allowances;
              uint256 private _totalSupply;
              string private _name;
              string private _symbol;
              /**
               * @dev Sets the values for {name} and {symbol}.
               *
               * The default value of {decimals} is 18. To select a different value for
               * {decimals} you should overload it.
               *
               * All two of these values are immutable: they can only be set once during
               * construction.
               */
              constructor(string memory name_, string memory symbol_) {
                  _name = name_;
                  _symbol = symbol_;
              }
              /**
               * @dev Returns the name of the token.
               */
              function name() public view virtual override returns (string memory) {
                  return _name;
              }
              /**
               * @dev Returns the symbol of the token, usually a shorter version of the
               * name.
               */
              function symbol() public view virtual override returns (string memory) {
                  return _symbol;
              }
              /**
               * @dev Returns the number of decimals used to get its user representation.
               * For example, if `decimals` equals `2`, a balance of `505` tokens should
               * be displayed to a user as `5.05` (`505 / 10 ** 2`).
               *
               * Tokens usually opt for a value of 18, imitating the relationship between
               * Ether and Wei. This is the value {ERC20} uses, unless this function is
               * overridden;
               *
               * NOTE: This information is only used for _display_ purposes: it in
               * no way affects any of the arithmetic of the contract, including
               * {IERC20-balanceOf} and {IERC20-transfer}.
               */
              function decimals() public view virtual override returns (uint8) {
                  return 18;
              }
              /**
               * @dev See {IERC20-totalSupply}.
               */
              function totalSupply() public view virtual override returns (uint256) {
                  return _totalSupply;
              }
              /**
               * @dev See {IERC20-balanceOf}.
               */
              function balanceOf(address account) public view virtual override returns (uint256) {
                  return _balances[account];
              }
              /**
               * @dev See {IERC20-transfer}.
               *
               * Requirements:
               *
               * - `to` cannot be the zero address.
               * - the caller must have a balance of at least `amount`.
               */
              function transfer(address to, uint256 amount) public virtual override returns (bool) {
                  address owner = _msgSender();
                  _transfer(owner, to, amount);
                  return true;
              }
              /**
               * @dev See {IERC20-allowance}.
               */
              function allowance(address owner, address spender) public view virtual override returns (uint256) {
                  return _allowances[owner][spender];
              }
              /**
               * @dev See {IERC20-approve}.
               *
               * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
               * `transferFrom`. This is semantically equivalent to an infinite approval.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function approve(address spender, uint256 amount) public virtual override returns (bool) {
                  address owner = _msgSender();
                  _approve(owner, spender, amount);
                  return true;
              }
              /**
               * @dev See {IERC20-transferFrom}.
               *
               * Emits an {Approval} event indicating the updated allowance. This is not
               * required by the EIP. See the note at the beginning of {ERC20}.
               *
               * NOTE: Does not update the allowance if the current allowance
               * is the maximum `uint256`.
               *
               * Requirements:
               *
               * - `from` and `to` cannot be the zero address.
               * - `from` must have a balance of at least `amount`.
               * - the caller must have allowance for ``from``'s tokens of at least
               * `amount`.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) public virtual override returns (bool) {
                  address spender = _msgSender();
                  _spendAllowance(from, spender, amount);
                  _transfer(from, to, amount);
                  return true;
              }
              /**
               * @dev Atomically increases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                  address owner = _msgSender();
                  _approve(owner, spender, allowance(owner, spender) + addedValue);
                  return true;
              }
              /**
               * @dev Atomically decreases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               * - `spender` must have allowance for the caller of at least
               * `subtractedValue`.
               */
              function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                  address owner = _msgSender();
                  uint256 currentAllowance = allowance(owner, spender);
                  require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                  unchecked {
                      _approve(owner, spender, currentAllowance - subtractedValue);
                  }
                  return true;
              }
              /**
               * @dev Moves `amount` of tokens from `from` to `to`.
               *
               * This internal function is equivalent to {transfer}, and can be used to
               * e.g. implement automatic token fees, slashing mechanisms, etc.
               *
               * Emits a {Transfer} event.
               *
               * Requirements:
               *
               * - `from` cannot be the zero address.
               * - `to` cannot be the zero address.
               * - `from` must have a balance of at least `amount`.
               */
              function _transfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {
                  require(from != address(0), "ERC20: transfer from the zero address");
                  require(to != address(0), "ERC20: transfer to the zero address");
                  _beforeTokenTransfer(from, to, amount);
                  uint256 fromBalance = _balances[from];
                  require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                  unchecked {
                      _balances[from] = fromBalance - amount;
                      // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                      // decrementing then incrementing.
                      _balances[to] += amount;
                  }
                  emit Transfer(from, to, amount);
                  _afterTokenTransfer(from, to, amount);
              }
              /** @dev Creates `amount` tokens and assigns them to `account`, increasing
               * the total supply.
               *
               * Emits a {Transfer} event with `from` set to the zero address.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               */
              function _mint(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: mint to the zero address");
                  _beforeTokenTransfer(address(0), account, amount);
                  _totalSupply += amount;
                  unchecked {
                      // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                      _balances[account] += amount;
                  }
                  emit Transfer(address(0), account, amount);
                  _afterTokenTransfer(address(0), account, amount);
              }
              /**
               * @dev Destroys `amount` tokens from `account`, reducing the
               * total supply.
               *
               * Emits a {Transfer} event with `to` set to the zero address.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               * - `account` must have at least `amount` tokens.
               */
              function _burn(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: burn from the zero address");
                  _beforeTokenTransfer(account, address(0), amount);
                  uint256 accountBalance = _balances[account];
                  require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                  unchecked {
                      _balances[account] = accountBalance - amount;
                      // Overflow not possible: amount <= accountBalance <= totalSupply.
                      _totalSupply -= amount;
                  }
                  emit Transfer(account, address(0), amount);
                  _afterTokenTransfer(account, address(0), amount);
              }
              /**
               * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
               *
               * This internal function is equivalent to `approve`, and can be used to
               * e.g. set automatic allowances for certain subsystems, etc.
               *
               * Emits an {Approval} event.
               *
               * Requirements:
               *
               * - `owner` cannot be the zero address.
               * - `spender` cannot be the zero address.
               */
              function _approve(
                  address owner,
                  address spender,
                  uint256 amount
              ) internal virtual {
                  require(owner != address(0), "ERC20: approve from the zero address");
                  require(spender != address(0), "ERC20: approve to the zero address");
                  _allowances[owner][spender] = amount;
                  emit Approval(owner, spender, amount);
              }
              /**
               * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
               *
               * Does not update the allowance amount in case of infinite allowance.
               * Revert if not enough allowance is available.
               *
               * Might emit an {Approval} event.
               */
              function _spendAllowance(
                  address owner,
                  address spender,
                  uint256 amount
              ) internal virtual {
                  uint256 currentAllowance = allowance(owner, spender);
                  if (currentAllowance != type(uint256).max) {
                      require(currentAllowance >= amount, "ERC20: insufficient allowance");
                      unchecked {
                          _approve(owner, spender, currentAllowance - amount);
                      }
                  }
              }
              /**
               * @dev Hook that is called before any transfer of tokens. This includes
               * minting and burning.
               *
               * Calling conditions:
               *
               * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
               * will be transferred to `to`.
               * - when `from` is zero, `amount` tokens will be minted for `to`.
               * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
               * - `from` and `to` are never both zero.
               *
               * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
               */
              function _beforeTokenTransfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {}
              /**
               * @dev Hook that is called after any transfer of tokens. This includes
               * minting and burning.
               *
               * Calling conditions:
               *
               * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
               * has been transferred to `to`.
               * - when `from` is zero, `amount` tokens have been minted for `to`.
               * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
               * - `from` and `to` are never both zero.
               *
               * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
               */
              function _afterTokenTransfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {}
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
          pragma solidity ^0.8.0;
          import "../IERC20.sol";
          /**
           * @dev Interface for the optional metadata functions from the ERC20 standard.
           *
           * _Available since v4.1._
           */
          interface IERC20Metadata is IERC20 {
              /**
               * @dev Returns the name of the token.
               */
              function name() external view returns (string memory);
              /**
               * @dev Returns the symbol of the token.
               */
              function symbol() external view returns (string memory);
              /**
               * @dev Returns the decimals places of the token.
               */
              function decimals() external view returns (uint8);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20 {
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
              /**
               * @dev Moves `amount` tokens from the caller's account to `to`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address to, uint256 amount) external returns (bool);
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
              /**
               * @dev Moves `amount` tokens from `from` to `to` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) external returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Provides information about the current execution context, including the
           * sender of the transaction and its data. While these are generally available
           * via msg.sender and msg.data, they should not be accessed in such a direct
           * manner, since when dealing with meta-transactions the account sending and
           * paying for execution may not be the actual sender (as far as an application
           * is concerned).
           *
           * This contract is only required for intermediate, library-like contracts.
           */
          abstract contract Context {
              function _msgSender() internal view virtual returns (address) {
                  return msg.sender;
              }
              function _msgData() internal view virtual returns (bytes calldata) {
                  return msg.data;
              }
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          interface IBasePolygonZkEVMGlobalExitRoot {
              /**
               * @dev Thrown when the caller is not the allowed contracts
               */
              error OnlyAllowedContracts();
              function updateExitRoot(bytes32 newRollupExitRoot) external;
              function globalExitRootMap(
                  bytes32 globalExitRootNum
              ) external returns (uint256);
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          /**
           * @dev Define interface for PolygonZkEVM Bridge message receiver
           */
          interface IBridgeMessageReceiver {
              function onMessageReceived(
                  address originAddress,
                  uint32 originNetwork,
                  bytes memory data
              ) external payable;
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          /**
           * @dev Contract helper responsible to manage the emergency state
           */
          contract EmergencyManager {
              /**
               * @dev Thrown when emergency state is active, and the function requires otherwise
               */
              error OnlyNotEmergencyState();
              /**
               * @dev Thrown when emergency state is not active, and the function requires otherwise
               */
              error OnlyEmergencyState();
              /**
               * @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.
               */
              uint256[10] private _gap;
              // Indicates whether the emergency state is active or not
              bool public isEmergencyState;
              /**
               * @dev Emitted when emergency state is activated
               */
              event EmergencyStateActivated();
              /**
               * @dev Emitted when emergency state is deactivated
               */
              event EmergencyStateDeactivated();
              /**
               * @notice Only allows a function to be callable if emergency state is unactive
               */
              modifier ifNotEmergencyState() {
                  if (isEmergencyState) {
                      revert OnlyNotEmergencyState();
                  }
                  _;
              }
              /**
               * @notice Only allows a function to be callable if emergency state is active
               */
              modifier ifEmergencyState() {
                  if (!isEmergencyState) {
                      revert OnlyEmergencyState();
                  }
                  _;
              }
              /**
               * @notice Activate emergency state
               */
              function _activateEmergencyState() internal virtual ifNotEmergencyState {
                  isEmergencyState = true;
                  emit EmergencyStateActivated();
              }
              /**
               * @notice Deactivate emergency state
               */
              function _deactivateEmergencyState() internal virtual ifEmergencyState {
                  isEmergencyState = false;
                  emit EmergencyStateDeactivated();
              }
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity 0.8.20;
          /**
           * @dev A library that provides the necessary calculations to calculate the global exit root
           */
          library GlobalExitRootLib {
              function calculateGlobalExitRoot(
                  bytes32 mainnetExitRoot,
                  bytes32 rollupExitRoot
              ) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked(mainnetExitRoot, rollupExitRoot));
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          // Implementation of permit based on https://github.com/WETH10/WETH10/blob/main/contracts/WETH10.sol
          pragma solidity 0.8.20;
          import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
          contract TokenWrapped is ERC20 {
              // Domain typehash
              bytes32 public constant DOMAIN_TYPEHASH =
                  keccak256(
                      "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                  );
              // Permit typehash
              bytes32 public constant PERMIT_TYPEHASH =
                  keccak256(
                      "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                  );
              // Version
              string public constant VERSION = "1";
              // Chain id on deployment
              uint256 public immutable deploymentChainId;
              // Domain separator calculated on deployment
              bytes32 private immutable _DEPLOYMENT_DOMAIN_SEPARATOR;
              // PolygonZkEVM Bridge address
              address public immutable bridgeAddress;
              // Decimals
              uint8 private immutable _decimals;
              // Permit nonces
              mapping(address => uint256) public nonces;
              modifier onlyBridge() {
                  require(
                      msg.sender == bridgeAddress,
                      "TokenWrapped::onlyBridge: Not PolygonZkEVMBridge"
                  );
                  _;
              }
              constructor(
                  string memory name,
                  string memory symbol,
                  uint8 __decimals
              ) ERC20(name, symbol) {
                  bridgeAddress = msg.sender;
                  _decimals = __decimals;
                  deploymentChainId = block.chainid;
                  _DEPLOYMENT_DOMAIN_SEPARATOR = _calculateDomainSeparator(block.chainid);
              }
              function mint(address to, uint256 value) external onlyBridge {
                  _mint(to, value);
              }
              // Notice that is not require to approve wrapped tokens to use the bridge
              function burn(address account, uint256 value) external onlyBridge {
                  _burn(account, value);
              }
              function decimals() public view virtual override returns (uint8) {
                  return _decimals;
              }
              // Permit relative functions
              function permit(
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) external {
                  require(
                      block.timestamp <= deadline,
                      "TokenWrapped::permit: Expired permit"
                  );
                  bytes32 hashStruct = keccak256(
                      abi.encode(
                          PERMIT_TYPEHASH,
                          owner,
                          spender,
                          value,
                          nonces[owner]++,
                          deadline
                      )
                  );
                  bytes32 digest = keccak256(
                      abi.encodePacked("\\x19\\x01", DOMAIN_SEPARATOR(), hashStruct)
                  );
                  address signer = ecrecover(digest, v, r, s);
                  require(
                      signer != address(0) && signer == owner,
                      "TokenWrapped::permit: Invalid signature"
                  );
                  _approve(owner, spender, value);
              }
              /**
               * @notice Calculate domain separator, given a chainID.
               * @param chainId Current chainID
               */
              function _calculateDomainSeparator(
                  uint256 chainId
              ) private view returns (bytes32) {
                  return
                      keccak256(
                          abi.encode(
                              DOMAIN_TYPEHASH,
                              keccak256(bytes(name())),
                              keccak256(bytes(VERSION)),
                              chainId,
                              address(this)
                          )
                      );
              }
              /// @dev Return the DOMAIN_SEPARATOR.
              function DOMAIN_SEPARATOR() public view returns (bytes32) {
                  return
                      block.chainid == deploymentChainId
                          ? _DEPLOYMENT_DOMAIN_SEPARATOR
                          : _calculateDomainSeparator(block.chainid);
              }
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          import "../../interfaces/IBasePolygonZkEVMGlobalExitRoot.sol";
          interface IPolygonZkEVMBridgeV2 {
              /**
               * @dev Thrown when the destination network is invalid
               */
              error DestinationNetworkInvalid();
              /**
               * @dev Thrown when the amount does not match msg.value
               */
              error AmountDoesNotMatchMsgValue();
              /**
               * @dev Thrown when user is bridging tokens and is also sending a value
               */
              error MsgValueNotZero();
              /**
               * @dev Thrown when the Ether transfer on claimAsset fails
               */
              error EtherTransferFailed();
              /**
               * @dev Thrown when the message transaction on claimMessage fails
               */
              error MessageFailed();
              /**
               * @dev Thrown when the global exit root does not exist
               */
              error GlobalExitRootInvalid();
              /**
               * @dev Thrown when the smt proof does not match
               */
              error InvalidSmtProof();
              /**
               * @dev Thrown when an index is already claimed
               */
              error AlreadyClaimed();
              /**
               * @dev Thrown when the owner of permit does not match the sender
               */
              error NotValidOwner();
              /**
               * @dev Thrown when the spender of the permit does not match this contract address
               */
              error NotValidSpender();
              /**
               * @dev Thrown when the amount of the permit does not match
               */
              error NotValidAmount();
              /**
               * @dev Thrown when the permit data contains an invalid signature
               */
              error NotValidSignature();
              /**
               * @dev Thrown when sender is not the rollup manager
               */
              error OnlyRollupManager();
              /**
               * @dev Thrown when the permit data contains an invalid signature
               */
              error NativeTokenIsEther();
              /**
               * @dev Thrown when the permit data contains an invalid signature
               */
              error NoValueInMessagesOnGasTokenNetworks();
              /**
               * @dev Thrown when the permit data contains an invalid signature
               */
              error GasTokenNetworkMustBeZeroOnEther();
              /**
               * @dev Thrown when the wrapped token deployment fails
               */
              error FailedTokenWrappedDeployment();
              function wrappedTokenToTokenInfo(
                  address destinationAddress
              ) external view returns (uint32, address);
              function updateGlobalExitRoot() external;
              function activateEmergencyState() external;
              function deactivateEmergencyState() external;
              function bridgeAsset(
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  address token,
                  bool forceUpdateGlobalExitRoot,
                  bytes calldata permitData
              ) external payable;
              function bridgeMessage(
                  uint32 destinationNetwork,
                  address destinationAddress,
                  bool forceUpdateGlobalExitRoot,
                  bytes calldata metadata
              ) external payable;
              function bridgeMessageWETH(
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amountWETH,
                  bool forceUpdateGlobalExitRoot,
                  bytes calldata metadata
              ) external;
              function claimAsset(
                  bytes32[32] calldata smtProofLocalExitRoot,
                  bytes32[32] calldata smtProofRollupExitRoot,
                  uint256 globalIndex,
                  bytes32 mainnetExitRoot,
                  bytes32 rollupExitRoot,
                  uint32 originNetwork,
                  address originTokenAddress,
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  bytes calldata metadata
              ) external;
              function claimMessage(
                  bytes32[32] calldata smtProofLocalExitRoot,
                  bytes32[32] calldata smtProofRollupExitRoot,
                  uint256 globalIndex,
                  bytes32 mainnetExitRoot,
                  bytes32 rollupExitRoot,
                  uint32 originNetwork,
                  address originAddress,
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  bytes calldata metadata
              ) external;
              function initialize(
                  uint32 _networkID,
                  address _gasTokenAddress,
                  uint32 _gasTokenNetwork,
                  IBasePolygonZkEVMGlobalExitRoot _globalExitRootManager,
                  address _polygonRollupManager,
                  bytes memory _gasTokenMetadata
              ) external;
              function getTokenMetadata(
                  address token
              ) external view returns (bytes memory);
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          /**
           * This contract will be used as a helper for all the sparse merkle tree related functions
           * Based on the implementation of the deposit eth2.0 contract https://github.com/ethereum/consensus-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol
           */
          contract DepositContractBase {
              /**
               * @dev Thrown when the merkle tree is full
               */
              error MerkleTreeFull();
              // Merkle tree levels
              uint256 internal constant _DEPOSIT_CONTRACT_TREE_DEPTH = 32;
              // This ensures `depositCount` will fit into 32-bits
              uint256 internal constant _MAX_DEPOSIT_COUNT =
                  2 ** _DEPOSIT_CONTRACT_TREE_DEPTH - 1;
              // Branch array which contains the necessary sibilings to compute the next root when a new
              // leaf is inserted
              bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] internal _branch;
              // Counter of current deposits
              uint256 public depositCount;
              /**
               * @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.
               */
              uint256[10] private _gap;
              /**
               * @notice Computes and returns the merkle root
               */
              function getRoot() public view virtual returns (bytes32) {
                  bytes32 node;
                  uint256 size = depositCount;
                  bytes32 currentZeroHashHeight = 0;
                  for (
                      uint256 height = 0;
                      height < _DEPOSIT_CONTRACT_TREE_DEPTH;
                      height++
                  ) {
                      if (((size >> height) & 1) == 1)
                          node = keccak256(abi.encodePacked(_branch[height], node));
                      else
                          node = keccak256(abi.encodePacked(node, currentZeroHashHeight));
                      currentZeroHashHeight = keccak256(
                          abi.encodePacked(currentZeroHashHeight, currentZeroHashHeight)
                      );
                  }
                  return node;
              }
              /**
               * @notice Add a new leaf to the merkle tree
               * @param leaf Leaf
               */
              function _addLeaf(bytes32 leaf) internal {
                  bytes32 node = leaf;
                  // Avoid overflowing the Merkle tree (and prevent edge case in computing `_branch`)
                  if (depositCount >= _MAX_DEPOSIT_COUNT) {
                      revert MerkleTreeFull();
                  }
                  // Add deposit data root to Merkle tree (update a single `_branch` node)
                  uint256 size = ++depositCount;
                  for (
                      uint256 height = 0;
                      height < _DEPOSIT_CONTRACT_TREE_DEPTH;
                      height++
                  ) {
                      if (((size >> height) & 1) == 1) {
                          _branch[height] = node;
                          return;
                      }
                      node = keccak256(abi.encodePacked(_branch[height], node));
                  }
                  // As the loop should always end prematurely with the `return` statement,
                  // this code should be unreachable. We assert `false` just to be safe.
                  assert(false);
              }
              /**
               * @notice Verify merkle proof
               * @param leafHash Leaf hash
               * @param smtProof Smt proof
               * @param index Index of the leaf
               * @param root Merkle root
               */
              function verifyMerkleProof(
                  bytes32 leafHash,
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProof,
                  uint32 index,
                  bytes32 root
              ) public pure returns (bool) {
                  return calculateRoot(leafHash, smtProof, index) == root;
              }
              /**
               * @notice Calculate root from merkle proof
               * @param leafHash Leaf hash
               * @param smtProof Smt proof
               * @param index Index of the leaf
               */
              function calculateRoot(
                  bytes32 leafHash,
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProof,
                  uint32 index
              ) public pure returns (bytes32) {
                  bytes32 node = leafHash;
                  // Compute root
                  for (
                      uint256 height = 0;
                      height < _DEPOSIT_CONTRACT_TREE_DEPTH;
                      height++
                  ) {
                      if (((index >> height) & 1) == 1)
                          node = keccak256(abi.encodePacked(smtProof[height], node));
                      else node = keccak256(abi.encodePacked(node, smtProof[height]));
                  }
                  return node;
              }
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
          import "./DepositContractBase.sol";
          /**
           * This contract will be used in the PolygonZkEVMBridge contract, it inherits the DepositContractBase and adds the logic
           * to calculate the leaf of the tree
           */
          contract DepositContractV2 is ReentrancyGuardUpgradeable, DepositContractBase {
              /**
               * @notice Given the leaf data returns the leaf value
               * @param leafType Leaf type -->  [0] transfer Ether / ERC20 tokens, [1] message
               * @param originNetwork Origin Network
               * @param originAddress [0] Origin token address, 0 address is reserved for ether, [1] msg.sender of the message
               * @param destinationNetwork Destination network
               * @param destinationAddress Destination address
               * @param amount [0] Amount of tokens/ether, [1] Amount of ether
               * @param metadataHash Hash of the metadata
               */
              function getLeafValue(
                  uint8 leafType,
                  uint32 originNetwork,
                  address originAddress,
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  bytes32 metadataHash
              ) public pure returns (bytes32) {
                  return
                      keccak256(
                          abi.encodePacked(
                              leafType,
                              originNetwork,
                              originAddress,
                              destinationNetwork,
                              destinationAddress,
                              amount,
                              metadataHash
                          )
                      );
              }
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity 0.8.20;
          import "./lib/DepositContractV2.sol";
          import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
          import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
          import "../lib/TokenWrapped.sol";
          import "../interfaces/IBasePolygonZkEVMGlobalExitRoot.sol";
          import "../interfaces/IBridgeMessageReceiver.sol";
          import "./interfaces/IPolygonZkEVMBridgeV2.sol";
          import "../lib/EmergencyManager.sol";
          import "../lib/GlobalExitRootLib.sol";
          /**
           * PolygonZkEVMBridge that will be deployed on Ethereum and all Polygon rollups
           * Contract responsible to manage the token interactions with other networks
           */
          contract PolygonZkEVMBridgeV2 is
              DepositContractV2,
              EmergencyManager,
              IPolygonZkEVMBridgeV2
          {
              using SafeERC20Upgradeable for IERC20Upgradeable;
              // Wrapped Token information struct
              struct TokenInformation {
                  uint32 originNetwork;
                  address originTokenAddress;
              }
              // bytes4(keccak256(bytes("permit(address,address,uint256,uint256,uint8,bytes32,bytes32)")));
              bytes4 private constant _PERMIT_SIGNATURE = 0xd505accf;
              // bytes4(keccak256(bytes("permit(address,address,uint256,uint256,bool,uint8,bytes32,bytes32)")));
              bytes4 private constant _PERMIT_SIGNATURE_DAI = 0x8fcbaf0c;
              // Mainnet identifier
              uint32 private constant _MAINNET_NETWORK_ID = 0;
              // ZkEVM identifier
              uint32 private constant _ZKEVM_NETWORK_ID = 1;
              // Leaf type asset
              uint8 private constant _LEAF_TYPE_ASSET = 0;
              // Leaf type message
              uint8 private constant _LEAF_TYPE_MESSAGE = 1;
              // Nullifier offset
              uint256 private constant _MAX_LEAFS_PER_NETWORK = 2 ** 32;
              // Indicate where's the mainnet flag bit in the global index
              uint256 private constant _GLOBAL_INDEX_MAINNET_FLAG = 2 ** 64;
              // Init code of the erc20 wrapped token, to deploy a wrapped token the constructor parameters must be appended
              bytes public constant BASE_INIT_BYTECODE_WRAPPED_TOKEN =
                  hex"6101006040523480156200001257600080fd5b5060405162001b6638038062001b6683398101604081905262000035916200028d565b82826003620000458382620003a1565b506004620000548282620003a1565b50503360c0525060ff811660e052466080819052620000739062000080565b60a052506200046d915050565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f620000ad6200012e565b805160209182012060408051808201825260018152603160f81b90840152805192830193909352918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc66060820152608081018390523060a082015260c001604051602081830303815290604052805190602001209050919050565b6060600380546200013f9062000312565b80601f01602080910402602001604051908101604052809291908181526020018280546200016d9062000312565b8015620001be5780601f106200019257610100808354040283529160200191620001be565b820191906000526020600020905b815481529060010190602001808311620001a057829003601f168201915b5050505050905090565b634e487b7160e01b600052604160045260246000fd5b600082601f830112620001f057600080fd5b81516001600160401b03808211156200020d576200020d620001c8565b604051601f8301601f19908116603f01168101908282118183101715620002385762000238620001c8565b816040528381526020925086838588010111156200025557600080fd5b600091505b838210156200027957858201830151818301840152908201906200025a565b600093810190920192909252949350505050565b600080600060608486031215620002a357600080fd5b83516001600160401b0380821115620002bb57600080fd5b620002c987838801620001de565b94506020860151915080821115620002e057600080fd5b50620002ef86828701620001de565b925050604084015160ff811681146200030757600080fd5b809150509250925092565b600181811c908216806200032757607f821691505b6020821081036200034857634e487b7160e01b600052602260045260246000fd5b50919050565b601f8211156200039c57600081815260208120601f850160051c81016020861015620003775750805b601f850160051c820191505b81811015620003985782815560010162000383565b5050505b505050565b81516001600160401b03811115620003bd57620003bd620001c8565b620003d581620003ce845462000312565b846200034e565b602080601f8311600181146200040d5760008415620003f45750858301515b600019600386901b1c1916600185901b17855562000398565b600085815260208120601f198616915b828110156200043e578886015182559484019460019091019084016200041d565b50858210156200045d5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60805160a05160c05160e0516116aa620004bc6000396000610237015260008181610307015281816105c001526106a70152600061053a015260008181610379015261050401526116aa6000f3fe608060405234801561001057600080fd5b50600436106101775760003560e01c806370a08231116100d8578063a457c2d71161008c578063d505accf11610066578063d505accf1461039b578063dd62ed3e146103ae578063ffa1ad74146103f457600080fd5b8063a457c2d71461034e578063a9059cbb14610361578063cd0d00961461037457600080fd5b806395d89b41116100bd57806395d89b41146102e75780639dc29fac146102ef578063a3c573eb1461030257600080fd5b806370a08231146102915780637ecebe00146102c757600080fd5b806330adf81f1161012f5780633644e515116101145780633644e51514610261578063395093511461026957806340c10f191461027c57600080fd5b806330adf81f14610209578063313ce5671461023057600080fd5b806318160ddd1161016057806318160ddd146101bd57806320606b70146101cf57806323b872dd146101f657600080fd5b806306fdde031461017c578063095ea7b31461019a575b600080fd5b610184610430565b60405161019191906113e4565b60405180910390f35b6101ad6101a8366004611479565b6104c2565b6040519015158152602001610191565b6002545b604051908152602001610191565b6101c17f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f81565b6101ad6102043660046114a3565b6104dc565b6101c17f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b60405160ff7f0000000000000000000000000000000000000000000000000000000000000000168152602001610191565b6101c1610500565b6101ad610277366004611479565b61055c565b61028f61028a366004611479565b6105a8565b005b6101c161029f3660046114df565b73ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090205490565b6101c16102d53660046114df565b60056020526000908152604090205481565b610184610680565b61028f6102fd366004611479565b61068f565b6103297f000000000000000000000000000000000000000000000000000000000000000081565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610191565b6101ad61035c366004611479565b61075e565b6101ad61036f366004611479565b61082f565b6101c17f000000000000000000000000000000000000000000000000000000000000000081565b61028f6103a9366004611501565b61083d565b6101c16103bc366004611574565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260016020908152604080832093909416825291909152205490565b6101846040518060400160405280600181526020017f310000000000000000000000000000000000000000000000000000000000000081525081565b60606003805461043f906115a7565b80601f016020809104026020016040519081016040528092919081815260200182805461046b906115a7565b80156104b85780601f1061048d576101008083540402835291602001916104b8565b820191906000526020600020905b81548152906001019060200180831161049b57829003601f168201915b5050505050905090565b6000336104d0818585610b73565b60019150505b92915050565b6000336104ea858285610d27565b6104f5858585610dfe565b506001949350505050565b60007f00000000000000000000000000000000000000000000000000000000000000004614610537576105324661106d565b905090565b507f000000000000000000000000000000000000000000000000000000000000000090565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff871684529091528120549091906104d090829086906105a3908790611629565b610b73565b3373ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001614610672576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603060248201527f546f6b656e577261707065643a3a6f6e6c794272696467653a204e6f7420506f60448201527f6c79676f6e5a6b45564d4272696467650000000000000000000000000000000060648201526084015b60405180910390fd5b61067c8282611135565b5050565b60606004805461043f906115a7565b3373ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001614610754576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603060248201527f546f6b656e577261707065643a3a6f6e6c794272696467653a204e6f7420506f60448201527f6c79676f6e5a6b45564d427269646765000000000000000000000000000000006064820152608401610669565b61067c8282611228565b33600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8716845290915281205490919083811015610822576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760448201527f207a65726f0000000000000000000000000000000000000000000000000000006064820152608401610669565b6104f58286868403610b73565b6000336104d0818585610dfe565b834211156108cc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152602060048201526024808201527f546f6b656e577261707065643a3a7065726d69743a204578706972656420706560448201527f726d6974000000000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff8716600090815260056020526040812080547f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9918a918a918a9190866109268361163c565b9091555060408051602081019690965273ffffffffffffffffffffffffffffffffffffffff94851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090506000610991610500565b6040517f19010000000000000000000000000000000000000000000000000000000000006020820152602281019190915260428101839052606201604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181528282528051602091820120600080855291840180845281905260ff89169284019290925260608301879052608083018690529092509060019060a0016020604051602081039080840390855afa158015610a55573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff811615801590610ad057508973ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16145b610b5c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602760248201527f546f6b656e577261707065643a3a7065726d69743a20496e76616c696420736960448201527f676e6174757265000000000000000000000000000000000000000000000000006064820152608401610669565b610b678a8a8a610b73565b50505050505050505050565b73ffffffffffffffffffffffffffffffffffffffff8316610c15576040517f08c379a0000000000000000000000000000000000000000000000000000000008152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f72657373000000000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff8216610cb8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f73730000000000000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b73ffffffffffffffffffffffffffffffffffffffff8381166000908152600160209081526040808320938616835292905220547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114610df85781811015610deb576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610669565b610df88484848403610b73565b50505050565b73ffffffffffffffffffffffffffffffffffffffff8316610ea1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f64726573730000000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff8216610f44576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f65737300000000000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff831660009081526020819052604090205481811015610ffa576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e636500000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3610df8565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f611098610430565b8051602091820120604080518082018252600181527f310000000000000000000000000000000000000000000000000000000000000090840152805192830193909352918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc66060820152608081018390523060a082015260c001604051602081830303815290604052805190602001209050919050565b73ffffffffffffffffffffffffffffffffffffffff82166111b2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610669565b80600260008282546111c49190611629565b909155505073ffffffffffffffffffffffffffffffffffffffff8216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050565b73ffffffffffffffffffffffffffffffffffffffff82166112cb576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f73000000000000000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff821660009081526020819052604090205481811015611381576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f63650000000000000000000000000000000000000000000000000000000000006064820152608401610669565b73ffffffffffffffffffffffffffffffffffffffff83166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9101610d1a565b600060208083528351808285015260005b81811015611411578581018301518582016040015282016113f5565b5060006040828601015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8301168501019250505092915050565b803573ffffffffffffffffffffffffffffffffffffffff8116811461147457600080fd5b919050565b6000806040838503121561148c57600080fd5b61149583611450565b946020939093013593505050565b6000806000606084860312156114b857600080fd5b6114c184611450565b92506114cf60208501611450565b9150604084013590509250925092565b6000602082840312156114f157600080fd5b6114fa82611450565b9392505050565b600080600080600080600060e0888a03121561151c57600080fd5b61152588611450565b965061153360208901611450565b95506040880135945060608801359350608088013560ff8116811461155757600080fd5b9699959850939692959460a0840135945060c09093013592915050565b6000806040838503121561158757600080fd5b61159083611450565b915061159e60208401611450565b90509250929050565b600181811c908216806115bb57607f821691505b6020821081036115f4577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b808201808211156104d6576104d66115fa565b60007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361166d5761166d6115fa565b506001019056fea26469706673582212208d88fee561cff7120d381c345cfc534cef8229a272dc5809d4bbb685ad67141164736f6c63430008110033";
              // Network identifier
              uint32 public networkID;
              // Global Exit Root address
              IBasePolygonZkEVMGlobalExitRoot public globalExitRootManager;
              // Last updated deposit count to the global exit root manager
              uint32 public lastUpdatedDepositCount;
              // Leaf index --> claimed bit map
              mapping(uint256 => uint256) public claimedBitMap;
              // keccak256(OriginNetwork || tokenAddress) --> Wrapped token address
              mapping(bytes32 => address) public tokenInfoToWrappedToken;
              // Wrapped token Address --> Origin token information
              mapping(address => TokenInformation) public wrappedTokenToTokenInfo;
              // Rollup manager address, previously PolygonZkEVM
              /// @custom:oz-renamed-from polygonZkEVMaddress
              address public polygonRollupManager;
              // Native address
              address public gasTokenAddress;
              // Native address
              uint32 public gasTokenNetwork;
              // Gas token metadata
              bytes public gasTokenMetadata;
              // WETH address
              TokenWrapped public WETHToken;
              /**
               * @dev Emitted when bridge assets or messages to another network
               */
              event BridgeEvent(
                  uint8 leafType,
                  uint32 originNetwork,
                  address originAddress,
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  bytes metadata,
                  uint32 depositCount
              );
              /**
               * @dev Emitted when a claim is done from another network
               */
              event ClaimEvent(
                  uint256 globalIndex,
                  uint32 originNetwork,
                  address originAddress,
                  address destinationAddress,
                  uint256 amount
              );
              /**
               * @dev Emitted when a new wrapped token is created
               */
              event NewWrappedToken(
                  uint32 originNetwork,
                  address originTokenAddress,
                  address wrappedTokenAddress,
                  bytes metadata
              );
              /**
               * Disable initalizers on the implementation following the best practices
               */
              constructor() {
                  _disableInitializers();
              }
              /**
               * @param _networkID networkID
               * @param _gasTokenAddress gas token address
               * @param _gasTokenNetwork gas token network
               * @param _globalExitRootManager global exit root manager address
               * @param _polygonRollupManager polygonZkEVM address
               * @notice The value of `_polygonRollupManager` on the L2 deployment of the contract will be address(0), so
               * emergency state is not possible for the L2 deployment of the bridge, intentionally
               * @param _gasTokenMetadata Abi encoded gas token metadata
               */
              function initialize(
                  uint32 _networkID,
                  address _gasTokenAddress,
                  uint32 _gasTokenNetwork,
                  IBasePolygonZkEVMGlobalExitRoot _globalExitRootManager,
                  address _polygonRollupManager,
                  bytes memory _gasTokenMetadata
              ) external virtual initializer {
                  networkID = _networkID;
                  globalExitRootManager = _globalExitRootManager;
                  polygonRollupManager = _polygonRollupManager;
                  // Set gas token
                  if (_gasTokenAddress == address(0)) {
                      // Gas token will be ether
                      if (_gasTokenNetwork != 0) {
                          revert GasTokenNetworkMustBeZeroOnEther();
                      }
                      // WETHToken, gasTokenAddress and gasTokenNetwork will be 0
                      // gasTokenMetadata will be empty
                  } else {
                      // Gas token will be an erc20
                      gasTokenAddress = _gasTokenAddress;
                      gasTokenNetwork = _gasTokenNetwork;
                      gasTokenMetadata = _gasTokenMetadata;
                      // Create a wrapped token for WETH, with salt == 0
                      WETHToken = _deployWrappedToken(
                          0, // salt
                          abi.encode("Wrapped Ether", "WETH", 18)
                      );
                  }
                  // Initialize OZ contracts
                  __ReentrancyGuard_init();
              }
              modifier onlyRollupManager() {
                  if (polygonRollupManager != msg.sender) {
                      revert OnlyRollupManager();
                  }
                  _;
              }
              /**
               * @notice Deposit add a new leaf to the merkle tree
               * note If this function is called with a reentrant token, it would be possible to `claimTokens` in the same call
               * Reducing the supply of tokens on this contract, and actually locking tokens in the contract.
               * Therefore we recommend to third parties bridges that if they do implement reentrant call of `beforeTransfer` of some reentrant tokens
               * do not call any external address in that case
               * note User/UI must be aware of the existing/available networks when choosing the destination network
               * @param destinationNetwork Network destination
               * @param destinationAddress Address destination
               * @param amount Amount of tokens
               * @param token Token address, 0 address is reserved for ether
               * @param forceUpdateGlobalExitRoot Indicates if the new global exit root is updated or not
               * @param permitData Raw data of the call `permit` of the token
               */
              function bridgeAsset(
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  address token,
                  bool forceUpdateGlobalExitRoot,
                  bytes calldata permitData
              ) public payable virtual ifNotEmergencyState nonReentrant {
                  if (destinationNetwork == networkID) {
                      revert DestinationNetworkInvalid();
                  }
                  address originTokenAddress;
                  uint32 originNetwork;
                  bytes memory metadata;
                  uint256 leafAmount = amount;
                  if (token == address(0)) {
                      // Check gas token transfer
                      if (msg.value != amount) {
                          revert AmountDoesNotMatchMsgValue();
                      }
                      // Set gas token parameters
                      originNetwork = gasTokenNetwork;
                      originTokenAddress = gasTokenAddress;
                      metadata = gasTokenMetadata;
                  } else {
                      // Check msg.value is 0 if tokens are bridged
                      if (msg.value != 0) {
                          revert MsgValueNotZero();
                      }
                      // Check if it's WETH, this only applies on L2 networks with gasTokens
                      // In case ether is the native token, WETHToken will be 0, and the address 0 is already checked
                      if (token == address(WETHToken)) {
                          // Burn tokens
                          TokenWrapped(token).burn(msg.sender, amount);
                          // Both origin network and originTokenAddress will be 0
                          // Metadata will be empty
                      } else {
                          TokenInformation memory tokenInfo = wrappedTokenToTokenInfo[
                              token
                          ];
                          if (tokenInfo.originTokenAddress != address(0)) {
                              // The token is a wrapped token from another network
                              // Burn tokens
                              TokenWrapped(token).burn(msg.sender, amount);
                              originTokenAddress = tokenInfo.originTokenAddress;
                              originNetwork = tokenInfo.originNetwork;
                          } else {
                              // Use permit if any
                              if (permitData.length != 0) {
                                  _permit(token, amount, permitData);
                              }
                              // In order to support fee tokens check the amount received, not the transferred
                              uint256 balanceBefore = IERC20Upgradeable(token).balanceOf(
                                  address(this)
                              );
                              IERC20Upgradeable(token).safeTransferFrom(
                                  msg.sender,
                                  address(this),
                                  amount
                              );
                              uint256 balanceAfter = IERC20Upgradeable(token).balanceOf(
                                  address(this)
                              );
                              // Override leafAmount with the received amount
                              leafAmount = balanceAfter - balanceBefore;
                              originTokenAddress = token;
                              originNetwork = networkID;
                          }
                          // Encode metadata
                          metadata = getTokenMetadata(token);
                      }
                  }
                  emit BridgeEvent(
                      _LEAF_TYPE_ASSET,
                      originNetwork,
                      originTokenAddress,
                      destinationNetwork,
                      destinationAddress,
                      leafAmount,
                      metadata,
                      uint32(depositCount)
                  );
                  _addLeaf(
                      getLeafValue(
                          _LEAF_TYPE_ASSET,
                          originNetwork,
                          originTokenAddress,
                          destinationNetwork,
                          destinationAddress,
                          leafAmount,
                          keccak256(metadata)
                      )
                  );
                  // Update the new root to the global exit root manager if set by the user
                  if (forceUpdateGlobalExitRoot) {
                      _updateGlobalExitRoot();
                  }
              }
              /**
               * @notice Bridge message and send ETH value
               * note User/UI must be aware of the existing/available networks when choosing the destination network
               * @param destinationNetwork Network destination
               * @param destinationAddress Address destination
               * @param forceUpdateGlobalExitRoot Indicates if the new global exit root is updated or not
               * @param metadata Message metadata
               */
              function bridgeMessage(
                  uint32 destinationNetwork,
                  address destinationAddress,
                  bool forceUpdateGlobalExitRoot,
                  bytes calldata metadata
              ) external payable ifNotEmergencyState {
                  // If exist a gas token, only allow call this function without value
                  if (msg.value != 0 && address(WETHToken) != address(0)) {
                      revert NoValueInMessagesOnGasTokenNetworks();
                  }
                  _bridgeMessage(
                      destinationNetwork,
                      destinationAddress,
                      msg.value,
                      forceUpdateGlobalExitRoot,
                      metadata
                  );
              }
              /**
               * @notice Bridge message and send ETH value
               * note User/UI must be aware of the existing/available networks when choosing the destination network
               * @param destinationNetwork Network destination
               * @param destinationAddress Address destination
               * @param amountWETH Amount of WETH tokens
               * @param forceUpdateGlobalExitRoot Indicates if the new global exit root is updated or not
               * @param metadata Message metadata
               */
              function bridgeMessageWETH(
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amountWETH,
                  bool forceUpdateGlobalExitRoot,
                  bytes calldata metadata
              ) external ifNotEmergencyState {
                  // If native token is ether, disable this function
                  if (address(WETHToken) == address(0)) {
                      revert NativeTokenIsEther();
                  }
                  // Burn wETH tokens
                  WETHToken.burn(msg.sender, amountWETH);
                  _bridgeMessage(
                      destinationNetwork,
                      destinationAddress,
                      amountWETH,
                      forceUpdateGlobalExitRoot,
                      metadata
                  );
              }
              /**
               * @notice Bridge message and send ETH value
               * @param destinationNetwork Network destination
               * @param destinationAddress Address destination
               * @param amountEther Amount of ether along with the message
               * @param forceUpdateGlobalExitRoot Indicates if the new global exit root is updated or not
               * @param metadata Message metadata
               */
              function _bridgeMessage(
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amountEther,
                  bool forceUpdateGlobalExitRoot,
                  bytes calldata metadata
              ) internal {
                  if (destinationNetwork == networkID) {
                      revert DestinationNetworkInvalid();
                  }
                  emit BridgeEvent(
                      _LEAF_TYPE_MESSAGE,
                      networkID,
                      msg.sender,
                      destinationNetwork,
                      destinationAddress,
                      amountEther,
                      metadata,
                      uint32(depositCount)
                  );
                  _addLeaf(
                      getLeafValue(
                          _LEAF_TYPE_MESSAGE,
                          networkID,
                          msg.sender,
                          destinationNetwork,
                          destinationAddress,
                          amountEther,
                          keccak256(metadata)
                      )
                  );
                  // Update the new root to the global exit root manager if set by the user
                  if (forceUpdateGlobalExitRoot) {
                      _updateGlobalExitRoot();
                  }
              }
              /**
               * @notice Verify merkle proof and withdraw tokens/ether
               * @param smtProofLocalExitRoot Smt proof to proof the leaf against the network exit root
               * @param smtProofRollupExitRoot Smt proof to proof the rollupLocalExitRoot against the rollups exit root
               * @param globalIndex Global index is defined as:
               * | 191 bits |    1 bit     |   32 bits   |     32 bits    |
               * |    0     |  mainnetFlag | rollupIndex | localRootIndex |
               * note that only the rollup index will be used only in case the mainnet flag is 0
               * note that global index do not assert the unused bits to 0.
               * This means that when synching the events, the globalIndex must be decoded the same way that in the Smart contract
               * to avoid possible synch attacks
               * @param mainnetExitRoot Mainnet exit root
               * @param rollupExitRoot Rollup exit root
               * @param originNetwork Origin network
               * @param originTokenAddress  Origin token address, 0 address is reserved for ether
               * @param destinationNetwork Network destination
               * @param destinationAddress Address destination
               * @param amount Amount of tokens
               * @param metadata Abi encoded metadata if any, empty otherwise
               */
              function claimAsset(
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofLocalExitRoot,
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofRollupExitRoot,
                  uint256 globalIndex,
                  bytes32 mainnetExitRoot,
                  bytes32 rollupExitRoot,
                  uint32 originNetwork,
                  address originTokenAddress,
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  bytes calldata metadata
              ) external ifNotEmergencyState {
                  // Destination network must be this networkID
                  if (destinationNetwork != networkID) {
                      revert DestinationNetworkInvalid();
                  }
                  // Verify leaf exist and it does not have been claimed
                  _verifyLeaf(
                      smtProofLocalExitRoot,
                      smtProofRollupExitRoot,
                      globalIndex,
                      mainnetExitRoot,
                      rollupExitRoot,
                      getLeafValue(
                          _LEAF_TYPE_ASSET,
                          originNetwork,
                          originTokenAddress,
                          destinationNetwork,
                          destinationAddress,
                          amount,
                          keccak256(metadata)
                      )
                  );
                  // Transfer funds
                  if (originTokenAddress == address(0)) {
                      if (address(WETHToken) == address(0)) {
                          // Ether is the native token
                          /* solhint-disable avoid-low-level-calls */
                          (bool success, ) = destinationAddress.call{value: amount}(
                              new bytes(0)
                          );
                          if (!success) {
                              revert EtherTransferFailed();
                          }
                      } else {
                          // Claim wETH
                          WETHToken.mint(destinationAddress, amount);
                      }
                  } else {
                      // Check if it's gas token
                      if (
                          originTokenAddress == gasTokenAddress &&
                          gasTokenNetwork == originNetwork
                      ) {
                          // Transfer gas token
                          /* solhint-disable avoid-low-level-calls */
                          (bool success, ) = destinationAddress.call{value: amount}(
                              new bytes(0)
                          );
                          if (!success) {
                              revert EtherTransferFailed();
                          }
                      } else {
                          // Transfer tokens
                          if (originNetwork == networkID) {
                              // The token is an ERC20 from this network
                              IERC20Upgradeable(originTokenAddress).safeTransfer(
                                  destinationAddress,
                                  amount
                              );
                          } else {
                              // The tokens is not from this network
                              // Create a wrapper for the token if not exist yet
                              bytes32 tokenInfoHash = keccak256(
                                  abi.encodePacked(originNetwork, originTokenAddress)
                              );
                              address wrappedToken = tokenInfoToWrappedToken[
                                  tokenInfoHash
                              ];
                              if (wrappedToken == address(0)) {
                                  // Get ERC20 metadata
                                  // Create a new wrapped erc20 using create2
                                  TokenWrapped newWrappedToken = _deployWrappedToken(
                                      tokenInfoHash,
                                      metadata
                                  );
                                  // Mint tokens for the destination address
                                  newWrappedToken.mint(destinationAddress, amount);
                                  // Create mappings
                                  tokenInfoToWrappedToken[tokenInfoHash] = address(
                                      newWrappedToken
                                  );
                                  wrappedTokenToTokenInfo[
                                      address(newWrappedToken)
                                  ] = TokenInformation(originNetwork, originTokenAddress);
                                  emit NewWrappedToken(
                                      originNetwork,
                                      originTokenAddress,
                                      address(newWrappedToken),
                                      metadata
                                  );
                              } else {
                                  // Use the existing wrapped erc20
                                  TokenWrapped(wrappedToken).mint(
                                      destinationAddress,
                                      amount
                                  );
                              }
                          }
                      }
                  }
                  emit ClaimEvent(
                      globalIndex,
                      originNetwork,
                      originTokenAddress,
                      destinationAddress,
                      amount
                  );
              }
              /**
               * @notice Verify merkle proof and execute message
               * If the receiving address is an EOA, the call will result as a success
               * Which means that the amount of ether will be transferred correctly, but the message
               * will not trigger any execution
               * @param smtProofLocalExitRoot Smt proof to proof the leaf against the exit root
               * @param smtProofRollupExitRoot Smt proof to proof the rollupLocalExitRoot against the rollups exit root
               * @param globalIndex Global index is defined as:
               * | 191 bits |    1 bit     |   32 bits   |     32 bits    |
               * |    0     |  mainnetFlag | rollupIndex | localRootIndex |
               * note that only the rollup index will be used only in case the mainnet flag is 0
               * note that global index do not assert the unused bits to 0.
               * This means that when synching the events, the globalIndex must be decoded the same way that in the Smart contract
               * to avoid possible synch attacks
               * @param mainnetExitRoot Mainnet exit root
               * @param rollupExitRoot Rollup exit root
               * @param originNetwork Origin network
               * @param originAddress Origin address
               * @param destinationNetwork Network destination
               * @param destinationAddress Address destination
               * @param amount message value
               * @param metadata Abi encoded metadata if any, empty otherwise
               */
              function claimMessage(
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofLocalExitRoot,
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofRollupExitRoot,
                  uint256 globalIndex,
                  bytes32 mainnetExitRoot,
                  bytes32 rollupExitRoot,
                  uint32 originNetwork,
                  address originAddress,
                  uint32 destinationNetwork,
                  address destinationAddress,
                  uint256 amount,
                  bytes calldata metadata
              ) external ifNotEmergencyState {
                  // Destination network must be this networkID
                  if (destinationNetwork != networkID) {
                      revert DestinationNetworkInvalid();
                  }
                  // Verify leaf exist and it does not have been claimed
                  _verifyLeaf(
                      smtProofLocalExitRoot,
                      smtProofRollupExitRoot,
                      globalIndex,
                      mainnetExitRoot,
                      rollupExitRoot,
                      getLeafValue(
                          _LEAF_TYPE_MESSAGE,
                          originNetwork,
                          originAddress,
                          destinationNetwork,
                          destinationAddress,
                          amount,
                          keccak256(metadata)
                      )
                  );
                  // Execute message
                  bool success;
                  if (address(WETHToken) == address(0)) {
                      // Native token is ether
                      // Transfer ether
                      /* solhint-disable avoid-low-level-calls */
                      (success, ) = destinationAddress.call{value: amount}(
                          abi.encodeCall(
                              IBridgeMessageReceiver.onMessageReceived,
                              (originAddress, originNetwork, metadata)
                          )
                      );
                  } else {
                      // Mint wETH tokens
                      WETHToken.mint(destinationAddress, amount);
                      // Execute message
                      /* solhint-disable avoid-low-level-calls */
                      (success, ) = destinationAddress.call(
                          abi.encodeCall(
                              IBridgeMessageReceiver.onMessageReceived,
                              (originAddress, originNetwork, metadata)
                          )
                      );
                  }
                  if (!success) {
                      revert MessageFailed();
                  }
                  emit ClaimEvent(
                      globalIndex,
                      originNetwork,
                      originAddress,
                      destinationAddress,
                      amount
                  );
              }
              /**
               * @notice Returns the precalculated address of a wrapper using the token information
               * Note Updating the metadata of a token is not supported.
               * Since the metadata has relevance in the address deployed, this function will not return a valid
               * wrapped address if the metadata provided is not the original one.
               * @param originNetwork Origin network
               * @param originTokenAddress Origin token address, 0 address is reserved for ether
               * @param name Name of the token
               * @param symbol Symbol of the token
               * @param decimals Decimals of the token
               */
              function precalculatedWrapperAddress(
                  uint32 originNetwork,
                  address originTokenAddress,
                  string memory name,
                  string memory symbol,
                  uint8 decimals
              ) public view returns (address) {
                  bytes32 salt = keccak256(
                      abi.encodePacked(originNetwork, originTokenAddress)
                  );
                  bytes32 hashCreate2 = keccak256(
                      abi.encodePacked(
                          bytes1(0xff),
                          address(this),
                          salt,
                          keccak256(
                              abi.encodePacked(
                                  BASE_INIT_BYTECODE_WRAPPED_TOKEN,
                                  abi.encode(name, symbol, decimals)
                              )
                          )
                      )
                  );
                  // Last 20 bytes of hash to address
                  return address(uint160(uint256(hashCreate2)));
              }
              /**
               * @notice Returns the address of a wrapper using the token information if already exist
               * @param originNetwork Origin network
               * @param originTokenAddress Origin token address, 0 address is reserved for ether
               */
              function getTokenWrappedAddress(
                  uint32 originNetwork,
                  address originTokenAddress
              ) external view returns (address) {
                  return
                      tokenInfoToWrappedToken[
                          keccak256(abi.encodePacked(originNetwork, originTokenAddress))
                      ];
              }
              /**
               * @notice Function to activate the emergency state
               " Only can be called by the Polygon ZK-EVM in extreme situations
               */
              function activateEmergencyState() external onlyRollupManager {
                  _activateEmergencyState();
              }
              /**
               * @notice Function to deactivate the emergency state
               " Only can be called by the Polygon ZK-EVM
               */
              function deactivateEmergencyState() external onlyRollupManager {
                  _deactivateEmergencyState();
              }
              /**
               * @notice Verify leaf and checks that it has not been claimed
               * @param smtProofLocalExitRoot Smt proof
               * @param smtProofRollupExitRoot Smt proof
               * @param globalIndex Index of the leaf
               * @param mainnetExitRoot Mainnet exit root
               * @param rollupExitRoot Rollup exit root
               * @param leafValue leaf value
               */
              function _verifyLeaf(
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofLocalExitRoot,
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProofRollupExitRoot,
                  uint256 globalIndex,
                  bytes32 mainnetExitRoot,
                  bytes32 rollupExitRoot,
                  bytes32 leafValue
              ) internal {
                  // Check blockhash where the global exit root was set
                  // Note that previusly timestamps were setted, since in only checked if != 0 it's ok
                  uint256 blockHashGlobalExitRoot = globalExitRootManager
                      .globalExitRootMap(
                          GlobalExitRootLib.calculateGlobalExitRoot(
                              mainnetExitRoot,
                              rollupExitRoot
                          )
                      );
                  // check that this global exit root exist
                  if (blockHashGlobalExitRoot == 0) {
                      revert GlobalExitRootInvalid();
                  }
                  uint32 leafIndex;
                  uint32 sourceBridgeNetwork;
                  // Get origin network from global index
                  if (globalIndex & _GLOBAL_INDEX_MAINNET_FLAG != 0) {
                      // the network is mainnet, therefore sourceBridgeNetwork is 0
                      // Last 32 bits are leafIndex
                      leafIndex = uint32(globalIndex);
                      if (
                          !verifyMerkleProof(
                              leafValue,
                              smtProofLocalExitRoot,
                              leafIndex,
                              mainnetExitRoot
                          )
                      ) {
                          revert InvalidSmtProof();
                      }
                  } else {
                      // the network is a rollup, therefore sourceBridgeNetwork must be decoded
                      uint32 indexRollup = uint32(globalIndex >> 32);
                      sourceBridgeNetwork = indexRollup + 1;
                      // Last 32 bits are leafIndex
                      leafIndex = uint32(globalIndex);
                      // Verify merkle proof agains rollup exit root
                      if (
                          !verifyMerkleProof(
                              calculateRoot(leafValue, smtProofLocalExitRoot, leafIndex),
                              smtProofRollupExitRoot,
                              indexRollup,
                              rollupExitRoot
                          )
                      ) {
                          revert InvalidSmtProof();
                      }
                  }
                  // Set and check nullifier
                  _setAndCheckClaimed(leafIndex, sourceBridgeNetwork);
              }
              /**
               * @notice Function to check if an index is claimed or not
               * @param leafIndex Index
               * @param sourceBridgeNetwork Origin network
               */
              function isClaimed(
                  uint32 leafIndex,
                  uint32 sourceBridgeNetwork
              ) external view returns (bool) {
                  uint256 globalIndex;
                  // For consistency with the previous setted nullifiers
                  if (
                      networkID == _MAINNET_NETWORK_ID &&
                      sourceBridgeNetwork == _ZKEVM_NETWORK_ID
                  ) {
                      globalIndex = uint256(leafIndex);
                  } else {
                      globalIndex =
                          uint256(leafIndex) +
                          uint256(sourceBridgeNetwork) *
                          _MAX_LEAFS_PER_NETWORK;
                  }
                  (uint256 wordPos, uint256 bitPos) = _bitmapPositions(globalIndex);
                  uint256 mask = (1 << bitPos);
                  return (claimedBitMap[wordPos] & mask) == mask;
              }
              /**
               * @notice Function to check that an index is not claimed and set it as claimed
               * @param leafIndex Index
               * @param sourceBridgeNetwork Origin network
               */
              function _setAndCheckClaimed(
                  uint32 leafIndex,
                  uint32 sourceBridgeNetwork
              ) private {
                  uint256 globalIndex;
                  // For consistency with the previous setted nullifiers
                  if (
                      networkID == _MAINNET_NETWORK_ID &&
                      sourceBridgeNetwork == _ZKEVM_NETWORK_ID
                  ) {
                      globalIndex = uint256(leafIndex);
                  } else {
                      globalIndex =
                          uint256(leafIndex) +
                          uint256(sourceBridgeNetwork) *
                          _MAX_LEAFS_PER_NETWORK;
                  }
                  (uint256 wordPos, uint256 bitPos) = _bitmapPositions(globalIndex);
                  uint256 mask = 1 << bitPos;
                  uint256 flipped = claimedBitMap[wordPos] ^= mask;
                  if (flipped & mask == 0) {
                      revert AlreadyClaimed();
                  }
              }
              /**
               * @notice Function to update the globalExitRoot if the last deposit is not submitted
               */
              function updateGlobalExitRoot() external {
                  if (lastUpdatedDepositCount < depositCount) {
                      _updateGlobalExitRoot();
                  }
              }
              /**
               * @notice Function to update the globalExitRoot
               */
              function _updateGlobalExitRoot() internal {
                  lastUpdatedDepositCount = uint32(depositCount);
                  globalExitRootManager.updateExitRoot(getRoot());
              }
              /**
               * @notice Function decode an index into a wordPos and bitPos
               * @param index Index
               */
              function _bitmapPositions(
                  uint256 index
              ) private pure returns (uint256 wordPos, uint256 bitPos) {
                  wordPos = uint248(index >> 8);
                  bitPos = uint8(index);
              }
              /**
               * @notice Function to call token permit method of extended ERC20
               + @param token ERC20 token address
               * @param amount Quantity that is expected to be allowed
               * @param permitData Raw data of the call `permit` of the token
               */
              function _permit(
                  address token,
                  uint256 amount,
                  bytes calldata permitData
              ) internal {
                  bytes4 sig = bytes4(permitData[:4]);
                  if (sig == _PERMIT_SIGNATURE) {
                      (
                          address owner,
                          address spender,
                          uint256 value,
                          uint256 deadline,
                          uint8 v,
                          bytes32 r,
                          bytes32 s
                      ) = abi.decode(
                              permitData[4:],
                              (
                                  address,
                                  address,
                                  uint256,
                                  uint256,
                                  uint8,
                                  bytes32,
                                  bytes32
                              )
                          );
                      if (owner != msg.sender) {
                          revert NotValidOwner();
                      }
                      if (spender != address(this)) {
                          revert NotValidSpender();
                      }
                      if (value != amount) {
                          revert NotValidAmount();
                      }
                      // we call without checking the result, in case it fails and he doesn't have enough balance
                      // the following transferFrom should be fail. This prevents DoS attacks from using a signature
                      // before the smartcontract call
                      /* solhint-disable avoid-low-level-calls */
                      address(token).call(
                          abi.encodeWithSelector(
                              _PERMIT_SIGNATURE,
                              owner,
                              spender,
                              value,
                              deadline,
                              v,
                              r,
                              s
                          )
                      );
                  } else {
                      if (sig != _PERMIT_SIGNATURE_DAI) {
                          revert NotValidSignature();
                      }
                      (
                          address holder,
                          address spender,
                          uint256 nonce,
                          uint256 expiry,
                          bool allowed,
                          uint8 v,
                          bytes32 r,
                          bytes32 s
                      ) = abi.decode(
                              permitData[4:],
                              (
                                  address,
                                  address,
                                  uint256,
                                  uint256,
                                  bool,
                                  uint8,
                                  bytes32,
                                  bytes32
                              )
                          );
                      if (holder != msg.sender) {
                          revert NotValidOwner();
                      }
                      if (spender != address(this)) {
                          revert NotValidSpender();
                      }
                      // we call without checking the result, in case it fails and he doesn't have enough balance
                      // the following transferFrom should be fail. This prevents DoS attacks from using a signature
                      // before the smartcontract call
                      /* solhint-disable avoid-low-level-calls */
                      address(token).call(
                          abi.encodeWithSelector(
                              _PERMIT_SIGNATURE_DAI,
                              holder,
                              spender,
                              nonce,
                              expiry,
                              allowed,
                              v,
                              r,
                              s
                          )
                      );
                  }
              }
              /**
               * @notice Internal function that uses create2 to deploy the wrapped tokens
               * @param salt Salt used in create2 params,
               * tokenInfoHash will be used as salt for all wrappeds except for bridge native WETH, that will be bytes32(0)
               * @param constructorArgs Encoded constructor args for the wrapped token
               */
              function _deployWrappedToken(
                  bytes32 salt,
                  bytes memory constructorArgs
              ) internal returns (TokenWrapped newWrappedToken) {
                  bytes memory initBytecode = abi.encodePacked(
                      BASE_INIT_BYTECODE_WRAPPED_TOKEN,
                      constructorArgs
                  );
                  /// @solidity memory-safe-assembly
                  assembly {
                      newWrappedToken := create2(
                          0,
                          add(initBytecode, 0x20),
                          mload(initBytecode),
                          salt
                      )
                  }
                  if (address(newWrappedToken) == address(0))
                      revert FailedTokenWrappedDeployment();
              }
              // Helpers to safely get the metadata from a token, inspired by https://github.com/traderjoe-xyz/joe-core/blob/main/contracts/MasterChefJoeV3.sol#L55-L95
              /**
               * @notice Provides a safe ERC20.symbol version which returns 'NO_SYMBOL' as fallback string
               * @param token The address of the ERC-20 token contract
               */
              function _safeSymbol(address token) internal view returns (string memory) {
                  (bool success, bytes memory data) = address(token).staticcall(
                      abi.encodeCall(IERC20MetadataUpgradeable.symbol, ())
                  );
                  return success ? _returnDataToString(data) : "NO_SYMBOL";
              }
              /**
               * @notice  Provides a safe ERC20.name version which returns 'NO_NAME' as fallback string.
               * @param token The address of the ERC-20 token contract.
               */
              function _safeName(address token) internal view returns (string memory) {
                  (bool success, bytes memory data) = address(token).staticcall(
                      abi.encodeCall(IERC20MetadataUpgradeable.name, ())
                  );
                  return success ? _returnDataToString(data) : "NO_NAME";
              }
              /**
               * @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
               * Note Tokens with (decimals > 255) are not supported
               * @param token The address of the ERC-20 token contract
               */
              function _safeDecimals(address token) internal view returns (uint8) {
                  (bool success, bytes memory data) = address(token).staticcall(
                      abi.encodeCall(IERC20MetadataUpgradeable.decimals, ())
                  );
                  return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
              }
              /**
               * @notice Function to convert returned data to string
               * returns 'NOT_VALID_ENCODING' as fallback value.
               * @param data returned data
               */
              function _returnDataToString(
                  bytes memory data
              ) internal pure returns (string memory) {
                  if (data.length >= 64) {
                      return abi.decode(data, (string));
                  } else if (data.length == 32) {
                      // Since the strings on bytes32 are encoded left-right, check the first zero in the data
                      uint256 nonZeroBytes;
                      while (nonZeroBytes < 32 && data[nonZeroBytes] != 0) {
                          nonZeroBytes++;
                      }
                      // If the first one is 0, we do not handle the encoding
                      if (nonZeroBytes == 0) {
                          return "NOT_VALID_ENCODING";
                      }
                      // Create a byte array with nonZeroBytes length
                      bytes memory bytesArray = new bytes(nonZeroBytes);
                      for (uint256 i = 0; i < nonZeroBytes; i++) {
                          bytesArray[i] = data[i];
                      }
                      return string(bytesArray);
                  } else {
                      return "NOT_VALID_ENCODING";
                  }
              }
              /**
               * @notice Returns the encoded token metadata
               * @param token Address of the token
               */
              function getTokenMetadata(
                  address token
              ) public view returns (bytes memory) {
                  return
                      abi.encode(
                          _safeName(token),
                          _safeSymbol(token),
                          _safeDecimals(token)
                      );
              }
              /**
               * @notice Returns the precalculated address of a wrapper using the token address
               * Note Updating the metadata of a token is not supported.
               * Since the metadata has relevance in the address deployed, this function will not return a valid
               * wrapped address if the metadata provided is not the original one.
               * @param originNetwork Origin network
               * @param originTokenAddress Origin token address, 0 address is reserved for ether
               * @param token Address of the token to calculate the wrapper address
               */
              function calculateTokenWrapperAddress(
                  uint32 originNetwork,
                  address originTokenAddress,
                  address token
              ) external view returns (address) {
                  return
                      precalculatedWrapperAddress(
                          originNetwork,
                          originTokenAddress,
                          _safeName(token),
                          _safeSymbol(token),
                          _safeDecimals(token)
                      );
              }
          }
          

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

          File 5 of 6: PolygonZkEVMGlobalExitRootV2
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
          pragma solidity ^0.8.2;
          import "../../utils/AddressUpgradeable.sol";
          /**
           * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
           * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
           * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
           * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
           *
           * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
           * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
           * case an upgrade adds a module that needs to be initialized.
           *
           * For example:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * 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.8.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library AddressUpgradeable {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return 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 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: AGPL-3.0
          pragma solidity ^0.8.20;
          interface IBasePolygonZkEVMGlobalExitRoot {
              /**
               * @dev Thrown when the caller is not the allowed contracts
               */
              error OnlyAllowedContracts();
              function updateExitRoot(bytes32 newRollupExitRoot) external;
              function globalExitRootMap(
                  bytes32 globalExitRootNum
              ) external returns (uint256);
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity 0.8.20;
          /**
           * @dev A library that provides the necessary calculations to calculate the global exit root
           */
          library GlobalExitRootLib {
              function calculateGlobalExitRoot(
                  bytes32 mainnetExitRoot,
                  bytes32 rollupExitRoot
              ) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked(mainnetExitRoot, rollupExitRoot));
              }
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          import "../../interfaces/IBasePolygonZkEVMGlobalExitRoot.sol";
          interface IPolygonZkEVMGlobalExitRootV2 is IBasePolygonZkEVMGlobalExitRoot {
              function getLastGlobalExitRoot() external view returns (bytes32);
              function getRoot() external view returns (bytes32);
              function l1InfoRootMap(
                  uint32 depositCount
              ) external view returns (bytes32);
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          /**
           * This contract will be used as a helper for all the sparse merkle tree related functions
           * Based on the implementation of the deposit eth2.0 contract https://github.com/ethereum/consensus-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol
           */
          contract DepositContractBase {
              /**
               * @dev Thrown when the merkle tree is full
               */
              error MerkleTreeFull();
              // Merkle tree levels
              uint256 internal constant _DEPOSIT_CONTRACT_TREE_DEPTH = 32;
              // This ensures `depositCount` will fit into 32-bits
              uint256 internal constant _MAX_DEPOSIT_COUNT =
                  2 ** _DEPOSIT_CONTRACT_TREE_DEPTH - 1;
              // Branch array which contains the necessary sibilings to compute the next root when a new
              // leaf is inserted
              bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] internal _branch;
              // Counter of current deposits
              uint256 public depositCount;
              /**
               * @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.
               */
              uint256[10] private _gap;
              /**
               * @notice Computes and returns the merkle root
               */
              function getRoot() public view virtual returns (bytes32) {
                  bytes32 node;
                  uint256 size = depositCount;
                  bytes32 currentZeroHashHeight = 0;
                  for (
                      uint256 height = 0;
                      height < _DEPOSIT_CONTRACT_TREE_DEPTH;
                      height++
                  ) {
                      if (((size >> height) & 1) == 1)
                          node = keccak256(abi.encodePacked(_branch[height], node));
                      else
                          node = keccak256(abi.encodePacked(node, currentZeroHashHeight));
                      currentZeroHashHeight = keccak256(
                          abi.encodePacked(currentZeroHashHeight, currentZeroHashHeight)
                      );
                  }
                  return node;
              }
              /**
               * @notice Add a new leaf to the merkle tree
               * @param leaf Leaf
               */
              function _addLeaf(bytes32 leaf) internal {
                  bytes32 node = leaf;
                  // Avoid overflowing the Merkle tree (and prevent edge case in computing `_branch`)
                  if (depositCount >= _MAX_DEPOSIT_COUNT) {
                      revert MerkleTreeFull();
                  }
                  // Add deposit data root to Merkle tree (update a single `_branch` node)
                  uint256 size = ++depositCount;
                  for (
                      uint256 height = 0;
                      height < _DEPOSIT_CONTRACT_TREE_DEPTH;
                      height++
                  ) {
                      if (((size >> height) & 1) == 1) {
                          _branch[height] = node;
                          return;
                      }
                      node = keccak256(abi.encodePacked(_branch[height], node));
                  }
                  // As the loop should always end prematurely with the `return` statement,
                  // this code should be unreachable. We assert `false` just to be safe.
                  assert(false);
              }
              /**
               * @notice Verify merkle proof
               * @param leafHash Leaf hash
               * @param smtProof Smt proof
               * @param index Index of the leaf
               * @param root Merkle root
               */
              function verifyMerkleProof(
                  bytes32 leafHash,
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProof,
                  uint32 index,
                  bytes32 root
              ) public pure returns (bool) {
                  return calculateRoot(leafHash, smtProof, index) == root;
              }
              /**
               * @notice Calculate root from merkle proof
               * @param leafHash Leaf hash
               * @param smtProof Smt proof
               * @param index Index of the leaf
               */
              function calculateRoot(
                  bytes32 leafHash,
                  bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH] calldata smtProof,
                  uint32 index
              ) public pure returns (bytes32) {
                  bytes32 node = leafHash;
                  // Compute root
                  for (
                      uint256 height = 0;
                      height < _DEPOSIT_CONTRACT_TREE_DEPTH;
                      height++
                  ) {
                      if (((index >> height) & 1) == 1)
                          node = keccak256(abi.encodePacked(smtProof[height], node));
                      else node = keccak256(abi.encodePacked(node, smtProof[height]));
                  }
                  return node;
              }
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity ^0.8.20;
          import "../interfaces/IPolygonZkEVMGlobalExitRootV2.sol";
          /**
           * Since the current contract of PolygonZkEVMGlobalExitRoot will be upgraded to a PolygonZkEVMGlobalExitRootV2, and it will implement
           * the DepositContractBase, this base is needed to preserve the previous storage slots
           */
          abstract contract PolygonZkEVMGlobalExitRootBaseStorage is
              IPolygonZkEVMGlobalExitRootV2
          {
              // Rollup root, contains all exit roots of all rollups
              bytes32 public lastRollupExitRoot;
              // Mainnet exit root, this will be updated every time a deposit is made in mainnet
              bytes32 public lastMainnetExitRoot;
              // Store every global exit root: Root --> blockhash
              // Note that previously recoded global exit roots in previous versions, timestamp was recorded instead of blockhash
              mapping(bytes32 => uint256) public globalExitRootMap;
          }
          // SPDX-License-Identifier: AGPL-3.0
          pragma solidity 0.8.20;
          import "./interfaces/IPolygonZkEVMGlobalExitRootV2.sol";
          import "./lib/PolygonZkEVMGlobalExitRootBaseStorage.sol";
          import "../lib/GlobalExitRootLib.sol";
          import "./lib/DepositContractBase.sol";
          import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
          /**
           * Contract responsible for managing the exit roots across multiple networks
           */
          contract PolygonZkEVMGlobalExitRootV2 is
              PolygonZkEVMGlobalExitRootBaseStorage,
              DepositContractBase,
              Initializable
          {
              // PolygonZkEVMBridge address
              address public immutable bridgeAddress;
              // Rollup manager contract address
              address public immutable rollupManager;
              // Store every l1InfoLeaf
              mapping(uint32 leafCount => bytes32 l1InfoRoot) public l1InfoRootMap;
              /**
               * @dev Emitted when the global exit root is updated
               */
              event UpdateL1InfoTree(
                  bytes32 indexed mainnetExitRoot,
                  bytes32 indexed rollupExitRoot
              );
              /**
               * @dev Emitted when the global exit root is updated with the L1InfoTree leaf information
               */
              event UpdateL1InfoTreeV2(
                  bytes32 currentL1InfoRoot,
                  uint32 indexed leafCount,
                  uint256 blockhash,
                  uint64 minTimestamp
              );
              /**
               * @dev Emitted when the global exit root manager starts adding leafs to the L1InfoRootMap
               */
              event InitL1InfoRootMap(uint32 leafCount, bytes32 currentL1InfoRoot);
              /**
               * @param _rollupManager Rollup manager contract address
               * @param _bridgeAddress PolygonZkEVMBridge contract address
               */
              constructor(address _rollupManager, address _bridgeAddress) {
                  rollupManager = _rollupManager;
                  bridgeAddress = _bridgeAddress;
                  // disable initializers
                  _disableInitializers();
              }
              /**
               * @notice Reset the deposit tree since will be replace by a recursive one
               */
              function initialize() external virtual initializer {
                  // Get the current historic root
                  bytes32 currentL1InfoRoot = getRoot();
                  // Store L1InfoRoot
                  l1InfoRootMap[uint32(depositCount)] = currentL1InfoRoot;
                  emit InitL1InfoRootMap(uint32(depositCount), currentL1InfoRoot);
              }
              /**
               * @notice Update the exit root of one of the networks and the global exit root
               * @param newRoot new exit tree root
               */
              function updateExitRoot(bytes32 newRoot) external {
                  // Store storage variables into temporal variables since will be used multiple times
                  bytes32 cacheLastRollupExitRoot;
                  bytes32 cacheLastMainnetExitRoot;
                  if (msg.sender == bridgeAddress) {
                      lastMainnetExitRoot = newRoot;
                      cacheLastMainnetExitRoot = newRoot;
                      cacheLastRollupExitRoot = lastRollupExitRoot;
                  } else if (msg.sender == rollupManager) {
                      lastRollupExitRoot = newRoot;
                      cacheLastRollupExitRoot = newRoot;
                      cacheLastMainnetExitRoot = lastMainnetExitRoot;
                  } else {
                      revert OnlyAllowedContracts();
                  }
                  bytes32 newGlobalExitRoot = GlobalExitRootLib.calculateGlobalExitRoot(
                      cacheLastMainnetExitRoot,
                      cacheLastRollupExitRoot
                  );
                  // If it already exists, do not modify the blockhash
                  if (globalExitRootMap[newGlobalExitRoot] == 0) {
                      uint64 currentTimestmap = uint64(block.timestamp);
                      uint256 lastBlockHash = uint256(blockhash(block.number - 1));
                      globalExitRootMap[newGlobalExitRoot] = lastBlockHash;
                      // save new leaf in L1InfoTree
                      _addLeaf(
                          getLeafValue(newGlobalExitRoot, lastBlockHash, currentTimestmap)
                      );
                      // Get the current historic root
                      bytes32 currentL1InfoRoot = getRoot();
                      // Store L1InfoRoot
                      l1InfoRootMap[uint32(depositCount)] = currentL1InfoRoot;
                      emit UpdateL1InfoTree(
                          cacheLastMainnetExitRoot,
                          cacheLastRollupExitRoot
                      );
                      emit UpdateL1InfoTreeV2(
                          currentL1InfoRoot,
                          uint32(depositCount),
                          lastBlockHash,
                          currentTimestmap
                      );
                  }
              }
              /**
               * @notice Return last global exit root
               */
              function getLastGlobalExitRoot() public view returns (bytes32) {
                  return
                      GlobalExitRootLib.calculateGlobalExitRoot(
                          lastMainnetExitRoot,
                          lastRollupExitRoot
                      );
              }
              /**
               * @notice Computes and returns the merkle root of the L1InfoTree
               */
              function getRoot()
                  public
                  view
                  override(DepositContractBase, IPolygonZkEVMGlobalExitRootV2)
                  returns (bytes32)
              {
                  return super.getRoot();
              }
              /**
               * @notice Given the leaf data returns the leaf hash
               * @param newGlobalExitRoot Last global exit root
               * @param lastBlockHash Last accesible block hash
               * @param timestamp Ethereum timestamp in seconds
               */
              function getLeafValue(
                  bytes32 newGlobalExitRoot,
                  uint256 lastBlockHash,
                  uint64 timestamp
              ) public pure returns (bytes32) {
                  return
                      keccak256(
                          abi.encodePacked(newGlobalExitRoot, lastBlockHash, timestamp)
                      );
              }
          }
          

          File 6 of 6: StMATIC
          // SPDX-FileCopyrightText: 2021 ShardLabs
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.7;
          import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
          import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
          import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
          import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
          import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
          import "./interfaces/IValidatorShare.sol";
          import "./interfaces/INodeOperatorRegistry.sol";
          import "./interfaces/IStakeManager.sol";
          import "./interfaces/IPoLidoNFT.sol";
          import "./interfaces/IFxStateRootTunnel.sol";
          import "./interfaces/IStMATIC.sol";
          /// @title StMATIC
          /// @author 2021 ShardLabs.
          contract StMATIC is
              IStMATIC,
              ERC20Upgradeable,
              AccessControlUpgradeable,
              PausableUpgradeable
          {
              using SafeERC20Upgradeable for IERC20Upgradeable;
              /// @notice node operator registry interface.
              INodeOperatorRegistry public override nodeOperatorRegistry;
              /// @notice The fee distribution.
              FeeDistribution public override entityFees;
              /// @notice StakeManager interface.
              IStakeManager public override stakeManager;
              /// @notice LidoNFT interface.
              IPoLidoNFT public override poLidoNFT;
              /// @notice fxStateRootTunnel interface.
              IFxStateRootTunnel public override fxStateRootTunnel;
              /// @notice contract version.
              string public override version;
              /// @notice dao address.
              address public override dao;
              /// @notice insurance address.
              address public override insurance;
              /// @notice Matic ERC20 token.
              address public override token;
              /// @notice Matic ERC20 token address NOT USED IN V2.
              uint256 public override lastWithdrawnValidatorId;
              /// @notice total buffered Matic in the contract.
              uint256 public override totalBuffered;
              /// @notice delegation lower bound.
              uint256 public override delegationLowerBound;
              /// @notice reward distribution lower bound.
              uint256 public override rewardDistributionLowerBound;
              /// @notice reserved funds in Matic.
              uint256 public override reservedFunds;
              /// @notice submit threshold NOT USED in V2.
              uint256 public override submitThreshold;
              /// @notice submit handler NOT USED in V2.
              bool public override submitHandler;
              /// @notice token to WithdrawRequest mapping one-to-one.
              mapping(uint256 => RequestWithdraw) public override token2WithdrawRequest;
              /// @notice DAO Role.
              bytes32 public constant override DAO = keccak256("DAO");
              bytes32 public constant override PAUSE_ROLE =
                  keccak256("LIDO_PAUSE_OPERATOR");
              bytes32 public constant override UNPAUSE_ROLE =
                  keccak256("LIDO_UNPAUSE_OPERATOR");
              /// @notice When an operator quit the system StMATIC contract withdraw the total delegated
              /// to it. The request is stored inside this array.
              RequestWithdraw[] public stMaticWithdrawRequest;
              /// @notice token to Array WithdrawRequest mapping one-to-many.
              mapping(uint256 => RequestWithdraw[]) public token2WithdrawRequests;
              /// @notice protocol fee.
              uint8 public override protocolFee;
              // @notice these state variable are used to mark entrance and exit form a contract function
              uint256 private constant _NOT_ENTERED = 1;
              uint256 private constant _ENTERED = 2;
              uint256 private _status;
              // @notice used to execute the recovery 1 time
              bool private recovered;
              /// @notice Prevents a contract from calling itself, directly or indirectly.
              modifier nonReentrant() {
                  _nonReentrant();
                  _status = _ENTERED;
                  _;
                  _status = _NOT_ENTERED;
              }
              /// @param _nodeOperatorRegistry - Address of the node operator registry
              /// @param _token - Address of MATIC token on Ethereum Mainnet
              /// @param _dao - Address of the DAO
              /// @param _insurance - Address of the insurance
              /// @param _stakeManager - Address of the stake manager
              /// @param _poLidoNFT - Address of the stMATIC NFT
              /// @param _fxStateRootTunnel - Address of the FxStateRootTunnel
              function initialize(
                  address _nodeOperatorRegistry,
                  address _token,
                  address _dao,
                  address _insurance,
                  address _stakeManager,
                  address _poLidoNFT,
                  address _fxStateRootTunnel
              ) external override initializer {
                  __AccessControl_init_unchained();
                  __Pausable_init_unchained();
                  __ERC20_init_unchained("Staked MATIC", "stMATIC");
                  _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
                  _grantRole(DAO, _dao);
                  _grantRole(PAUSE_ROLE, msg.sender);
                  _grantRole(UNPAUSE_ROLE, _dao);
                  nodeOperatorRegistry = INodeOperatorRegistry(_nodeOperatorRegistry);
                  stakeManager = IStakeManager(_stakeManager);
                  poLidoNFT = IPoLidoNFT(_poLidoNFT);
                  fxStateRootTunnel = IFxStateRootTunnel(_fxStateRootTunnel);
                  dao = _dao;
                  token = _token;
                  insurance = _insurance;
                  entityFees = FeeDistribution(25, 50, 25);
              }
              /// @notice Send funds to StMATIC contract and mints StMATIC to msg.sender
              /// @notice Requires that msg.sender has approved _amount of MATIC to this contract
              /// @param _amount - Amount of MATIC sent from msg.sender to this contract
              /// @param _referral - referral address.
              /// @return Amount of StMATIC shares generated
              function submit(uint256 _amount, address _referral)
                  external
                  override
                  whenNotPaused
                  nonReentrant
                  returns (uint256)
              {
                  _require(_amount > 0, "Invalid amount");
                  IERC20Upgradeable(token).safeTransferFrom(
                      msg.sender,
                      address(this),
                      _amount
                  );
                  (
                      uint256 amountToMint,
                      uint256 totalShares,
                      uint256 totalPooledMatic
                  ) = convertMaticToStMatic(_amount);
                  _require(amountToMint > 0, "Mint ZERO");
                  _mint(msg.sender, amountToMint);
                  totalBuffered += _amount;
                  _bridge(totalShares + amountToMint, totalPooledMatic + _amount);
                  emit SubmitEvent(msg.sender, _amount, _referral);
                  return amountToMint;
              }
              /// @notice Stores users request to withdraw into a RequestWithdraw struct
              /// @param _amount - Amount of StMATIC that is requested to withdraw
              /// @param _referral - referral address.
              /// @return NFT token id.
              function requestWithdraw(uint256 _amount, address _referral)
                  external
                  override
                  whenNotPaused
                  nonReentrant
                  returns (uint256)
              {
                  _require(
                      _amount > 0 && balanceOf(msg.sender) >= _amount,
                      "Invalid amount"
                  );
                  uint256 tokenId;
                  {
                      uint256 totalPooledMatic = getTotalPooledMatic();
                      uint256 totalAmount2WithdrawInMatic = _convertStMaticToMatic(
                          _amount,
                          totalPooledMatic
                      );
                      _require(totalAmount2WithdrawInMatic > 0, "Withdraw ZERO Matic");
                      (
                          INodeOperatorRegistry.ValidatorData[] memory activeNodeOperators,
                          uint256 totalDelegated,
                          uint256[] memory bigNodeOperatorIds,
                          uint256[] memory smallNodeOperatorIds,
                          uint256[] memory allowedAmountToRequestFromOperators,
                          uint256 totalValidatorsToWithdrawFrom
                      ) = nodeOperatorRegistry.getValidatorsRequestWithdraw(totalAmount2WithdrawInMatic);
                      {
                          uint256 totalBufferedMem = totalBuffered;
                          uint256 reservedFundsMem = reservedFunds;
                          uint256 localActiveBalance = totalBufferedMem > reservedFundsMem
                              ? totalBufferedMem - reservedFundsMem
                              : 0;
                          uint256 liquidity = totalDelegated + localActiveBalance;
                          _require(
                              liquidity >= totalAmount2WithdrawInMatic,
                              "Too much to withdraw"
                          );
                      }
                      // Added a scoop here to fix stack too deep error
                      {
                          uint256 currentAmount2WithdrawInMatic = totalAmount2WithdrawInMatic;
                          tokenId = poLidoNFT.mint(msg.sender);
                          if (totalDelegated != 0) {
                              if (totalValidatorsToWithdrawFrom != 0) {
                                  currentAmount2WithdrawInMatic = _requestWithdrawBalanced(
                                      tokenId,
                                      activeNodeOperators,
                                      totalAmount2WithdrawInMatic,
                                      totalValidatorsToWithdrawFrom,
                                      totalDelegated,
                                      currentAmount2WithdrawInMatic
                                  );
                              } else {
                                  // request withdraw from big delegated validators
                                  currentAmount2WithdrawInMatic = _requestWithdrawUnbalanced(
                                      tokenId,
                                      activeNodeOperators,
                                      bigNodeOperatorIds,
                                      allowedAmountToRequestFromOperators,
                                      currentAmount2WithdrawInMatic
                                  );
                                  // request withdraw from small delegated validators
                                  if (currentAmount2WithdrawInMatic != 0) {
                                      currentAmount2WithdrawInMatic = _requestWithdrawUnbalanced(
                                          tokenId,
                                          activeNodeOperators,
                                          smallNodeOperatorIds,
                                          allowedAmountToRequestFromOperators,
                                          currentAmount2WithdrawInMatic
                                      );
                                  }
                              }
                          }
                          if (totalAmount2WithdrawInMatic > totalDelegated) {
                              IStakeManager stakeManagerMem = stakeManager;
                              token2WithdrawRequests[tokenId].push(
                                  RequestWithdraw(
                                      currentAmount2WithdrawInMatic,
                                      0,
                                      stakeManagerMem.epoch() + stakeManagerMem.withdrawalDelay(),
                                      address(0)
                                  )
                              );
                              reservedFunds += currentAmount2WithdrawInMatic;
                              currentAmount2WithdrawInMatic = 0;
                          }
                      }
                      _burn(msg.sender, _amount);
                      _bridge(totalSupply(), totalPooledMatic - totalAmount2WithdrawInMatic);
                  }
                  emit RequestWithdrawEvent(msg.sender, _amount, _referral);
                  return tokenId;
              }
              /// @notice Request withdraw when system is balanced
              function _requestWithdrawBalanced(
                  uint256 tokenId,
                  INodeOperatorRegistry.ValidatorData[] memory activeNodeOperators,
                  uint256 totalAmount2WithdrawInMatic,
                  uint256 totalValidatorsToWithdrawFrom,
                  uint256 totalDelegated,
                  uint256 currentAmount2WithdrawInMatic
              ) private returns (uint256) {
                  uint256 totalAmount = min(totalDelegated, totalAmount2WithdrawInMatic);
                  uint256 amount2WithdrawFromValidator = totalAmount /
                      totalValidatorsToWithdrawFrom;
                  for (uint256 idx = 0; idx < totalValidatorsToWithdrawFrom; idx++) {
                      address validatorShare = activeNodeOperators[idx].validatorShare;
                      _require(
                          _calculateValidatorShares(
                              validatorShare,
                              amount2WithdrawFromValidator
                          ) > 0,
                          "ZERO shares to withdraw"
                      );
                      currentAmount2WithdrawInMatic = _requestWithdraw(
                          tokenId,
                          validatorShare,
                          amount2WithdrawFromValidator,
                          currentAmount2WithdrawInMatic
                      );
                  }
                  return currentAmount2WithdrawInMatic;
              }
              /// @notice Request withdraw when system is unbalanced
              function _requestWithdrawUnbalanced(
                  uint256 tokenId,
                  INodeOperatorRegistry.ValidatorData[] memory activeNodeOperators,
                  uint256[] memory nodeOperatorIds,
                  uint256[] memory allowedAmountToRequestFromOperators,
                  uint256 currentAmount2WithdrawInMatic
              ) private returns (uint256) {
                  for (uint256 idx = 0; idx < nodeOperatorIds.length; idx++) {
                      uint256 id = nodeOperatorIds[idx];
                      uint256 amountCanBeRequested = allowedAmountToRequestFromOperators[
                          id
                      ];
                      if (amountCanBeRequested == 0) continue;
                      uint256 amount2WithdrawFromValidator = min(amountCanBeRequested, currentAmount2WithdrawInMatic);
                      address validatorShare = activeNodeOperators[id].validatorShare;
                      _require(
                          _calculateValidatorShares(
                              validatorShare,
                              amount2WithdrawFromValidator
                          ) > 0,
                          "ZERO shares to withdraw"
                      );
                      currentAmount2WithdrawInMatic = _requestWithdraw(
                          tokenId,
                          validatorShare,
                          amount2WithdrawFromValidator,
                          currentAmount2WithdrawInMatic
                      );
                      if (currentAmount2WithdrawInMatic == 0) break;
                  }
                  return currentAmount2WithdrawInMatic;
              }
              function _requestWithdraw(
                  uint256 tokenId,
                  address validatorShare,
                  uint256 amount2WithdrawFromValidator,
                  uint256 currentAmount2WithdrawInMatic
              ) private returns (uint256) {
                  sellVoucher_new(
                      validatorShare,
                      amount2WithdrawFromValidator,
                      type(uint256).max
                  );
                  IStakeManager stakeManagerMem = stakeManager;
                  token2WithdrawRequests[tokenId].push(
                      RequestWithdraw(
                          0,
                          IValidatorShare(validatorShare).unbondNonces(address(this)),
                          stakeManagerMem.epoch() + stakeManagerMem.withdrawalDelay(),
                          validatorShare
                      )
                  );
                  currentAmount2WithdrawInMatic -= amount2WithdrawFromValidator;
                  return currentAmount2WithdrawInMatic;
              }
              /// @notice This will be included in the cron job
              /// @notice Delegates tokens to validator share contract
              function delegate() external override whenNotPaused nonReentrant {
                  uint256 ltotalBuffered = totalBuffered;
                  uint256 lreservedFunds = reservedFunds;
                  _require(
                      ltotalBuffered > delegationLowerBound + lreservedFunds,
                      "Amount to delegate lower than minimum"
                  );
                  uint256 amountToDelegate = ltotalBuffered - lreservedFunds;
                  (
                      INodeOperatorRegistry.ValidatorData[]
                          memory delegatableNodeOperators,
                      uint256[] memory operatorRatiosToDelegate,
                      uint256 totalRatio
                  ) = nodeOperatorRegistry.getValidatorsDelegationAmount(
                          amountToDelegate
                      );
                  uint256 totalDelegatableNodeOperators = delegatableNodeOperators.length; 
                  uint256 remainder;
                  uint256 amountDelegated;
                  address maticTokenAddress = token;
                  address stakeManagerAddress = address(stakeManager);
                  IERC20Upgradeable(maticTokenAddress).safeApprove(stakeManagerAddress, 0);
                  IERC20Upgradeable(maticTokenAddress).safeApprove(
                      stakeManagerAddress,
                      amountToDelegate
                  );
                  // If the total Ratio is equal to ZERO that means the system is balanced so we
                  // distribute the buffered tokens equally between the validators
                  uint256 amountToDelegatePerOperator = amountToDelegate / totalDelegatableNodeOperators;
                  for (uint256 i = 0; i < totalDelegatableNodeOperators; i++) {
                      if (totalRatio != 0) {
                          if (operatorRatiosToDelegate[i] == 0) continue;
                          amountToDelegatePerOperator =
                              (operatorRatiosToDelegate[i] * amountToDelegate) /
                              totalRatio;
                      }
                      address _validatorAddress = delegatableNodeOperators[i]
                          .validatorShare;
                      uint256 shares = _calculateValidatorShares(
                          _validatorAddress,
                          amountToDelegatePerOperator
                      );
                      if (shares == 0) continue;
                      buyVoucher(_validatorAddress, amountToDelegatePerOperator, 0);
                      amountDelegated += amountToDelegatePerOperator;
                  }
                  remainder = amountToDelegate - amountDelegated;
                  totalBuffered = remainder + lreservedFunds;
                  emit DelegateEvent(amountDelegated, remainder);
              }
              /// @notice Claims tokens from validator share and sends them to the
              /// user if his request is in the userToWithdrawRequest
              /// @param _tokenId - Id of the token that wants to be claimed
              function claimTokens(uint256 _tokenId) external override whenNotPaused {
                  _require(
                      poLidoNFT.isApprovedOrOwner(msg.sender, _tokenId),
                      "Not owner"
                  );
                  if (token2WithdrawRequest[_tokenId].requestEpoch != 0) {
                      _claimTokensV1(_tokenId);
                  } else if (token2WithdrawRequests[_tokenId].length != 0) {
                      _claimTokensV2(_tokenId);
                  } else {
                      revert("Invalid claim token");
                  }
              }
              /// @notice Claims tokens v2
              function _claimTokensV2(uint256 _tokenId) private {
                  RequestWithdraw[] memory usersRequest = token2WithdrawRequests[
                      _tokenId
                  ];
                  _require(
                      stakeManager.epoch() >= usersRequest[0].requestEpoch,
                      "Not able to claim yet"
                  );
                  poLidoNFT.burn(_tokenId);
                  delete token2WithdrawRequests[_tokenId];
                  uint256 length = usersRequest.length;
                  uint256 amountToClaim;
                  address maticTokenAddress = token;
                  uint256 balanceBeforeClaim = IERC20Upgradeable(maticTokenAddress).balanceOf(
                      address(this)
                  );
                  for (uint256 idx = 0; idx < length; idx++) {
                      if (usersRequest[idx].validatorAddress != address(0)) {
                          unstakeClaimTokens_new(
                              usersRequest[idx].validatorAddress,
                              usersRequest[idx].validatorNonce
                          );
                      } else {
                          uint256 _amountToClaim = usersRequest[idx]
                              .amount2WithdrawFromStMATIC;
                          reservedFunds -= _amountToClaim;
                          totalBuffered -= _amountToClaim;
                          amountToClaim += _amountToClaim;
                      }
                  }
                  amountToClaim +=
                      IERC20Upgradeable(maticTokenAddress).balanceOf(address(this)) -
                      balanceBeforeClaim;
                  IERC20Upgradeable(maticTokenAddress).safeTransfer(msg.sender, amountToClaim);
                  emit ClaimTokensEvent(msg.sender, _tokenId, amountToClaim, 0);
              }
              /// @notice Claims tokens v1
              function _claimTokensV1(uint256 _tokenId) private {
                  RequestWithdraw memory usersRequest = token2WithdrawRequest[_tokenId];
                  _require(
                      stakeManager.epoch() >= usersRequest.requestEpoch,
                      "Not able to claim yet"
                  );
                  poLidoNFT.burn(_tokenId);
                  delete token2WithdrawRequest[_tokenId];
                  uint256 amountToClaim;
                  address maticTokenAddress = token;
                  if (usersRequest.validatorAddress != address(0)) {
                      uint256 balanceBeforeClaim = IERC20Upgradeable(maticTokenAddress).balanceOf(
                          address(this)
                      );
                      unstakeClaimTokens_new(
                          usersRequest.validatorAddress,
                          usersRequest.validatorNonce
                      );
                      amountToClaim =
                          IERC20Upgradeable(maticTokenAddress).balanceOf(address(this)) -
                          balanceBeforeClaim;
                  } else {
                      amountToClaim = usersRequest.amount2WithdrawFromStMATIC;
                      reservedFunds -= amountToClaim;
                      totalBuffered -= amountToClaim;
                  }
                  IERC20Upgradeable(maticTokenAddress).safeTransfer(msg.sender, amountToClaim);
                  emit ClaimTokensEvent(msg.sender, _tokenId, amountToClaim, 0);
              }
              /// @notice Distributes rewards claimed from validator shares based on fees defined
              /// in entityFee.
              function distributeRewards() external override whenNotPaused nonReentrant {
                  INodeOperatorRegistry.ValidatorData[] memory operatorInfos = nodeOperatorRegistry.listDelegatedNodeOperators();
                  uint256 totalActiveOperatorInfos = operatorInfos.length;
                  for (uint256 i = 0; i < totalActiveOperatorInfos; i++) {
                      IValidatorShare validatorShare = IValidatorShare(
                          operatorInfos[i].validatorShare
                      );
                      uint256 stMaticReward = validatorShare.getLiquidRewards(
                          address(this)
                      );
                      uint256 rewardThreshold = validatorShare.minAmount();
                      if (stMaticReward > rewardThreshold) {
                          validatorShare.withdrawRewards();
                      }
                  }
                  address maticTokenAddress = token;
                  uint256 totalRewards = IERC20Upgradeable(maticTokenAddress).balanceOf(
                      address(this)
                  ) - totalBuffered;
                  uint256 protocolRewards = totalRewards * protocolFee / 100;
                  _require(
                      protocolRewards > rewardDistributionLowerBound,
                      "Amount to distribute lower than minimum"
                  );
                  uint256 balanceBeforeDistribution = IERC20Upgradeable(maticTokenAddress).balanceOf(
                      address(this)
                  );
                  uint256 daoRewards = (protocolRewards * entityFees.dao) / 100;
                  uint256 insuranceRewards = (protocolRewards * entityFees.insurance) / 100;
                  uint256 operatorsRewards = (protocolRewards * entityFees.operators) / 100;
                  uint256 operatorReward = operatorsRewards / totalActiveOperatorInfos;
                  IERC20Upgradeable(maticTokenAddress).safeTransfer(dao, daoRewards);
                  IERC20Upgradeable(maticTokenAddress).safeTransfer(insurance, insuranceRewards);
                  for (uint256 i = 0; i < totalActiveOperatorInfos; i++) {
                      IERC20Upgradeable(maticTokenAddress).safeTransfer(
                          operatorInfos[i].rewardAddress,
                          operatorReward
                      );
                  }
                  uint256 currentBalance = IERC20Upgradeable(maticTokenAddress).balanceOf(
                      address(this)
                  );
                  uint256 totalDistributed = balanceBeforeDistribution - currentBalance;
                  // Add the remainder to totalBuffered
                  totalBuffered = currentBalance;
                  _bridge(totalSupply(), getTotalPooledMatic());
                  emit DistributeRewardsEvent(totalDistributed);
              }
              /// @notice Only NodeOperatorRegistry can call this function
              /// @notice Withdraws funds from stopped validator.
              /// @param _validatorShare - Address of the validator share that will be withdrawn
              function withdrawTotalDelegated(address _validatorShare)
                  external
                  override
                  nonReentrant
              {
                  _require(
                      msg.sender == address(nodeOperatorRegistry),
                      "Not a node operator"
                  );
                  (uint256 stakedAmount, ) = getTotalStake(
                      IValidatorShare(_validatorShare)
                  );
                  // Check if the validator has enough shares.
                  uint256 shares = _calculateValidatorShares(
                      _validatorShare,
                      stakedAmount
                  );
                  if (shares == 0) {
                      return;
                  }
                  _createWithdrawRequest(_validatorShare, stakedAmount);
                  emit WithdrawTotalDelegatedEvent(_validatorShare, stakedAmount);
              }
              /// @notice Rebalane the system by request withdraw from the validators that contains
              /// more token delegated to them.
              function rebalanceDelegatedTokens() external override onlyRole(DAO) {
                  uint256 amountToReDelegate = totalBuffered -
                      reservedFunds +
                      calculatePendingBufferedTokens();
                  (
                      INodeOperatorRegistry.ValidatorData[] memory nodeOperators,
                      uint256[] memory operatorRatiosToRebalance,
                      uint256 totalRatio,
                      uint256 totalToWithdraw
                  ) = nodeOperatorRegistry.getValidatorsRebalanceAmount(
                          amountToReDelegate
                      );
                  uint256 amountToWithdraw;
                  address _validatorAddress;
                  for (uint256 i = 0; i < nodeOperators.length; i++) {
                      if (operatorRatiosToRebalance[i] == 0) continue;
                      amountToWithdraw =
                          (operatorRatiosToRebalance[i] * totalToWithdraw) /
                          totalRatio;
                      if (amountToWithdraw == 0) continue;
                      _validatorAddress = nodeOperators[i].validatorShare;
                      uint256 shares = _calculateValidatorShares(
                          _validatorAddress,
                          amountToWithdraw
                      );
                      if (shares == 0) continue;
                      _createWithdrawRequest(
                          nodeOperators[i].validatorShare,
                          amountToWithdraw
                      );
                  }
              }
              function _createWithdrawRequest(address _validatorShare, uint256 amount)
                  private
              {
                  sellVoucher_new(_validatorShare, amount, type(uint256).max);
                  IStakeManager stakeManagerMem = stakeManager;
                  stMaticWithdrawRequest.push(
                      RequestWithdraw(
                          0,
                          IValidatorShare(_validatorShare).unbondNonces(address(this)),
                          stakeManagerMem.epoch() + stakeManagerMem.withdrawalDelay(),
                          _validatorShare
                      )
                  );
              }
              /// @notice calculate the total amount stored in stMaticWithdrawRequest array.
              /// @return pendingBufferedTokens the total pending amount for stMatic.
              function calculatePendingBufferedTokens()
                  public
                  view
                  override
                  returns (uint256 pendingBufferedTokens)
              {
                  uint256 pendingWithdrawalLength = stMaticWithdrawRequest.length;
                  for (uint256 i = 0; i < pendingWithdrawalLength; i++) {
                      pendingBufferedTokens += _getMaticFromRequestData(
                          stMaticWithdrawRequest[i]
                      );
                  }
                  return pendingBufferedTokens;
              }
              /// @notice Claims tokens from validator share and sends them to the StMATIC contract.
              function claimTokensFromValidatorToContract(uint256 _index)
                  external
                  override
                  whenNotPaused
                  nonReentrant
              {
                  uint256 length = stMaticWithdrawRequest.length;
                  _require(_index < length, "invalid index");
                  RequestWithdraw memory lidoRequest = stMaticWithdrawRequest[_index];
                  _require(
                      stakeManager.epoch() >= lidoRequest.requestEpoch,
                      "Not able to claim yet"
                  );
                  address maticTokenAddress = token;
                  uint256 balanceBeforeClaim = IERC20Upgradeable(maticTokenAddress).balanceOf(
                      address(this)
                  );
                  unstakeClaimTokens_new(
                      lidoRequest.validatorAddress,
                      lidoRequest.validatorNonce
                  );
                  uint256 claimedAmount = IERC20Upgradeable(maticTokenAddress).balanceOf(
                      address(this)
                  ) - balanceBeforeClaim;
                  totalBuffered += claimedAmount;
                  if (_index != length - 1 && length != 1) {
                      stMaticWithdrawRequest[_index] = stMaticWithdrawRequest[length - 1];
                  }
                  stMaticWithdrawRequest.pop();
                  _bridge(totalSupply(), getTotalPooledMatic());
                  emit ClaimTotalDelegatedEvent(
                      lidoRequest.validatorAddress,
                      claimedAmount
                  );
              }
              /// @notice Pauses the contract
              function pause() external onlyRole(PAUSE_ROLE) {
                  _pause();
              }
              /// @notice Unpauses the contract
              function unpause() external onlyRole(UNPAUSE_ROLE) {
                  _unpause();
              }
              ////////////////////////////////////////////////////////////
              /////                                                    ///
              /////             ***ValidatorShare API***               ///
              /////                                                    ///
              ////////////////////////////////////////////////////////////
              /// @notice Returns the stMaticWithdrawRequest list
              function getTotalWithdrawRequest()
                  public
                  view
                  returns (RequestWithdraw[] memory)
              {
                  return stMaticWithdrawRequest;
              }
              /// @notice API for delegated buying vouchers from validatorShare
              /// @param _validatorShare - Address of validatorShare contract
              /// @param _amount - Amount of MATIC to use for buying vouchers
              /// @param _minSharesToMint - Minimum of shares that is bought with _amount of MATIC
              /// @return Actual amount of MATIC used to buy voucher, might differ from _amount because of _minSharesToMint
              function buyVoucher(
                  address _validatorShare,
                  uint256 _amount,
                  uint256 _minSharesToMint
              ) private returns (uint256) {
                  uint256 amountSpent = IValidatorShare(_validatorShare).buyVoucher(
                      _amount,
                      _minSharesToMint
                  );
                  return amountSpent;
              }
              /// @notice API for delegated unstaking and claiming tokens from validatorShare
              /// @param _validatorShare - Address of validatorShare contract
              /// @param _unbondNonce - Unbond nonce
              function unstakeClaimTokens_new(
                  address _validatorShare,
                  uint256 _unbondNonce
              ) private {
                  IValidatorShare(_validatorShare).unstakeClaimTokens_new(_unbondNonce);
              }
              /// @notice API for delegated selling vouchers from validatorShare
              /// @param _validatorShare - Address of validatorShare contract
              /// @param _claimAmount - Amount of MATIC to claim
              /// @param _maximumSharesToBurn - Maximum amount of shares to burn
              function sellVoucher_new(
                  address _validatorShare,
                  uint256 _claimAmount,
                  uint256 _maximumSharesToBurn
              ) private {
                  IValidatorShare(_validatorShare).sellVoucher_new(
                      _claimAmount,
                      _maximumSharesToBurn
                  );
              }
              /// @notice API for getting total stake of this contract from validatorShare
              /// @param _validatorShare - Address of validatorShare contract
              /// @return Total stake of this contract and MATIC -> share exchange rate
              function getTotalStake(IValidatorShare _validatorShare)
                  public
                  view
                  override
                  returns (uint256, uint256)
              {
                  return _validatorShare.getTotalStake(address(this));
              }
              /// @notice API for liquid rewards of this contract from validatorShare
              /// @param _validatorShare - Address of validatorShare contract
              /// @return Liquid rewards of this contract
              function getLiquidRewards(IValidatorShare _validatorShare)
                  external
                  view
                  override
                  returns (uint256)
              {
                  return _validatorShare.getLiquidRewards(address(this));
              }
              ////////////////////////////////////////////////////////////
              /////                                                    ///
              /////            ***Helpers & Utilities***               ///
              /////                                                    ///
              ////////////////////////////////////////////////////////////
              /// @notice Helper function for that returns total pooled MATIC
              /// @return Total pooled MATIC
              function getTotalStakeAcrossAllValidators()
                  public
                  view
                  override
                  returns (uint256)
              {
                  uint256 totalStake;
                  INodeOperatorRegistry.ValidatorData[] memory nodeOperators = nodeOperatorRegistry.listWithdrawNodeOperators();
                  for (uint256 i = 0; i < nodeOperators.length; i++) {
                      (uint256 currValidatorShare, ) = getTotalStake(
                          IValidatorShare(nodeOperators[i].validatorShare)
                      );
                      totalStake += currValidatorShare;
                  }
                  return totalStake;
              }
              /// @notice Function that calculates total pooled Matic
              /// @return Total pooled Matic
              function getTotalPooledMatic() public view override returns (uint256) {
                  uint256 totalStaked = getTotalStakeAcrossAllValidators();
                  return _getTotalPooledMatic(totalStaked);
              }
              function _getTotalPooledMatic(uint256 _totalStaked)
                  private
                  view
                  returns (uint256)
              {
                  return
                      _totalStaked +
                      totalBuffered +
                      calculatePendingBufferedTokens() -
                      reservedFunds;
              }
              /// @notice Function that converts arbitrary stMATIC to Matic
              /// @param _amountInStMatic - Amount of stMATIC to convert to Matic
              /// @return amountInMatic - Amount of Matic after conversion,
              /// @return totalStMaticAmount - Total StMatic in the contract,
              /// @return totalPooledMatic - Total Matic in the staking pool
              function convertStMaticToMatic(uint256 _amountInStMatic)
                  external
                  view
                  override
                  returns (
                      uint256 amountInMatic,
                      uint256 totalStMaticAmount,
                      uint256 totalPooledMatic
                  )
              {
                  totalStMaticAmount = totalSupply();
                  uint256 totalPooledMATIC = getTotalPooledMatic();
                  return (
                      _convertStMaticToMatic(_amountInStMatic, totalPooledMATIC),
                      totalStMaticAmount,
                      totalPooledMATIC
                  );
              }
              /// @notice Function that converts arbitrary amount of stMatic to Matic
              /// @param _stMaticAmount - amount of stMatic to convert to Matic
              /// @return amountInMatic, totalStMaticAmount and totalPooledMatic
              function _convertStMaticToMatic(
                  uint256 _stMaticAmount,
                  uint256 _totalPooledMatic
              ) private view returns (uint256) {
                  uint256 totalStMaticSupply = totalSupply();
                  totalStMaticSupply = totalStMaticSupply == 0 ? 1 : totalStMaticSupply;
                  _totalPooledMatic = _totalPooledMatic == 0 ? 1 : _totalPooledMatic;
                  uint256 amountInMatic = (_stMaticAmount * _totalPooledMatic) /
                      totalStMaticSupply;
                  return amountInMatic;
              }
              /// @notice Function that converts arbitrary Matic to stMATIC
              /// @param _amountInMatic - Amount of Matic to convert to stMatic
              /// @return amountInStMatic - Amount of Matic to converted to stMatic
              /// @return totalStMaticSupply - Total amount of StMatic in the contract
              /// @return totalPooledMatic - Total amount of Matic in the staking pool
              function convertMaticToStMatic(uint256 _amountInMatic)
                  public
                  view
                  override
                  returns (
                      uint256 amountInStMatic,
                      uint256 totalStMaticSupply,
                      uint256 totalPooledMatic
                  )
              {
                  totalStMaticSupply = totalSupply();
                  totalPooledMatic = getTotalPooledMatic();
                  return (
                      _convertMaticToStMatic(_amountInMatic, totalPooledMatic),
                      totalStMaticSupply,
                      totalPooledMatic
                  );
              }
              function getToken2WithdrawRequests(uint256 _tokenId)
                  external
                  view
                  returns (RequestWithdraw[] memory)
              {
                  return token2WithdrawRequests[_tokenId];
              }
              /// @notice Function that converts arbitrary amount of Matic to stMatic
              /// @param _maticAmount - Amount in Matic to convert to stMatic
              /// @return amountInStMatic , totalStMaticAmount and totalPooledMatic
              function _convertMaticToStMatic(
                  uint256 _maticAmount,
                  uint256 _totalPooledMatic
              ) private view returns (uint256) {
                  uint256 totalStMaticSupply = totalSupply();
                  totalStMaticSupply = totalStMaticSupply == 0 ? 1 : totalStMaticSupply;
                  _totalPooledMatic = _totalPooledMatic == 0 ? 1 : _totalPooledMatic;
                  uint256 amountInStMatic = (_maticAmount * totalStMaticSupply) /
                      _totalPooledMatic;
                  return amountInStMatic;
              }
              ////////////////////////////////////////////////////////////
              /////                                                    ///
              /////                 ***Setters***                      ///
              /////                                                    ///
              ////////////////////////////////////////////////////////////
              /// @notice Function that sets entity fees
              /// @notice Callable only by dao
              /// @param _daoFee - DAO fee in %
              /// @param _operatorsFee - Operator fees in %
              /// @param _insuranceFee - Insurance fee in %
              function setFees(
                  uint8 _daoFee,
                  uint8 _operatorsFee,
                  uint8 _insuranceFee
              ) external override onlyRole(DAO) {
                  _require(
                      _daoFee + _operatorsFee + _insuranceFee == 100,
                      "sum(fee)!=100"
                  );
                  entityFees.dao = _daoFee;
                  entityFees.operators = _operatorsFee;
                  entityFees.insurance = _insuranceFee;
                  emit SetFees(_daoFee, _operatorsFee, _insuranceFee);
              }
              /// @notice Function that sets protocol fee
              /// @param _newProtocolFee new protocol fee
              function setProtocolFee(uint8 _newProtocolFee)
                  external
                  override
                  onlyRole(DAO)
              {
                  _require(
                      _newProtocolFee > 0 && _newProtocolFee <= 100,
                      "Invalid protcol fee"
                  );
                  uint8 oldProtocolFee = protocolFee;
                  protocolFee = _newProtocolFee;
                  emit SetProtocolFee(oldProtocolFee, _newProtocolFee);
              }
              /// @notice Function that sets new dao address
              /// @notice Callable only by dao
              /// @param _newDAO - New dao address
              function setDaoAddress(address _newDAO) external override onlyRole(DAO) {
                  address oldDAO = dao;
                  dao = _newDAO;
                  emit SetDaoAddress(oldDAO, _newDAO);
              }
              /// @notice Function that sets new insurance address
              /// @notice Callable only by dao
              /// @param _address - New insurance address
              function setInsuranceAddress(address _address)
                  external
                  override
                  onlyRole(DAO)
              {
                  insurance = _address;
                  emit SetInsuranceAddress(_address);
              }
              /// @notice Function that sets new node operator address
              /// @notice Only callable by dao
              /// @param _address - New node operator address
              function setNodeOperatorRegistryAddress(address _address)
                  external
                  override
                  onlyRole(DAO)
              {
                  nodeOperatorRegistry = INodeOperatorRegistry(_address);
                  emit SetNodeOperatorRegistryAddress(_address);
              }
              /// @notice Function that sets new lower bound for delegation
              /// @notice Only callable by dao
              /// @param _delegationLowerBound - New lower bound for delegation
              function setDelegationLowerBound(uint256 _delegationLowerBound)
                  external
                  override
                  onlyRole(DAO)
              {
                  delegationLowerBound = _delegationLowerBound;
                  emit SetDelegationLowerBound(_delegationLowerBound);
              }
              /// @notice Function that sets new lower bound for rewards distribution
              /// @notice Only callable by dao
              /// @param _newRewardDistributionLowerBound - New lower bound for rewards distribution
              function setRewardDistributionLowerBound(
                  uint256 _newRewardDistributionLowerBound
              ) external override onlyRole(DAO) {
                  uint256 oldRewardDistributionLowerBound = rewardDistributionLowerBound;
                  rewardDistributionLowerBound = _newRewardDistributionLowerBound;
                  emit SetRewardDistributionLowerBound(
                      oldRewardDistributionLowerBound,
                      _newRewardDistributionLowerBound
                  );
              }
              /// @notice Function that sets the poLidoNFT address
              /// @param _newLidoNFT new poLidoNFT address
              function setPoLidoNFT(address _newLidoNFT) external override onlyRole(DAO) {
                  address oldPoLidoNFT = address(poLidoNFT);
                  poLidoNFT = IPoLidoNFT(_newLidoNFT);
                  emit SetLidoNFT(oldPoLidoNFT, _newLidoNFT);
              }
              /// @notice Function that sets the fxStateRootTunnel address
              /// @param _newFxStateRootTunnel address of fxStateRootTunnel
              function setFxStateRootTunnel(address _newFxStateRootTunnel)
                  external
                  override
                  onlyRole(DAO)
              {
                  address oldFxStateRootTunnel = address(fxStateRootTunnel);
                  fxStateRootTunnel = IFxStateRootTunnel(_newFxStateRootTunnel);
                  emit SetFxStateRootTunnel(oldFxStateRootTunnel, _newFxStateRootTunnel);
              }
              /// @notice Function that sets the new version
              /// @param _newVersion - New version that will be set
              function setVersion(string calldata _newVersion)
                  external
                  override
                  onlyRole(DAO)
              {
                  emit Version(version, _newVersion);
                  version = _newVersion;
              }
              /// @notice Function that retrieves the amount of matic that will be claimed from the NFT token
              /// @param _tokenId - Id of the PolidoNFT
              function getMaticFromTokenId(uint256 _tokenId)
                  external
                  view
                  override
                  returns (uint256)
              {
                  if (token2WithdrawRequest[_tokenId].requestEpoch != 0) {
                      return _getMaticFromRequestData(token2WithdrawRequest[_tokenId]);
                  } else if (token2WithdrawRequests[_tokenId].length != 0) {
                      RequestWithdraw[] memory requestsData = token2WithdrawRequests[
                          _tokenId
                      ];
                      uint256 totalMatic;
                      for (uint256 idx = 0; idx < requestsData.length; idx++) {
                          totalMatic += _getMaticFromRequestData(requestsData[idx]);
                      }
                      return totalMatic;
                  }
                  return 0;
              }
              function _getMaticFromRequestData(RequestWithdraw memory requestData)
                  private
                  view
                  returns (uint256)
              {
                  if (requestData.validatorAddress == address(0)) {
                      return requestData.amount2WithdrawFromStMATIC;
                  }
                  IValidatorShare validatorShare = IValidatorShare(
                      requestData.validatorAddress
                  );
                  uint256 exchangeRatePrecision = _getExchangeRatePrecision(
                      validatorShare.validatorId()
                  );
                  uint256 withdrawExchangeRate = validatorShare.withdrawExchangeRate();
                  IValidatorShare.DelegatorUnbond memory unbond = validatorShare
                      .unbonds_new(address(this), requestData.validatorNonce);
                  return (withdrawExchangeRate * unbond.shares) / exchangeRatePrecision;
              }
              function _nonReentrant() private view {
                  _require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
              }
              function _require(bool _condition, string memory _message) private pure {
                  require(_condition, _message);
              }
              /// @dev get the exchange rate precision per validator.
              /// More details: https://github.com/maticnetwork/contracts/blob/v0.3.0-backport/contracts/staking/validatorShare/ValidatorShare.sol#L21
              /// https://github.com/maticnetwork/contracts/blob/v0.3.0-backport/contracts/staking/validatorShare/ValidatorShare.sol#L87
              function _getExchangeRatePrecision(uint256 _validatorId)
                  private
                  pure
                  returns (uint256)
              {
                  return _validatorId < 8 ? 100 : 10**29;
              }
              /// @dev calculate the number of shares to get when delegate an amount of Matic
              function _calculateValidatorShares(
                  address _validatorAddress,
                  uint256 _amountInMatic
              ) private view returns (uint256) {
                  IValidatorShare validatorShare = IValidatorShare(_validatorAddress);
                  uint256 exchangeRatePrecision = _getExchangeRatePrecision(
                      validatorShare.validatorId()
                  );
                  uint256 rate = validatorShare.exchangeRate();
                  return (_amountInMatic * exchangeRatePrecision) / rate;
              }
              /// @dev call fxStateRootTunnel to update L2.
              function _bridge(uint256 _totalSupply, uint256 _totalPooledMatic) private {
                  fxStateRootTunnel.sendMessageToChild(abi.encode(_totalSupply, _totalPooledMatic));
              }
              function min(uint256 _valueA, uint256 _valueB) private pure returns(uint256) {
                  return _valueA > _valueB ? _valueB : _valueA;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
          pragma solidity ^0.8.0;
          import "./IERC20Upgradeable.sol";
          import "./extensions/IERC20MetadataUpgradeable.sol";
          import "../../utils/ContextUpgradeable.sol";
          import "../../proxy/utils/Initializable.sol";
          /**
           * @dev Implementation of the {IERC20} interface.
           *
           * This implementation is agnostic to the way tokens are created. This means
           * that a supply mechanism has to be added in a derived contract using {_mint}.
           * For a generic mechanism see {ERC20PresetMinterPauser}.
           *
           * TIP: For a detailed writeup see our guide
           * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
           * to implement supply mechanisms].
           *
           * We have followed general OpenZeppelin Contracts guidelines: functions revert
           * instead returning `false` on failure. This behavior is nonetheless
           * conventional and does not conflict with the expectations of ERC20
           * applications.
           *
           * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
           * This allows applications to reconstruct the allowance for all accounts just
           * by listening to said events. Other implementations of the EIP may not emit
           * these events, as it isn't required by the specification.
           *
           * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
           * functions have been added to mitigate the well-known issues around setting
           * allowances. See {IERC20-approve}.
           */
          contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
              mapping(address => uint256) private _balances;
              mapping(address => mapping(address => uint256)) private _allowances;
              uint256 private _totalSupply;
              string private _name;
              string private _symbol;
              /**
               * @dev Sets the values for {name} and {symbol}.
               *
               * The default value of {decimals} is 18. To select a different value for
               * {decimals} you should overload it.
               *
               * All two of these values are immutable: they can only be set once during
               * construction.
               */
              function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
                  __ERC20_init_unchained(name_, symbol_);
              }
              function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
                  _name = name_;
                  _symbol = symbol_;
              }
              /**
               * @dev Returns the name of the token.
               */
              function name() public view virtual override returns (string memory) {
                  return _name;
              }
              /**
               * @dev Returns the symbol of the token, usually a shorter version of the
               * name.
               */
              function symbol() public view virtual override returns (string memory) {
                  return _symbol;
              }
              /**
               * @dev Returns the number of decimals used to get its user representation.
               * For example, if `decimals` equals `2`, a balance of `505` tokens should
               * be displayed to a user as `5.05` (`505 / 10 ** 2`).
               *
               * Tokens usually opt for a value of 18, imitating the relationship between
               * Ether and Wei. This is the value {ERC20} uses, unless this function is
               * overridden;
               *
               * NOTE: This information is only used for _display_ purposes: it in
               * no way affects any of the arithmetic of the contract, including
               * {IERC20-balanceOf} and {IERC20-transfer}.
               */
              function decimals() public view virtual override returns (uint8) {
                  return 18;
              }
              /**
               * @dev See {IERC20-totalSupply}.
               */
              function totalSupply() public view virtual override returns (uint256) {
                  return _totalSupply;
              }
              /**
               * @dev See {IERC20-balanceOf}.
               */
              function balanceOf(address account) public view virtual override returns (uint256) {
                  return _balances[account];
              }
              /**
               * @dev See {IERC20-transfer}.
               *
               * Requirements:
               *
               * - `to` cannot be the zero address.
               * - the caller must have a balance of at least `amount`.
               */
              function transfer(address to, uint256 amount) public virtual override returns (bool) {
                  address owner = _msgSender();
                  _transfer(owner, to, amount);
                  return true;
              }
              /**
               * @dev See {IERC20-allowance}.
               */
              function allowance(address owner, address spender) public view virtual override returns (uint256) {
                  return _allowances[owner][spender];
              }
              /**
               * @dev See {IERC20-approve}.
               *
               * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
               * `transferFrom`. This is semantically equivalent to an infinite approval.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function approve(address spender, uint256 amount) public virtual override returns (bool) {
                  address owner = _msgSender();
                  _approve(owner, spender, amount);
                  return true;
              }
              /**
               * @dev See {IERC20-transferFrom}.
               *
               * Emits an {Approval} event indicating the updated allowance. This is not
               * required by the EIP. See the note at the beginning of {ERC20}.
               *
               * NOTE: Does not update the allowance if the current allowance
               * is the maximum `uint256`.
               *
               * Requirements:
               *
               * - `from` and `to` cannot be the zero address.
               * - `from` must have a balance of at least `amount`.
               * - the caller must have allowance for ``from``'s tokens of at least
               * `amount`.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) public virtual override returns (bool) {
                  address spender = _msgSender();
                  _spendAllowance(from, spender, amount);
                  _transfer(from, to, amount);
                  return true;
              }
              /**
               * @dev Atomically increases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                  address owner = _msgSender();
                  _approve(owner, spender, _allowances[owner][spender] + addedValue);
                  return true;
              }
              /**
               * @dev Atomically decreases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               * - `spender` must have allowance for the caller of at least
               * `subtractedValue`.
               */
              function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                  address owner = _msgSender();
                  uint256 currentAllowance = _allowances[owner][spender];
                  require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                  unchecked {
                      _approve(owner, spender, currentAllowance - subtractedValue);
                  }
                  return true;
              }
              /**
               * @dev Moves `amount` of tokens from `sender` to `recipient`.
               *
               * This internal function is equivalent to {transfer}, and can be used to
               * e.g. implement automatic token fees, slashing mechanisms, etc.
               *
               * Emits a {Transfer} event.
               *
               * Requirements:
               *
               * - `from` cannot be the zero address.
               * - `to` cannot be the zero address.
               * - `from` must have a balance of at least `amount`.
               */
              function _transfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {
                  require(from != address(0), "ERC20: transfer from the zero address");
                  require(to != address(0), "ERC20: transfer to the zero address");
                  _beforeTokenTransfer(from, to, amount);
                  uint256 fromBalance = _balances[from];
                  require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                  unchecked {
                      _balances[from] = fromBalance - amount;
                  }
                  _balances[to] += amount;
                  emit Transfer(from, to, amount);
                  _afterTokenTransfer(from, to, amount);
              }
              /** @dev Creates `amount` tokens and assigns them to `account`, increasing
               * the total supply.
               *
               * Emits a {Transfer} event with `from` set to the zero address.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               */
              function _mint(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: mint to the zero address");
                  _beforeTokenTransfer(address(0), account, amount);
                  _totalSupply += amount;
                  _balances[account] += amount;
                  emit Transfer(address(0), account, amount);
                  _afterTokenTransfer(address(0), account, amount);
              }
              /**
               * @dev Destroys `amount` tokens from `account`, reducing the
               * total supply.
               *
               * Emits a {Transfer} event with `to` set to the zero address.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               * - `account` must have at least `amount` tokens.
               */
              function _burn(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: burn from the zero address");
                  _beforeTokenTransfer(account, address(0), amount);
                  uint256 accountBalance = _balances[account];
                  require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                  unchecked {
                      _balances[account] = accountBalance - amount;
                  }
                  _totalSupply -= amount;
                  emit Transfer(account, address(0), amount);
                  _afterTokenTransfer(account, address(0), amount);
              }
              /**
               * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
               *
               * This internal function is equivalent to `approve`, and can be used to
               * e.g. set automatic allowances for certain subsystems, etc.
               *
               * Emits an {Approval} event.
               *
               * Requirements:
               *
               * - `owner` cannot be the zero address.
               * - `spender` cannot be the zero address.
               */
              function _approve(
                  address owner,
                  address spender,
                  uint256 amount
              ) internal virtual {
                  require(owner != address(0), "ERC20: approve from the zero address");
                  require(spender != address(0), "ERC20: approve to the zero address");
                  _allowances[owner][spender] = amount;
                  emit Approval(owner, spender, amount);
              }
              /**
               * @dev Spend `amount` form the allowance of `owner` toward `spender`.
               *
               * Does not update the allowance amount in case of infinite allowance.
               * Revert if not enough allowance is available.
               *
               * Might emit an {Approval} event.
               */
              function _spendAllowance(
                  address owner,
                  address spender,
                  uint256 amount
              ) internal virtual {
                  uint256 currentAllowance = allowance(owner, spender);
                  if (currentAllowance != type(uint256).max) {
                      require(currentAllowance >= amount, "ERC20: insufficient allowance");
                      unchecked {
                          _approve(owner, spender, currentAllowance - amount);
                      }
                  }
              }
              /**
               * @dev Hook that is called before any transfer of tokens. This includes
               * minting and burning.
               *
               * Calling conditions:
               *
               * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
               * will be transferred to `to`.
               * - when `from` is zero, `amount` tokens will be minted for `to`.
               * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
               * - `from` and `to` are never both zero.
               *
               * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
               */
              function _beforeTokenTransfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {}
              /**
               * @dev Hook that is called after any transfer of tokens. This includes
               * minting and burning.
               *
               * Calling conditions:
               *
               * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
               * has been transferred to `to`.
               * - when `from` is zero, `amount` tokens have been minted for `to`.
               * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
               * - `from` and `to` are never both zero.
               *
               * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
               */
              function _afterTokenTransfer(
                  address from,
                  address to,
                  uint256 amount
              ) internal virtual {}
              /**
               * @dev This empty reserved space is put in place to allow future versions to add new
               * variables without shifting down storage in the inheritance chain.
               * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
               */
              uint256[45] private __gap;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControlUpgradeable.sol";
          import "../utils/ContextUpgradeable.sol";
          import "../utils/StringsUpgradeable.sol";
          import "../utils/introspection/ERC165Upgradeable.sol";
          import "../proxy/utils/Initializable.sol";
          /**
           * @dev Contract module that allows children to implement role-based access
           * control mechanisms. This is a lightweight version that doesn't allow enumerating role
           * members except through off-chain means by accessing the contract event logs. Some
           * applications may benefit from on-chain enumerability, for those cases see
           * {AccessControlEnumerable}.
           *
           * Roles are referred to by their `bytes32` identifier. These should be exposed
           * in the external API and be unique. The best way to achieve this is by
           * using `public constant` hash digests:
           *
           * ```
           * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
           * ```
           *
           * Roles can be used to represent a set of permissions. To restrict access to a
           * function call, use {hasRole}:
           *
           * ```
           * function foo() public {
           *     require(hasRole(MY_ROLE, msg.sender));
           *     ...
           * }
           * ```
           *
           * Roles can be granted and revoked dynamically via the {grantRole} and
           * {revokeRole} functions. Each role has an associated admin role, and only
           * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
           *
           * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
           * that only accounts with this role will be able to grant or revoke other
           * roles. More complex role relationships can be created by using
           * {_setRoleAdmin}.
           *
           * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
           * grant and revoke this role. Extra precautions should be taken to secure
           * accounts that have been granted it.
           */
          abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
              function __AccessControl_init() internal onlyInitializing {
              }
              function __AccessControl_init_unchained() internal onlyInitializing {
              }
              struct RoleData {
                  mapping(address => bool) members;
                  bytes32 adminRole;
              }
              mapping(bytes32 => RoleData) private _roles;
              bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
              /**
               * @dev Modifier that checks that an account has a specific role. Reverts
               * with a standardized message including the required role.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               *
               * _Available since v4.1._
               */
              modifier onlyRole(bytes32 role) {
                  _checkRole(role, _msgSender());
                  _;
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                  return _roles[role].members[account];
              }
              /**
               * @dev Revert with a standard message if `account` is missing `role`.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               */
              function _checkRole(bytes32 role, address account) internal view virtual {
                  if (!hasRole(role, account)) {
                      revert(
                          string(
                              abi.encodePacked(
                                  "AccessControl: account ",
                                  StringsUpgradeable.toHexString(uint160(account), 20),
                                  " is missing role ",
                                  StringsUpgradeable.toHexString(uint256(role), 32)
                              )
                          )
                      );
                  }
              }
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                  return _roles[role].adminRole;
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _grantRole(role, account);
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _revokeRole(role, account);
              }
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been revoked `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) public virtual override {
                  require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                  _revokeRole(role, account);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event. Note that unlike {grantRole}, this function doesn't perform any
               * checks on the calling account.
               *
               * [WARNING]
               * ====
               * This function should only be called from the constructor when setting
               * up the initial roles for the system.
               *
               * Using this function in any other way is effectively circumventing the admin
               * system imposed by {AccessControl}.
               * ====
               *
               * NOTE: This function is deprecated in favor of {_grantRole}.
               */
              function _setupRole(bytes32 role, address account) internal virtual {
                  _grantRole(role, account);
              }
              /**
               * @dev Sets `adminRole` as ``role``'s admin role.
               *
               * Emits a {RoleAdminChanged} event.
               */
              function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                  bytes32 previousAdminRole = getRoleAdmin(role);
                  _roles[role].adminRole = adminRole;
                  emit RoleAdminChanged(role, previousAdminRole, adminRole);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * Internal function without access restriction.
               */
              function _grantRole(bytes32 role, address account) internal virtual {
                  if (!hasRole(role, account)) {
                      _roles[role].members[account] = true;
                      emit RoleGranted(role, account, _msgSender());
                  }
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * Internal function without access restriction.
               */
              function _revokeRole(bytes32 role, address account) internal virtual {
                  if (hasRole(role, account)) {
                      _roles[role].members[account] = false;
                      emit RoleRevoked(role, account, _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.5.0) (token/ERC20/IERC20.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20Upgradeable {
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
              /**
               * @dev Moves `amount` tokens from the caller's account to `to`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address to, uint256 amount) external returns (bool);
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
              /**
               * @dev Moves `amount` tokens from `from` to `to` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 amount
              ) external returns (bool);
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
          pragma solidity ^0.8.0;
          import "../IERC20Upgradeable.sol";
          import "../../../utils/AddressUpgradeable.sol";
          /**
           * @title SafeERC20
           * @dev Wrappers around ERC20 operations that throw on failure (when the token
           * contract returns false). Tokens that return no value (and instead revert or
           * throw on failure) are also supported, non-reverting calls are assumed to be
           * successful.
           * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
           * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
           */
          library SafeERC20Upgradeable {
              using AddressUpgradeable for address;
              function safeTransfer(
                  IERC20Upgradeable token,
                  address to,
                  uint256 value
              ) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
              }
              function safeTransferFrom(
                  IERC20Upgradeable token,
                  address from,
                  address to,
                  uint256 value
              ) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
              }
              /**
               * @dev Deprecated. This function has issues similar to the ones found in
               * {IERC20-approve}, and its usage is discouraged.
               *
               * Whenever possible, use {safeIncreaseAllowance} and
               * {safeDecreaseAllowance} instead.
               */
              function safeApprove(
                  IERC20Upgradeable token,
                  address spender,
                  uint256 value
              ) internal {
                  // safeApprove should only be called when setting an initial allowance,
                  // or when resetting it to zero. To increase and decrease it, use
                  // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                  require(
                      (value == 0) || (token.allowance(address(this), spender) == 0),
                      "SafeERC20: approve from non-zero to non-zero allowance"
                  );
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
              }
              function safeIncreaseAllowance(
                  IERC20Upgradeable token,
                  address spender,
                  uint256 value
              ) internal {
                  uint256 newAllowance = token.allowance(address(this), spender) + value;
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
              }
              function safeDecreaseAllowance(
                  IERC20Upgradeable token,
                  address spender,
                  uint256 value
              ) internal {
                  unchecked {
                      uint256 oldAllowance = token.allowance(address(this), spender);
                      require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                      uint256 newAllowance = oldAllowance - value;
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                  }
              }
              /**
               * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
               * on the return value: the return value is optional (but if data is returned, it must not be false).
               * @param token The token targeted by the call.
               * @param data The call data (encoded using abi.encode or one of its variants).
               */
              function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
                  // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                  // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                  // the target address contains contract code and also asserts for success in the low-level call.
                  bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                  if (returndata.length > 0) {
                      // Return data is optional
                      require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (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 Returns true if the contract is paused, and false otherwise.
               */
              function paused() public view virtual returns (bool) {
                  return _paused;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is not paused.
               *
               * Requirements:
               *
               * - The contract must not be paused.
               */
              modifier whenNotPaused() {
                  require(!paused(), "Pausable: paused");
                  _;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is paused.
               *
               * Requirements:
               *
               * - The contract must be paused.
               */
              modifier whenPaused() {
                  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-FileCopyrightText: 2021 ShardLabs
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.7;
          /// @title Polygon validator share interface.
          /// @dev https://github.com/maticnetwork/contracts/blob/v0.3.0-backport/contracts/staking/validatorShare/ValidatorShare.sol
          /// @author 2021 ShardLabs
          interface IValidatorShare {
              struct DelegatorUnbond {
                  uint256 shares;
                  uint256 withdrawEpoch;
              }
              function unbondNonces(address _address) external view returns (uint256);
              function activeAmount() external view returns (uint256);
              function validatorId() external view returns (uint256);
              function withdrawExchangeRate() external view returns (uint256);
              function withdrawRewards() external;
              function unstakeClaimTokens() external;
              function minAmount() external view returns (uint256);
              function getLiquidRewards(address user) external view returns (uint256);
              function delegation() external view returns (bool);
              function updateDelegation(bool _delegation) external;
              function buyVoucher(uint256 _amount, uint256 _minSharesToMint)
                  external
                  returns (uint256);
              function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn)
                  external;
              function unstakeClaimTokens_new(uint256 unbondNonce) external;
              function unbonds_new(address _address, uint256 _unbondNonce)
                  external
                  view
                  returns (DelegatorUnbond memory);
              function getTotalStake(address user)
                  external
                  view
                  returns (uint256, uint256);
              function owner() external view returns (address);
              function restake() external returns (uint256, uint256);
              function unlock() external;
              function lock() external;
              function drain(
                  address token,
                  address payable destination,
                  uint256 amount
              ) external;
              function slash(uint256 _amount) external;
              function migrateOut(address user, uint256 amount) external;
              function migrateIn(address user, uint256 amount) external;
              function exchangeRate() external view returns (uint256);
          }
          // SPDX-FileCopyrightText: 2021 ShardLabs
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.7;
          /// @title INodeOperatorRegistry
          /// @author 2021 ShardLabs
          /// @notice Node operator registry interface
          interface INodeOperatorRegistry {
              /// @notice Node Operator Registry Statuses
              /// StakeManager statuses: https://github.com/maticnetwork/contracts/blob/v0.3.0-backport/contracts/staking/stakeManager/StakeManagerStorage.sol#L13
              /// ACTIVE: (validator.status == status.Active && validator.deactivationEpoch == 0)
              /// JAILED: (validator.status == status.Locked && validator.deactivationEpoch == 0)
              /// EJECTED: ((validator.status == status.Active || validator.status == status.Locked) && validator.deactivationEpoch != 0)
              /// UNSTAKED: (validator.status == status.Unstaked)
              enum NodeOperatorRegistryStatus {
                  INACTIVE,
                  ACTIVE,
                  JAILED,
                  EJECTED,
                  UNSTAKED
              }
              /// @notice The full node operator struct.
              /// @param validatorId the validator id on stakeManager.
              /// @param commissionRate rate of each operator
              /// @param validatorShare the validator share address of the validator.
              /// @param rewardAddress the reward address.
              /// @param delegation delegation.
              /// @param status the status of the node operator in the stake manager.
              struct FullNodeOperatorRegistry {
                  uint256 validatorId;
                  uint256 commissionRate;
                  address validatorShare;
                  address rewardAddress;
                  bool delegation;
                  NodeOperatorRegistryStatus status;
              }
              /// @notice The node operator struct
              /// @param validatorShare the validator share address of the validator.
              /// @param rewardAddress the reward address.
              struct ValidatorData {
                  address validatorShare;
                  address rewardAddress;
              }
              /// @notice Add a new node operator to the system.
              /// ONLY DAO can execute this function.
              /// @param validatorId the validator id on stakeManager.
              /// @param rewardAddress the reward address.
              function addNodeOperator(uint256 validatorId, address rewardAddress)
                  external;
              /// @notice Exit the node operator registry
              /// ONLY the owner of the node operator can call this function
              function exitNodeOperatorRegistry() external;
              /// @notice Remove a node operator from the system and withdraw total delegated tokens to it.
              /// ONLY DAO can execute this function.
              /// withdraw delegated tokens from it.
              /// @param validatorId the validator id on stakeManager.
              function removeNodeOperator(uint256 validatorId) external;
              /// @notice Remove a node operator from the system if it fails to meet certain conditions.
              /// 1. If the commission of the Node Operator is less than the standard commission.
              /// 2. If the Node Operator is either Unstaked or Ejected.
              /// @param validatorId the validator id on stakeManager.
              function removeInvalidNodeOperator(uint256 validatorId) external;
              /// @notice Set StMatic address.
              /// ONLY DAO can call this function
              /// @param newStMatic new stMatic address.
              function setStMaticAddress(address newStMatic) external;
              /// @notice Update reward address of a Node Operator.
              /// ONLY Operator owner can call this function
              /// @param newRewardAddress the new reward address.
              function setRewardAddress(address newRewardAddress) external;
              /// @notice set DISTANCETHRESHOLD
              /// ONLY DAO can call this function
              /// @param distanceThreshold the min rebalance threshold to include
              /// a validator in the delegation process.
              function setDistanceThreshold(uint256 distanceThreshold) external;
              /// @notice set MINREQUESTWITHDRAWRANGE
              /// ONLY DAO can call this function
              /// @param minRequestWithdrawRange the min request withdraw range.
              function setMinRequestWithdrawRange(uint8 minRequestWithdrawRange) external;
              /// @notice set MAXWITHDRAWPERCENTAGEPERREBALANCE
              /// ONLY DAO can call this function
              /// @param maxWithdrawPercentagePerRebalance the max withdraw percentage to
              /// withdraw from a validator per rebalance.
              function setMaxWithdrawPercentagePerRebalance(
                  uint256 maxWithdrawPercentagePerRebalance
              ) external;
              /// @notice Allows to set new version.
              /// @param _newVersion new contract version.
              function setVersion(string memory _newVersion) external;
              /// @notice List all the ACTIVE operators on the stakeManager.
              /// @return activeNodeOperators a list of ACTIVE node operator.
              function listDelegatedNodeOperators()
                  external
                  view
                  returns (ValidatorData[] memory);
              /// @notice List all the operators on the stakeManager that can be withdrawn from this includes ACTIVE, JAILED, and
              /// @notice UNSTAKED operators.
              /// @return nodeOperators a list of ACTIVE, JAILED or UNSTAKED node operator.
              function listWithdrawNodeOperators()
                  external
                  view
                  returns (ValidatorData[] memory);
              /// @notice  Calculate how total buffered should be delegated between the active validators,
              /// depending on if the system is balanced or not. If validators are in EJECTED or UNSTAKED
              /// status the function will revert.
              /// @param amountToDelegate The total that can be delegated.
              /// @return validators all active node operators.
              /// @return operatorRatiosToDelegate a list of operator's ratio used to calculate the amount to delegate per node.
              /// @return totalRatio the total ratio. If ZERO that means the system is balanced.
              ///  It will be calculated if the system is not balanced.
              function getValidatorsDelegationAmount(uint256 amountToDelegate)
                  external
                  view
                  returns (
                      ValidatorData[] memory validators,
                      uint256[] memory operatorRatiosToDelegate,
                      uint256 totalRatio
                  );
              /// @notice  Calculate how the system could be rebalanced depending on the current
              /// buffered tokens. If validators are in EJECTED or UNSTAKED status the function will revert.
              /// If the system is balanced the function will revert.
              /// @notice Calculate the operator ratios to rebalance the system.
              /// @param totalBuffered The total amount buffered in stMatic.
              /// @return validators all active node operators.
              /// @return operatorRatiosToRebalance a list of operator's ratio used to calculate the amount to withdraw per node.
              /// @return totalRatio the total ratio. If ZERO that means the system is balanced.
              /// @return totalToWithdraw the total amount to withdraw.
              function getValidatorsRebalanceAmount(uint256 totalBuffered)
                  external
                  view
                  returns (
                      ValidatorData[] memory validators,
                      uint256[] memory operatorRatiosToRebalance,
                      uint256 totalRatio,
                      uint256 totalToWithdraw
                  );
              /// @notice Calculate the validators to request withdrawal from depending if the system is balalnced or not.
              /// @param _withdrawAmount The amount to withdraw.
              /// @return validators all node operators.
              /// @return totalDelegated total amount delegated.
              /// @return bigNodeOperatorIds stores the ids of node operators that amount delegated to it is greater than the average delegation.
              /// @return smallNodeOperatorIds stores the ids of node operators that amount delegated to it is less than the average delegation.
              /// @return operatorAmountCanBeRequested amount that can be requested from a spécific validator when the system is not balanced.
              /// @return totalValidatorToWithdrawFrom the number of validator to withdraw from when the system is balanced.
              function getValidatorsRequestWithdraw(uint256 _withdrawAmount)
                  external
                  view
                  returns (
                      ValidatorData[] memory validators,
                      uint256 totalDelegated,
                      uint256[] memory bigNodeOperatorIds,
                      uint256[] memory smallNodeOperatorIds,
                      uint256[] memory operatorAmountCanBeRequested,
                      uint256 totalValidatorToWithdrawFrom
                  );
              /// @notice Returns a node operator.
              /// @param validatorId the validator id on stakeManager.
              /// @return operatorStatus a node operator.
              function getNodeOperator(uint256 validatorId)
                  external
                  view
                  returns (FullNodeOperatorRegistry memory operatorStatus);
              /// @notice Returns a node operator.
              /// @param rewardAddress the reward address.
              /// @return operatorStatus a node operator.
              function getNodeOperator(address rewardAddress)
                  external
                  view
                  returns (FullNodeOperatorRegistry memory operatorStatus);
              /// @notice Returns a node operator status.
              /// @param  validatorId is the id of the node operator.
              /// @return operatorStatus Returns a node operator status.
              function getNodeOperatorStatus(uint256 validatorId)
                  external
                  view
                  returns (NodeOperatorRegistryStatus operatorStatus);
              /// @notice Return a list of all validator ids in the system.
              function getValidatorIds() external view returns (uint256[] memory);
              /// @notice Explain to an end user what this does
              /// @return isBalanced if the system is balanced or not.
              /// @return distanceThreshold the distance threshold
              /// @return minAmount min amount delegated to a validator.
              /// @return maxAmount max amount delegated to a validator.
              function getProtocolStats()
                  external
                  view
                  returns (
                      bool isBalanced,
                      uint256 distanceThreshold,
                      uint256 minAmount,
                      uint256 maxAmount
                  );
              /// @notice List all the node operator statuses in the system.
              /// @return inactiveNodeOperator the number of inactive operators.
              /// @return activeNodeOperator the number of active operators.
              /// @return jailedNodeOperator the number of jailed operators.
              /// @return ejectedNodeOperator the number of ejected operators.
              /// @return unstakedNodeOperator the number of unstaked operators.
              function getStats()
                  external
                  view
                  returns (
                      uint256 inactiveNodeOperator,
                      uint256 activeNodeOperator,
                      uint256 jailedNodeOperator,
                      uint256 ejectedNodeOperator,
                      uint256 unstakedNodeOperator
                  );
              ////////////////////////////////////////////////////////////
              /////                                                    ///
              /////                 ***EVENTS***                       ///
              /////                                                    ///
              ////////////////////////////////////////////////////////////
              /// @notice Add Node Operator event
              /// @param validatorId validator id.
              /// @param rewardAddress reward address.
              event AddNodeOperator(uint256 validatorId, address rewardAddress);
              /// @notice Remove Node Operator event.
              /// @param validatorId validator id.
              /// @param rewardAddress reward address.
              event RemoveNodeOperator(uint256 validatorId, address rewardAddress);
              /// @notice Remove Invalid Node Operator event.
              /// @param validatorId validator id.
              /// @param rewardAddress reward address.
              event RemoveInvalidNodeOperator(uint256 validatorId, address rewardAddress);
              /// @notice Set StMatic address event.
              /// @param oldStMatic old stMatic address.
              /// @param newStMatic new stMatic address.
              event SetStMaticAddress(address oldStMatic, address newStMatic);
              /// @notice Set reward address event.
              /// @param validatorId the validator id.
              /// @param oldRewardAddress old reward address.
              /// @param newRewardAddress new reward address.
              event SetRewardAddress(
                  uint256 validatorId,
                  address oldRewardAddress,
                  address newRewardAddress
              );
              /// @notice Emit when the distance threshold is changed.
              /// @param oldDistanceThreshold the old distance threshold.
              /// @param newDistanceThreshold the new distance threshold.
              event SetDistanceThreshold(
                  uint256 oldDistanceThreshold,
                  uint256 newDistanceThreshold
              );
              /// @notice Emit when the min request withdraw range is changed.
              /// @param oldMinRequestWithdrawRange the old min request withdraw range.
              /// @param newMinRequestWithdrawRange the new min request withdraw range.
              event SetMinRequestWithdrawRange(
                  uint8 oldMinRequestWithdrawRange,
                  uint8 newMinRequestWithdrawRange
              );
              /// @notice Emit when the max withdraw percentage per rebalance is changed.
              /// @param oldMaxWithdrawPercentagePerRebalance the old max withdraw percentage per rebalance.
              /// @param newMaxWithdrawPercentagePerRebalance the new max withdraw percentage per rebalance.
              event SetMaxWithdrawPercentagePerRebalance(
                  uint256 oldMaxWithdrawPercentagePerRebalance,
                  uint256 newMaxWithdrawPercentagePerRebalance
              );
              /// @notice Emit when set new version.
              /// @param oldVersion the old version.
              /// @param newVersion the new version.
              event SetVersion(string oldVersion, string newVersion);
              /// @notice Emit when the node operator exits the registry
              /// @param validatorId node operator id
              /// @param rewardAddress node operator reward address
              event ExitNodeOperator(uint256 validatorId, address rewardAddress);
          }
          // SPDX-FileCopyrightText: 2021 ShardLabs
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.7;
          /// @title polygon stake manager interface.
          /// @author 2021 ShardLabs
          interface IStakeManager {
              /// @dev Plygon stakeManager status and Validator struct
              /// https://github.com/maticnetwork/contracts/blob/v0.3.0-backport/contracts/staking/stakeManager/StakeManagerStorage.sol
              enum Status {
                  Inactive,
                  Active,
                  Locked,
                  Unstaked
              }
              struct Validator {
                  uint256 amount;
                  uint256 reward;
                  uint256 activationEpoch;
                  uint256 deactivationEpoch;
                  uint256 jailTime;
                  address signer;
                  address contractAddress;
                  Status status;
                  uint256 commissionRate;
                  uint256 lastCommissionUpdate;
                  uint256 delegatorsReward;
                  uint256 delegatedAmount;
                  uint256 initialRewardPerStake;
              }
              /// @notice get the validator contract used for delegation.
              /// @param validatorId validator id.
              /// @return return the address of the validator contract.
              function getValidatorContract(uint256 validatorId)
                  external
                  view
                  returns (address);
              /// @notice Transfers amount from delegator
              function delegationDeposit(
                  uint256 validatorId,
                  uint256 amount,
                  address delegator
              ) external returns (bool);
              function epoch() external view returns (uint256);
              function validators(uint256 _index)
                  external
                  view
                  returns (Validator memory);
              /// @notice Returns a withdrawal delay.
              function withdrawalDelay() external  view returns (uint256);
          }
          // SPDX-FileCopyrightText: 2021 ShardLabs
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.7;
          import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
          /// @title PoLidoNFT interface.
          /// @author 2021 ShardLabs
          interface IPoLidoNFT is IERC721Upgradeable {
              
              /// @notice Mint a new Lido NFT for a _to address.
              /// @param _to owner of the NFT.
              /// @return tokenId returns the token id.
              function mint(address _to) external returns (uint256);
              /// @notice Burn a Lido NFT for a _to address.
              /// @param _tokenId the token id.
              function burn(uint256 _tokenId) external;
              /// @notice Check if the spender is the owner of the NFT or it was approved to it.
              /// @param _spender the spender address.
              /// @param _tokenId the token id.
              /// @return result return if the token is owned or approved to/by the spender.
              function isApprovedOrOwner(address _spender, uint256 _tokenId)
                  external
                  view
                  returns (bool);
              /// @notice Set stMatic address.
              /// @param _stMATIC new stMatic address.
              function setStMATIC(address _stMATIC) external;
              /// @notice List all the tokens owned by an address.
              /// @param _owner the owner address.
              /// @return result return a list of token ids.
              function getOwnedTokens(address _owner) external view returns (uint256[] memory);
              /// @notice toggle pause/unpause the contract
              function togglePause() external;
              /// @notice Allows to set new version.
              /// @param _newVersion new contract version.
              function setVersion(string calldata _newVersion) external;
          }
          // SPDX-FileCopyrightText: 2021 ShardLabs
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.7;
          interface IFxStateRootTunnel {
              /// @notice send message to child
              /// @param _message message
              function sendMessageToChild(bytes memory _message) external;
              /// @notice Set stMatic address.
              /// @param _newStMATIC the new stMatic address.
              function setStMATIC(address _newStMATIC) external;
          }
          // SPDX-FileCopyrightText: 2021 ShardLabs
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity 0.8.7;
          import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
          import "./IValidatorShare.sol";
          import "./INodeOperatorRegistry.sol";
          import "./IStakeManager.sol";
          import "./IPoLidoNFT.sol";
          import "./IFxStateRootTunnel.sol";
          /// @title StMATIC interface.
          /// @author 2021 ShardLabs
          interface IStMATIC is IERC20Upgradeable {
              /// @notice The request withdraw struct.
              /// @param amount2WithdrawFromStMATIC amount in Matic.
              /// @param validatorNonce validator nonce.
              /// @param requestEpoch request epoch.
              /// @param validatorAddress validator share address.
              struct RequestWithdraw {
                  uint256 amount2WithdrawFromStMATIC;
                  uint256 validatorNonce;
                  uint256 requestEpoch;
                  address validatorAddress;
              }
              /// @notice The fee distribution struct.
              /// @param dao dao fee.
              /// @param operators operators fee.
              /// @param insurance insurance fee.
              struct FeeDistribution {
                  uint8 dao;
                  uint8 operators;
                  uint8 insurance;
              }
              /// @notice node operator registry interface.
              function nodeOperatorRegistry()
                  external
                  view
                  returns (INodeOperatorRegistry);
              /// @notice The fee distribution.
              /// @return dao dao fee.
              /// @return operators operators fee.
              /// @return insurance insurance fee.
              function entityFees()
                  external
                  view
                  returns (
                      uint8,
                      uint8,
                      uint8
                  );
              /// @notice StakeManager interface.
              function stakeManager() external view returns (IStakeManager);
              /// @notice LidoNFT interface.
              function poLidoNFT() external view returns (IPoLidoNFT);
              /// @notice fxStateRootTunnel interface.
              function fxStateRootTunnel() external view returns (IFxStateRootTunnel);
              /// @notice contract version.
              function version() external view returns (string memory);
              /// @notice dao address.
              function dao() external view returns (address);
              /// @notice insurance address.
              function insurance() external view returns (address);
              /// @notice Matic ERC20 token.
              function token() external view returns (address);
              /// @notice Matic ERC20 token address NOT USED IN V2.
              function lastWithdrawnValidatorId() external view returns (uint256);
              /// @notice total buffered Matic in the contract.
              function totalBuffered() external view returns (uint256);
              /// @notice delegation lower bound.
              function delegationLowerBound() external view returns (uint256);
              /// @notice reward distribution lower bound.
              function rewardDistributionLowerBound() external view returns (uint256);
              /// @notice reserved funds in Matic.
              function reservedFunds() external view returns (uint256);
              /// @notice submit threshold NOT USED in V2.
              function submitThreshold() external view returns (uint256);
              /// @notice submit handler NOT USED in V2.
              function submitHandler() external view returns (bool);
              /// @notice token to WithdrawRequest mapping.
              function token2WithdrawRequest(uint256 _requestId)
                  external
                  view
                  returns (
                      uint256,
                      uint256,
                      uint256,
                      address
                  );
              /// @notice DAO Role.
              function DAO() external view returns (bytes32);
              /// @notice PAUSE_ROLE Role.
              function PAUSE_ROLE() external view returns (bytes32);
              /// @notice UNPAUSE_ROLE Role.
              function UNPAUSE_ROLE() external view returns (bytes32);
              /// @notice Protocol Fee.
              function protocolFee() external view returns (uint8);
              /// @param _nodeOperatorRegistry - Address of the node operator registry
              /// @param _token - Address of MATIC token on Ethereum Mainnet
              /// @param _dao - Address of the DAO
              /// @param _insurance - Address of the insurance
              /// @param _stakeManager - Address of the stake manager
              /// @param _poLidoNFT - Address of the stMATIC NFT
              /// @param _fxStateRootTunnel - Address of the FxStateRootTunnel
              function initialize(
                  address _nodeOperatorRegistry,
                  address _token,
                  address _dao,
                  address _insurance,
                  address _stakeManager,
                  address _poLidoNFT,
                  address _fxStateRootTunnel
              ) external;
              /// @notice Send funds to StMATIC contract and mints StMATIC to msg.sender
              /// @notice Requires that msg.sender has approved _amount of MATIC to this contract
              /// @param _amount - Amount of MATIC sent from msg.sender to this contract
              /// @param _referral - referral address.
              /// @return Amount of StMATIC shares generated
              function submit(uint256 _amount, address _referral) external returns (uint256);
              /// @notice Stores users request to withdraw into a RequestWithdraw struct
              /// @param _amount - Amount of StMATIC that is requested to withdraw
              /// @param _referral - referral address.
              /// @return NFT token id.
              function requestWithdraw(uint256 _amount, address _referral) external returns (uint256);
              /// @notice This will be included in the cron job
              /// @notice Delegates tokens to validator share contract
              function delegate() external;
              /// @notice Claims tokens from validator share and sends them to the
              /// StMATIC contract
              /// @param _tokenId - Id of the token that is supposed to be claimed
              function claimTokens(uint256 _tokenId) external;
              /// @notice Distributes rewards claimed from validator shares based on fees defined
              /// in entityFee.
              function distributeRewards() external;
              /// @notice withdraw total delegated
              /// @param _validatorShare validator share address.
              function withdrawTotalDelegated(address _validatorShare) external;
              /// @notice Claims tokens from validator share and sends them to the
              /// StMATIC contract
              /// @param _tokenId - Id of the token that is supposed to be claimed
              function claimTokensFromValidatorToContract(uint256 _tokenId) external;
              /// @notice Rebalane the system by request withdraw from the validators that contains
              /// more token delegated to them.
              function rebalanceDelegatedTokens() external;
              /// @notice Helper function for that returns total pooled MATIC
              /// @return Total pooled MATIC
              function getTotalStake(IValidatorShare _validatorShare)
                  external
                  view
                  returns (uint256, uint256);
              /// @notice API for liquid rewards of this contract from validatorShare
              /// @param _validatorShare - Address of validatorShare contract
              /// @return Liquid rewards of this contract
              function getLiquidRewards(IValidatorShare _validatorShare)
                  external
                  view
                  returns (uint256);
              /// @notice Helper function for that returns total pooled MATIC
              /// @return Total pooled MATIC
              function getTotalStakeAcrossAllValidators() external view returns (uint256);
              /// @notice Function that calculates total pooled Matic
              /// @return Total pooled Matic
              function getTotalPooledMatic() external view returns (uint256);
              /// @notice get Matic from token id.
              /// @param _tokenId NFT token id.
              /// @return total the amount in Matic.
              function getMaticFromTokenId(uint256 _tokenId)
                  external
                  view
                  returns (uint256);
              /// @notice calculate the total amount stored in all the NFTs owned by
              /// stMatic contract.
              /// @return pendingBufferedTokens the total pending amount for stMatic.
              function calculatePendingBufferedTokens() external view returns(uint256);
              /// @notice Function that converts arbitrary stMATIC to Matic
              /// @param _amountInStMatic - Amount of stMATIC to convert to Matic
              /// @return amountInMatic - Amount of Matic after conversion,
              /// @return totalStMaticAmount - Total StMatic in the contract,
              /// @return totalPooledMatic - Total Matic in the staking pool
              function convertStMaticToMatic(uint256 _amountInStMatic)
                  external
                  view
                  returns (
                      uint256 amountInMatic,
                      uint256 totalStMaticAmount,
                      uint256 totalPooledMatic
                  );
              /// @notice Function that converts arbitrary Matic to stMATIC
              /// @param _amountInMatic - Amount of Matic to convert to stMatic
              /// @return amountInStMatic - Amount of Matic to converted to stMatic
              /// @return totalStMaticSupply - Total amount of StMatic in the contract
              /// @return totalPooledMatic - Total amount of Matic in the staking pool
              function convertMaticToStMatic(uint256 _amountInMatic)
                  external
                  view
                  returns (
                      uint256 amountInStMatic,
                      uint256 totalStMaticSupply,
                      uint256 totalPooledMatic
                  );
              /// @notice Allows to set fees.
              /// @param _daoFee the new daoFee
              /// @param _operatorsFee the new operatorsFee
              /// @param _insuranceFee the new insuranceFee
              function setFees(
                  uint8 _daoFee,
                  uint8 _operatorsFee,
                  uint8 _insuranceFee
              ) external;
              /// @notice Function that sets protocol fee
              /// @param _newProtocolFee - Insurance fee in %
              function setProtocolFee(uint8 _newProtocolFee) external;
              /// @notice Allows to set DaoAddress.
              /// @param _newDaoAddress new DaoAddress.
              function setDaoAddress(address _newDaoAddress) external;
              /// @notice Allows to set InsuranceAddress.
              /// @param _newInsuranceAddress new InsuranceAddress.
              function setInsuranceAddress(address _newInsuranceAddress) external;
              /// @notice Allows to set NodeOperatorRegistryAddress.
              /// @param _newNodeOperatorRegistry new NodeOperatorRegistryAddress.
              function setNodeOperatorRegistryAddress(address _newNodeOperatorRegistry)
                  external;
              /// @notice Allows to set delegationLowerBound.
              /// @param _delegationLowerBound new delegationLowerBound.
              function setDelegationLowerBound(uint256 _delegationLowerBound) external;
              /// @notice Allows to set setRewardDistributionLowerBound.
              /// @param _rewardDistributionLowerBound new setRewardDistributionLowerBound.
              function setRewardDistributionLowerBound(
                  uint256 _rewardDistributionLowerBound
              ) external;
              /// @notice Allows to set LidoNFT.
              /// @param _poLidoNFT new LidoNFT.
              function setPoLidoNFT(address _poLidoNFT) external;
              /// @notice Allows to set fxStateRootTunnel.
              /// @param _fxStateRootTunnel new fxStateRootTunnel.
              function setFxStateRootTunnel(address _fxStateRootTunnel) external;
              /// @notice Allows to set new version.
              /// @param _newVersion new contract version.
              function setVersion(string calldata _newVersion) external;
              ////////////////////////////////////////////////////////////
              /////                                                    ///
              /////                 ***EVENTS***                       ///
              /////                                                    ///
              ////////////////////////////////////////////////////////////
              /// @notice Emit when submit.
              /// @param _from msg.sender.
              /// @param _amount amount.
              /// @param _referral - referral address.
              event SubmitEvent(address indexed _from, uint256 _amount, address indexed _referral);
              /// @notice Emit when request withdraw.
              /// @param _from msg.sender.
              /// @param _amount amount.
              /// @param _referral - referral address.
              event RequestWithdrawEvent(address indexed _from, uint256 _amount, address indexed _referral);
              /// @notice Emit when distribute rewards.
              /// @param _amount amount.
              event DistributeRewardsEvent(uint256 indexed _amount);
              /// @notice Emit when withdraw total delegated.
              /// @param _from msg.sender.
              /// @param _amount amount.
              event WithdrawTotalDelegatedEvent(
                  address indexed _from,
                  uint256 indexed _amount
              );
              /// @notice Emit when delegate.
              /// @param _amountDelegated amount to delegate.
              /// @param _remainder remainder.
              event DelegateEvent(
                  uint256 indexed _amountDelegated,
                  uint256 indexed _remainder
              );
              /// @notice Emit when ClaimTokens.
              /// @param _from msg.sender.
              /// @param _id token id.
              /// @param _amountClaimed amount Claimed.
              /// @param _amountBurned amount Burned.
              event ClaimTokensEvent(
                  address indexed _from,
                  uint256 indexed _id,
                  uint256 indexed _amountClaimed,
                  uint256 _amountBurned
              );
              /// @notice Emit when set new InsuranceAddress.
              /// @param _newInsuranceAddress the new InsuranceAddress.
              event SetInsuranceAddress(address indexed _newInsuranceAddress);
              /// @notice Emit when set new NodeOperatorRegistryAddress.
              /// @param _newNodeOperatorRegistryAddress the new NodeOperatorRegistryAddress.
              event SetNodeOperatorRegistryAddress(
                  address indexed _newNodeOperatorRegistryAddress
              );
              /// @notice Emit when set new SetDelegationLowerBound.
              /// @param _delegationLowerBound the old DelegationLowerBound.
              event SetDelegationLowerBound(uint256 indexed _delegationLowerBound);
              /// @notice Emit when set new RewardDistributionLowerBound.
              /// @param oldRewardDistributionLowerBound the old RewardDistributionLowerBound.
              /// @param newRewardDistributionLowerBound the new RewardDistributionLowerBound.
              event SetRewardDistributionLowerBound(
                  uint256 oldRewardDistributionLowerBound,
                  uint256 newRewardDistributionLowerBound
              );
              /// @notice Emit when set new LidoNFT.
              /// @param oldLidoNFT the old oldLidoNFT.
              /// @param newLidoNFT the new newLidoNFT.
              event SetLidoNFT(address oldLidoNFT, address newLidoNFT);
              /// @notice Emit when set new FxStateRootTunnel.
              /// @param oldFxStateRootTunnel the old FxStateRootTunnel.
              /// @param newFxStateRootTunnel the new FxStateRootTunnel.
              event SetFxStateRootTunnel(
                  address oldFxStateRootTunnel,
                  address newFxStateRootTunnel
              );
              /// @notice Emit when set new DAO.
              /// @param oldDaoAddress the old DAO.
              /// @param newDaoAddress the new DAO.
              event SetDaoAddress(address oldDaoAddress, address newDaoAddress);
              /// @notice Emit when set fees.
              /// @param daoFee the new daoFee
              /// @param operatorsFee the new operatorsFee
              /// @param insuranceFee the new insuranceFee
              event SetFees(uint256 daoFee, uint256 operatorsFee, uint256 insuranceFee);
              /// @notice Emit when set ProtocolFee.
              /// @param oldProtocolFee the new ProtocolFee
              /// @param newProtocolFee the new ProtocolFee
              event SetProtocolFee(uint8 oldProtocolFee, uint8 newProtocolFee);
              /// @notice Emit when set ProtocolFee.
              /// @param validatorShare vaidatorshare address.
              /// @param amountClaimed amount claimed.
              event ClaimTotalDelegatedEvent(
                  address indexed validatorShare,
                  uint256 indexed amountClaimed
              );
              /// @notice Emit when set version.
              /// @param oldVersion old.
              /// @param newVersion new.
              event Version(
                  string oldVersion,
                  string indexed newVersion
              );
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
          pragma solidity ^0.8.0;
          import "../IERC20Upgradeable.sol";
          /**
           * @dev Interface for the optional metadata functions from the ERC20 standard.
           *
           * _Available since v4.1._
           */
          interface IERC20MetadataUpgradeable is IERC20Upgradeable {
              /**
               * @dev Returns the name of the token.
               */
              function name() external view returns (string memory);
              /**
               * @dev Returns the symbol of the token.
               */
              function symbol() external view returns (string memory);
              /**
               * @dev Returns the decimals places of the token.
               */
              function decimals() external view returns (uint8);
          }
          // 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.5.0) (proxy/utils/Initializable.sol)
          pragma solidity ^0.8.0;
          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.
           *
           * 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 initialize the implementation contract, you can either invoke the
           * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() initializer {}
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               */
              bool private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Modifier to protect an initializer function from being invoked twice.
               */
              modifier initializer() {
                  // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                  // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                  // contract may have been reentered.
                  require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
                  bool isTopLevelCall = !_initializing;
                  if (isTopLevelCall) {
                      _initializing = true;
                      _initialized = true;
                  }
                  _;
                  if (isTopLevelCall) {
                      _initializing = false;
                  }
              }
              /**
               * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
               * {initializer} modifier, directly or indirectly.
               */
              modifier onlyInitializing() {
                  require(_initializing, "Initializable: contract is not initializing");
                  _;
              }
              function _isConstructor() private view returns (bool) {
                  return !AddressUpgradeable.isContract(address(this));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
          pragma solidity ^0.8.1;
          /**
           * @dev Collection of functions related to the address type
           */
          library AddressUpgradeable {
              /**
               * @dev Returns true if `account` is a contract.
               *
               * [IMPORTANT]
               * ====
               * It is unsafe to assume that an address for which this function returns
               * false is an externally-owned account (EOA) and not a contract.
               *
               * Among others, `isContract` will return false for the following
               * types of addresses:
               *
               *  - an externally-owned account
               *  - a contract in construction
               *  - an address where a contract will be created
               *  - an address where a contract lived, but was destroyed
               * ====
               *
               * [IMPORTANT]
               * ====
               * You shouldn't rely on `isContract` to protect against flash loan attacks!
               *
               * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
               * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
               * constructor.
               * ====
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies on extcodesize/address.code.length, which returns 0
                  // for contracts in construction, since the code is only stored at the end
                  // of the constructor execution.
                  return account.code.length > 0;
              }
              /**
               * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
               * `recipient`, forwarding all available gas and reverting on errors.
               *
               * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
               * of certain opcodes, possibly making contracts go over the 2300 gas limit
               * imposed by `transfer`, making them unable to receive funds via
               * `transfer`. {sendValue} removes this limitation.
               *
               * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
               */
              function sendValue(address payable recipient, uint256 amount) internal {
                  require(address(this).balance >= amount, "Address: insufficient balance");
                  (bool success, ) = recipient.call{value: amount}("");
                  require(success, "Address: unable to send value, recipient may have reverted");
              }
              /**
               * @dev Performs a Solidity function call using a low level `call`. A
               * plain `call` is an unsafe replacement for a function call: use this
               * function instead.
               *
               * If `target` reverts with a revert reason, it is bubbled up by this
               * function (like regular Solidity function calls).
               *
               * Returns the raw returned data. To convert to the expected return value,
               * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
               *
               * Requirements:
               *
               * - `target` must be a contract.
               * - calling `target` with `data` must not revert.
               *
               * _Available since v3.1._
               */
              function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCall(target, data, "Address: low-level call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
               * `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, 0, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but also transferring `value` wei to `target`.
               *
               * Requirements:
               *
               * - the calling contract must have an ETH balance of at least `value`.
               * - the called Solidity function must be `payable`.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value
              ) internal returns (bytes memory) {
                  return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
              }
              /**
               * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
               * with `errorMessage` as a fallback revert reason when `target` reverts.
               *
               * _Available since v3.1._
               */
              function functionCallWithValue(
                  address target,
                  bytes memory data,
                  uint256 value,
                  string memory errorMessage
              ) internal returns (bytes memory) {
                  require(address(this).balance >= value, "Address: insufficient balance for call");
                  require(isContract(target), "Address: call to non-contract");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResult(success, returndata, errorMessage);
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                  return functionStaticCall(target, data, "Address: low-level static call failed");
              }
              /**
               * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
               * but performing a static call.
               *
               * _Available since v3.3._
               */
              function functionStaticCall(
                  address target,
                  bytes memory data,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  require(isContract(target), "Address: static call to non-contract");
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResult(success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason using the provided one.
               *
               * _Available since v4.3._
               */
              function verifyCallResult(
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal pure returns (bytes memory) {
                  if (success) {
                      return returndata;
                  } else {
                      // Look for revert reason and bubble it up if present
                      if (returndata.length > 0) {
                          // The easiest way to bubble the revert reason is using memory via assembly
                          assembly {
                              let returndata_size := mload(returndata)
                              revert(add(32, returndata), returndata_size)
                          }
                      } else {
                          revert(errorMessage);
                      }
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev External interface of AccessControl declared to support ERC165 detection.
           */
          interface IAccessControlUpgradeable {
              /**
               * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
               *
               * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
               * {RoleAdminChanged} not being emitted signaling this.
               *
               * _Available since v3.1._
               */
              event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
              /**
               * @dev Emitted when `account` is granted `role`.
               *
               * `sender` is the account that originated the contract call, an admin role
               * bearer except when using {AccessControl-_setupRole}.
               */
              event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Emitted when `account` is revoked `role`.
               *
               * `sender` is the account that originated the contract call:
               *   - if using `revokeRole`, it is the admin role bearer
               *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
               */
              event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) external view returns (bool);
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {AccessControl-_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) external view returns (bytes32);
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been granted `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev String operations.
           */
          library StringsUpgradeable {
              bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
              /**
               * @dev Converts a `uint256` to its ASCII `string` decimal representation.
               */
              function toString(uint256 value) internal pure returns (string memory) {
                  // Inspired by OraclizeAPI's implementation - MIT licence
                  // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                  if (value == 0) {
                      return "0";
                  }
                  uint256 temp = value;
                  uint256 digits;
                  while (temp != 0) {
                      digits++;
                      temp /= 10;
                  }
                  bytes memory buffer = new bytes(digits);
                  while (value != 0) {
                      digits -= 1;
                      buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                      value /= 10;
                  }
                  return string(buffer);
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  if (value == 0) {
                      return "0x00";
                  }
                  uint256 temp = value;
                  uint256 length = 0;
                  while (temp != 0) {
                      length++;
                      temp >>= 8;
                  }
                  return toHexString(value, length);
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  bytes memory buffer = new bytes(2 * length + 2);
                  buffer[0] = "0";
                  buffer[1] = "x";
                  for (uint256 i = 2 * length + 1; i > 1; --i) {
                      buffer[i] = _HEX_SYMBOLS[value & 0xf];
                      value >>= 4;
                  }
                  require(value == 0, "Strings: hex length insufficient");
                  return string(buffer);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
          pragma solidity ^0.8.0;
          import "./IERC165Upgradeable.sol";
          import "../../proxy/utils/Initializable.sol";
          /**
           * @dev Implementation of the {IERC165} interface.
           *
           * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
           * for the additional interface id that will be supported. For example:
           *
           * ```solidity
           * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
           *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
           * }
           * ```
           *
           * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
           */
          abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
              function __ERC165_init() internal onlyInitializing {
              }
              function __ERC165_init_unchained() internal onlyInitializing {
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IERC165Upgradeable).interfaceId;
              }
              /**
               * @dev This empty reserved space is put in place to allow future versions to add new
               * variables without shifting down storage in the inheritance chain.
               * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
               */
              uint256[50] private __gap;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC165 standard, as defined in the
           * https://eips.ethereum.org/EIPS/eip-165[EIP].
           *
           * Implementers can declare support of contract interfaces, which can then be
           * queried by others ({ERC165Checker}).
           *
           * For an implementation, see {ERC165}.
           */
          interface IERC165Upgradeable {
              /**
               * @dev Returns true if this contract implements the interface defined by
               * `interfaceId`. See the corresponding
               * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
               * to learn more about how these ids are created.
               *
               * This function call must use less than 30 000 gas.
               */
              function supportsInterface(bytes4 interfaceId) external view returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
          pragma solidity ^0.8.0;
          import "../../utils/introspection/IERC165Upgradeable.sol";
          /**
           * @dev Required interface of an ERC721 compliant contract.
           */
          interface IERC721Upgradeable is IERC165Upgradeable {
              /**
               * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
               */
              event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
              /**
               * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
               */
              event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
              /**
               * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
               */
              event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
              /**
               * @dev Returns the number of tokens in ``owner``'s account.
               */
              function balanceOf(address owner) external view returns (uint256 balance);
              /**
               * @dev Returns the owner of the `tokenId` token.
               *
               * Requirements:
               *
               * - `tokenId` must exist.
               */
              function ownerOf(uint256 tokenId) external view returns (address owner);
              /**
               * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
               * are aware of the ERC721 protocol to prevent tokens from being forever locked.
               *
               * Requirements:
               *
               * - `from` cannot be the zero address.
               * - `to` cannot be the zero address.
               * - `tokenId` token must exist and be owned by `from`.
               * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
               * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
               *
               * Emits a {Transfer} event.
               */
              function safeTransferFrom(
                  address from,
                  address to,
                  uint256 tokenId
              ) external;
              /**
               * @dev Transfers `tokenId` token from `from` to `to`.
               *
               * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
               *
               * Requirements:
               *
               * - `from` cannot be the zero address.
               * - `to` cannot be the zero address.
               * - `tokenId` token must be owned by `from`.
               * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(
                  address from,
                  address to,
                  uint256 tokenId
              ) external;
              /**
               * @dev Gives permission to `to` to transfer `tokenId` token to another account.
               * The approval is cleared when the token is transferred.
               *
               * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
               *
               * Requirements:
               *
               * - The caller must own the token or be an approved operator.
               * - `tokenId` must exist.
               *
               * Emits an {Approval} event.
               */
              function approve(address to, uint256 tokenId) external;
              /**
               * @dev Returns the account approved for `tokenId` token.
               *
               * Requirements:
               *
               * - `tokenId` must exist.
               */
              function getApproved(uint256 tokenId) external view returns (address operator);
              /**
               * @dev Approve or remove `operator` as an operator for the caller.
               * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
               *
               * Requirements:
               *
               * - The `operator` cannot be the caller.
               *
               * Emits an {ApprovalForAll} event.
               */
              function setApprovalForAll(address operator, bool _approved) external;
              /**
               * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
               *
               * See {setApprovalForAll}
               */
              function isApprovedForAll(address owner, address operator) external view returns (bool);
              /**
               * @dev Safely transfers `tokenId` token from `from` to `to`.
               *
               * Requirements:
               *
               * - `from` cannot be the zero address.
               * - `to` cannot be the zero address.
               * - `tokenId` token must exist and be owned by `from`.
               * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
               * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
               *
               * Emits a {Transfer} event.
               */
              function safeTransferFrom(
                  address from,
                  address to,
                  uint256 tokenId,
                  bytes calldata data
              ) external;
          }