creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControlUpgradeable {\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted signaling this.\n     *\n     * _Available since v3.1._\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call, an admin role\n     * bearer except when using {AccessControl-_setupRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     */\n    function renounceRole(bytes32 role, address account) external;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized < type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20PermitUpgradeable {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n    using AddressUpgradeable for address;\n\n    function safeTransfer(\n        IERC20Upgradeable token,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20Upgradeable token,\n        address from,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(\n        IERC20Upgradeable token,\n        address spender,\n        uint256 value\n    ) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(\n        IERC20Upgradeable token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 newAllowance = token.allowance(address(this), spender) + value;\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(\n        IERC20Upgradeable token,\n        address spender,\n        uint256 value\n    ) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            uint256 newAllowance = oldAllowance - value;\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n        }\n    }\n\n    function safePermit(\n        IERC20PermitUpgradeable token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length > 0) {\n            // Return data is optional\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165Upgradeable).interfaceId;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1);\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator,\n        Rounding rounding\n    ) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10**64) {\n                value /= 10**64;\n                result += 64;\n            }\n            if (value >= 10**32) {\n                value /= 10**32;\n                result += 32;\n            }\n            if (value >= 10**16) {\n                value /= 10**16;\n                result += 16;\n            }\n            if (value >= 10**8) {\n                value /= 10**8;\n                result += 8;\n            }\n            if (value >= 10**4) {\n                value /= 10**4;\n                result += 4;\n            }\n            if (value >= 10**2) {\n                value /= 10**2;\n                result += 2;\n            }\n            if (value >= 10**1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = MathUpgradeable.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, MathUpgradeable.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n}\n"
      },
      "@openzeppelin/contracts5/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts5/interfaces/IERC1967.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n}\n"
      },
      "@openzeppelin/contracts5/proxy/beacon/IBeacon.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {UpgradeableBeacon} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"
      },
      "@openzeppelin/contracts5/proxy/ERC1967/ERC1967Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)\n\npragma solidity ^0.8.20;\n\nimport {Proxy} from \"../Proxy.sol\";\nimport {ERC1967Utils} from \"./ERC1967Utils.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy {\n    /**\n     * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.\n     *\n     * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an\n     * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.\n     *\n     * Requirements:\n     *\n     * - If `data` is empty, `msg.value` must be zero.\n     */\n    constructor(address implementation, bytes memory _data) payable {\n        ERC1967Utils.upgradeToAndCall(implementation, _data);\n    }\n\n    /**\n     * @dev Returns the current implementation address.\n     *\n     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using\n     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n     */\n    function _implementation() internal view virtual override returns (address) {\n        return ERC1967Utils.getImplementation();\n    }\n}\n"
      },
      "@openzeppelin/contracts5/proxy/ERC1967/ERC1967Utils.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\n\npragma solidity ^0.8.20;\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../../utils/Address.sol\";\nimport {StorageSlot} from \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n */\nlibrary ERC1967Utils {\n    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.\n    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev The `implementation` of the proxy is invalid.\n     */\n    error ERC1967InvalidImplementation(address implementation);\n\n    /**\n     * @dev The `admin` of the proxy is invalid.\n     */\n    error ERC1967InvalidAdmin(address admin);\n\n    /**\n     * @dev The `beacon` of the proxy is invalid.\n     */\n    error ERC1967InvalidBeacon(address beacon);\n\n    /**\n     * @dev An upgrade function sees `msg.value > 0` that may be lost.\n     */\n    error ERC1967NonPayable();\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        if (newImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(newImplementation);\n        }\n        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n        _setImplementation(newImplementation);\n        emit Upgraded(newImplementation);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(newImplementation, data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Returns the current admin.\n     *\n     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using\n     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n     */\n    function getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        if (newAdmin == address(0)) {\n            revert ERC1967InvalidAdmin(address(0));\n        }\n        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {IERC1967-AdminChanged} event.\n     */\n    function changeAdmin(address newAdmin) internal {\n        emit AdminChanged(getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the EIP1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        if (newBeacon.code.length == 0) {\n            revert ERC1967InvalidBeacon(newBeacon);\n        }\n\n        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n        address beaconImplementation = IBeacon(newBeacon).implementation();\n        if (beaconImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(beaconImplementation);\n        }\n    }\n\n    /**\n     * @dev Change the beacon and trigger a setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-BeaconUpgraded} event.\n     *\n     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n     * efficiency.\n     */\n    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n        _setBeacon(newBeacon);\n        emit BeaconUpgraded(newBeacon);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n     * if an upgrade doesn't perform an initialization call.\n     */\n    function _checkNonPayable() private {\n        if (msg.value > 0) {\n            revert ERC1967NonPayable();\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts5/proxy/Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n    /**\n     * @dev Delegates the current call to `implementation`.\n     *\n     * This function does not return to its internal call site, it will return directly to the external caller.\n     */\n    function _delegate(address implementation) internal virtual {\n        assembly {\n            // Copy msg.data. We take full control of memory in this inline assembly\n            // block because it will not return to Solidity code. We overwrite the\n            // Solidity scratch pad at memory position 0.\n            calldatacopy(0, 0, calldatasize())\n\n            // Call the implementation.\n            // out and outsize are 0 because we don't know the size yet.\n            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n            // Copy the returned data.\n            returndatacopy(0, 0, returndatasize())\n\n            switch result\n            // delegatecall returns 0 on error.\n            case 0 {\n                revert(0, returndatasize())\n            }\n            default {\n                return(0, returndatasize())\n            }\n        }\n    }\n\n    /**\n     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback\n     * function and {_fallback} should delegate.\n     */\n    function _implementation() internal view virtual returns (address);\n\n    /**\n     * @dev Delegates the current call to the address returned by `_implementation()`.\n     *\n     * This function does not return to its internal call site, it will return directly to the external caller.\n     */\n    function _fallback() internal virtual {\n        _delegate(_implementation());\n    }\n\n    /**\n     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n     * function in the contract matches the call data.\n     */\n    fallback() external payable virtual {\n        _fallback();\n    }\n}\n"
      },
      "@openzeppelin/contracts5/proxy/transparent/ProxyAdmin.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.20;\n\nimport {ITransparentUpgradeableProxy} from \"./TransparentUpgradeableProxy.sol\";\nimport {Ownable} from \"../../access/Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n    /**\n     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`\n     * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n     * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n     * If the getter returns `\"5.0.0\"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must\n     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n     * during an upgrade.\n     */\n    string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n    /**\n     * @dev Sets the initial owner who can perform upgrades.\n     */\n    constructor(address initialOwner) Ownable(initialOwner) {}\n\n    /**\n     * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.\n     * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.\n     *\n     * Requirements:\n     *\n     * - This contract must be the admin of `proxy`.\n     * - If `data` is empty, `msg.value` must be zero.\n     */\n    function upgradeAndCall(\n        ITransparentUpgradeableProxy proxy,\n        address implementation,\n        bytes memory data\n    ) public payable virtual onlyOwner {\n        proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n    }\n}\n"
      },
      "@openzeppelin/contracts5/proxy/transparent/TransparentUpgradeableProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC1967Utils} from \"../ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"../ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"../../interfaces/IERC1967.sol\";\nimport {ProxyAdmin} from \"./ProxyAdmin.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n    function upgradeToAndCall(address, bytes calldata) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to\n * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating\n * the proxy admin cannot fallback to the target implementation.\n *\n * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a\n * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to\n * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and\n * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative\n * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a\n * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.\n *\n * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an\n * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be\n * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an\n * undesirable state where the admin slot is different from the actual admin.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the\n * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new\n * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This\n * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n    // An immutable address for the admin to avoid unnecessary SLOADs before each call\n    // at the expense of removing the ability to change the admin once it's set.\n    // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n    // with its own ability to transfer the permissions to another account.\n    address private immutable _admin;\n\n    /**\n     * @dev The proxy caller is the current admin, and can't fallback to the proxy target.\n     */\n    error ProxyDeniedAdminAccess();\n\n    /**\n     * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n     * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n     * {ERC1967Proxy-constructor}.\n     */\n    constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n        _admin = address(new ProxyAdmin(initialOwner));\n        // Set the storage value and emit an event for ERC-1967 compatibility\n        ERC1967Utils.changeAdmin(_proxyAdmin());\n    }\n\n    /**\n     * @dev Returns the admin of this proxy.\n     */\n    function _proxyAdmin() internal virtual returns (address) {\n        return _admin;\n    }\n\n    /**\n     * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n     */\n    function _fallback() internal virtual override {\n        if (msg.sender == _proxyAdmin()) {\n            if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n                revert ProxyDeniedAdminAccess();\n            } else {\n                _dispatchUpgradeToAndCall();\n            }\n        } else {\n            super._fallback();\n        }\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n     *\n     * Requirements:\n     *\n     * - If `data` is empty, `msg.value` must be zero.\n     */\n    function _dispatchUpgradeToAndCall() private {\n        (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n        ERC1967Utils.upgradeToAndCall(newImplementation, data);\n    }\n}\n"
      },
      "@openzeppelin/contracts5/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error AddressInsufficientBalance(address account);\n\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedInnerCall();\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert AddressInsufficientBalance(address(this));\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert FailedInnerCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {FailedInnerCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert AddressInsufficientBalance(address(this));\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n     * unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {FailedInnerCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert FailedInnerCall();\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts5/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "@openzeppelin/contracts5/utils/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n}\n"
      },
      "contracts/interfaces/IBasePolygonZkEVMGlobalExitRoot.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\ninterface IBasePolygonZkEVMGlobalExitRoot {\n    /**\n     * @dev Thrown when the caller is not the allowed contracts\n     */\n    error OnlyAllowedContracts();\n\n    function updateExitRoot(bytes32 newRollupExitRoot) external;\n\n    function globalExitRootMap(\n        bytes32 globalExitRootNum\n    ) external returns (uint256);\n}\n"
      },
      "contracts/interfaces/IPolygonZkEVMBridge.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\ninterface IPolygonZkEVMBridge {\n    /**\n     * @dev Thrown when sender is not the PolygonZkEVM address\n     */\n    error OnlyPolygonZkEVM();\n\n    /**\n     * @dev Thrown when the destination network is invalid\n     */\n    error DestinationNetworkInvalid();\n\n    /**\n     * @dev Thrown when the amount does not match msg.value\n     */\n    error AmountDoesNotMatchMsgValue();\n\n    /**\n     * @dev Thrown when user is bridging tokens and is also sending a value\n     */\n    error MsgValueNotZero();\n\n    /**\n     * @dev Thrown when the Ether transfer on claimAsset fails\n     */\n    error EtherTransferFailed();\n\n    /**\n     * @dev Thrown when the message transaction on claimMessage fails\n     */\n    error MessageFailed();\n\n    /**\n     * @dev Thrown when the global exit root does not exist\n     */\n    error GlobalExitRootInvalid();\n\n    /**\n     * @dev Thrown when the smt proof does not match\n     */\n    error InvalidSmtProof();\n\n    /**\n     * @dev Thrown when an index is already claimed\n     */\n    error AlreadyClaimed();\n\n    /**\n     * @dev Thrown when the owner of permit does not match the sender\n     */\n    error NotValidOwner();\n\n    /**\n     * @dev Thrown when the spender of the permit does not match this contract address\n     */\n    error NotValidSpender();\n\n    /**\n     * @dev Thrown when the amount of the permit does not match\n     */\n    error NotValidAmount();\n\n    /**\n     * @dev Thrown when the permit data contains an invalid signature\n     */\n    error NotValidSignature();\n\n    function bridgeAsset(\n        uint32 destinationNetwork,\n        address destinationAddress,\n        uint256 amount,\n        address token,\n        bool forceUpdateGlobalExitRoot,\n        bytes calldata permitData\n    ) external payable;\n\n    function bridgeMessage(\n        uint32 destinationNetwork,\n        address destinationAddress,\n        bool forceUpdateGlobalExitRoot,\n        bytes calldata metadata\n    ) external payable;\n\n    function claimAsset(\n        bytes32[32] calldata smtProof,\n        uint32 index,\n        bytes32 mainnetExitRoot,\n        bytes32 rollupExitRoot,\n        uint32 originNetwork,\n        address originTokenAddress,\n        uint32 destinationNetwork,\n        address destinationAddress,\n        uint256 amount,\n        bytes calldata metadata\n    ) external;\n\n    function claimMessage(\n        bytes32[32] calldata smtProof,\n        uint32 index,\n        bytes32 mainnetExitRoot,\n        bytes32 rollupExitRoot,\n        uint32 originNetwork,\n        address originAddress,\n        uint32 destinationNetwork,\n        address destinationAddress,\n        uint256 amount,\n        bytes calldata metadata\n    ) external;\n\n    function updateGlobalExitRoot() external;\n\n    function activateEmergencyState() external;\n\n    function deactivateEmergencyState() external;\n}\n"
      },
      "contracts/interfaces/IPolygonZkEVMErrors.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\ninterface IPolygonZkEVMErrors {\n    /**\n     * @dev Thrown when the pending state timeout exceeds the _HALT_AGGREGATION_TIMEOUT\n     */\n    error PendingStateTimeoutExceedHaltAggregationTimeout();\n\n    /**\n     * @dev Thrown when the trusted aggregator timeout exceeds the _HALT_AGGREGATION_TIMEOUT\n     */\n    error TrustedAggregatorTimeoutExceedHaltAggregationTimeout();\n\n    /**\n     * @dev Thrown when the caller is not the admin\n     */\n    error OnlyAdmin();\n\n    /**\n     * @dev Thrown when the caller is not the trusted sequencer\n     */\n    error OnlyTrustedSequencer();\n\n    /**\n     * @dev Thrown when the caller is not the trusted aggregator\n     */\n    error OnlyTrustedAggregator();\n\n    /**\n     * @dev Thrown when attempting to sequence 0 batches\n     */\n    error SequenceZeroBatches();\n\n    /**\n     * @dev Thrown when attempting to sequence or verify more batches than _MAX_VERIFY_BATCHES\n     */\n    error ExceedMaxVerifyBatches();\n\n    /**\n     * @dev Thrown when the forced data does not match\n     */\n    error ForcedDataDoesNotMatch();\n\n    /**\n     * @dev Thrown when the sequenced timestamp is below the forced minimum timestamp\n     */\n    error SequencedTimestampBelowForcedTimestamp();\n\n    /**\n     * @dev Thrown when a global exit root is not zero and does not exist\n     */\n    error GlobalExitRootNotExist();\n\n    /**\n     * @dev Thrown when transactions array length is above _MAX_TRANSACTIONS_BYTE_LENGTH.\n     */\n    error TransactionsLengthAboveMax();\n\n    /**\n     * @dev Thrown when a sequenced timestamp is not inside a correct range.\n     */\n    error SequencedTimestampInvalid();\n\n    /**\n     * @dev Thrown when there are more sequenced force batches than were actually submitted, should be unreachable\n     */\n    error ForceBatchesOverflow();\n\n    /**\n     * @dev Thrown when there are more sequenced force batches than were actually submitted\n     */\n    error TrustedAggregatorTimeoutNotExpired();\n\n    /**\n     * @dev Thrown when attempting to access a pending state that does not exist\n     */\n    error PendingStateDoesNotExist();\n\n    /**\n     * @dev Thrown when the init num batch does not match with the one in the pending state\n     */\n    error InitNumBatchDoesNotMatchPendingState();\n\n    /**\n     * @dev Thrown when the old state root of a certain batch does not exist\n     */\n    error OldStateRootDoesNotExist();\n\n    /**\n     * @dev Thrown when the init verification batch is above the last verification batch\n     */\n    error InitNumBatchAboveLastVerifiedBatch();\n\n    /**\n     * @dev Thrown when the final verification batch is below or equal the last verification batch\n     */\n    error FinalNumBatchBelowLastVerifiedBatch();\n\n    /**\n     * @dev Thrown when the zkproof is not valid\n     */\n    error InvalidProof();\n\n    /**\n     * @dev Thrown when attempting to consolidate a pending state not yet consolidable\n     */\n    error PendingStateNotConsolidable();\n\n    /**\n     * @dev Thrown when attempting to consolidate a pending state that is already consolidated or does not exist\n     */\n    error PendingStateInvalid();\n\n    /**\n     * @dev Thrown when the matic amount is below the necessary matic fee\n     */\n    error NotEnoughMaticAmount();\n\n    /**\n     * @dev Thrown when attempting to sequence a force batch using sequenceForceBatches and the\n     * force timeout did not expire\n     */\n    error ForceBatchTimeoutNotExpired();\n\n    /**\n     * @dev Thrown when attempting to set a new trusted aggregator timeout equal or bigger than current one\n     */\n    error NewTrustedAggregatorTimeoutMustBeLower();\n\n    /**\n     * @dev Thrown when attempting to set a new pending state timeout equal or bigger than current one\n     */\n    error NewPendingStateTimeoutMustBeLower();\n\n    /**\n     * @dev Thrown when attempting to set a new multiplier batch fee in a invalid range of values\n     */\n    error InvalidRangeMultiplierBatchFee();\n\n    /**\n     * @dev Thrown when attempting to set a batch time target in an invalid range of values\n     */\n    error InvalidRangeBatchTimeTarget();\n\n    /**\n     * @dev Thrown when attempting to set a force batch timeout in an invalid range of values\n     */\n    error InvalidRangeForceBatchTimeout();\n\n    /**\n     * @dev Thrown when the caller is not the pending admin\n     */\n    error OnlyPendingAdmin();\n\n    /**\n     * @dev Thrown when the final pending state num is not in a valid range\n     */\n    error FinalPendingStateNumInvalid();\n\n    /**\n     * @dev Thrown when the final num batch does not match with the one in the pending state\n     */\n    error FinalNumBatchDoesNotMatchPendingState();\n\n    /**\n     * @dev Thrown when the stored root matches the new root proving a different state\n     */\n    error StoredRootMustBeDifferentThanNewRoot();\n\n    /**\n     * @dev Thrown when the batch is already verified when attempting to activate the emergency state\n     */\n    error BatchAlreadyVerified();\n\n    /**\n     * @dev Thrown when the batch is not sequenced or not at the end of a sequence when attempting to activate the emergency state\n     */\n    error BatchNotSequencedOrNotSequenceEnd();\n\n    /**\n     * @dev Thrown when the halt timeout is not expired when attempting to activate the emergency state\n     */\n    error HaltTimeoutNotExpired();\n\n    /**\n     * @dev Thrown when the old accumulate input hash does not exist\n     */\n    error OldAccInputHashDoesNotExist();\n\n    /**\n     * @dev Thrown when the new accumulate input hash does not exist\n     */\n    error NewAccInputHashDoesNotExist();\n\n    /**\n     * @dev Thrown when the new state root is not inside prime\n     */\n    error NewStateRootNotInsidePrime();\n\n    /**\n     * @dev Thrown when force batch is not allowed\n     */\n    error ForceBatchNotAllowed();\n\n    /**\n     * @dev Thrown when try to activate force batches when they are already active\n     */\n    error ForceBatchesAlreadyActive();\n}\n"
      },
      "contracts/interfaces/IVerifierRollup.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Define interface verifier\n */\ninterface IVerifierRollup {\n    function verifyProof(\n        bytes32[24] calldata proof,\n        uint256[1] calldata pubSignals\n    ) external view returns (bool);\n}\n"
      },
      "contracts/lib/EmergencyManager.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract helper responsible to manage the emergency state\n */\ncontract EmergencyManager {\n    /**\n     * @dev Thrown when emergency state is active, and the function requires otherwise\n     */\n    error OnlyNotEmergencyState();\n\n    /**\n     * @dev Thrown when emergency state is not active, and the function requires otherwise\n     */\n    error OnlyEmergencyState();\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     */\n    uint256[10] private _gap;\n\n    // Indicates whether the emergency state is active or not\n    bool public isEmergencyState;\n\n    /**\n     * @dev Emitted when emergency state is activated\n     */\n    event EmergencyStateActivated();\n\n    /**\n     * @dev Emitted when emergency state is deactivated\n     */\n    event EmergencyStateDeactivated();\n\n    /**\n     * @notice Only allows a function to be callable if emergency state is unactive\n     */\n    modifier ifNotEmergencyState() {\n        if (isEmergencyState) {\n            revert OnlyNotEmergencyState();\n        }\n        _;\n    }\n\n    /**\n     * @notice Only allows a function to be callable if emergency state is active\n     */\n    modifier ifEmergencyState() {\n        if (!isEmergencyState) {\n            revert OnlyEmergencyState();\n        }\n        _;\n    }\n\n    /**\n     * @notice Activate emergency state\n     */\n    function _activateEmergencyState() internal virtual ifNotEmergencyState {\n        isEmergencyState = true;\n        emit EmergencyStateActivated();\n    }\n\n    /**\n     * @notice Deactivate emergency state\n     */\n    function _deactivateEmergencyState() internal virtual ifEmergencyState {\n        isEmergencyState = false;\n        emit EmergencyStateDeactivated();\n    }\n}\n"
      },
      "contracts/v2/consensus/validium/PolygonValidiumEtrog.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.20;\n\nimport \"../../lib/PolygonRollupBaseEtrog.sol\";\nimport \"../../interfaces/IDataAvailabilityProtocol.sol\";\nimport \"../../interfaces/IPolygonValidium.sol\";\n\n/**\n * Contract responsible for managing the states and the updates of L2 network.\n * There will be a trusted sequencer, which is able to send transactions.\n * Any user can force some transaction and the sequencer will have a timeout to add them in the queue.\n * The sequenced state is deterministic and can be precalculated before it's actually verified by a zkProof.\n * The aggregators will be able to verify the sequenced state with zkProofs and therefore make available the withdrawals from L2 network.\n * To enter and exit of the L2 network will be used a PolygonZkEVMBridge smart contract that will be deployed in both networks.\n * It is advised to use timelocks for the admin address in case of Validium since if can change the dataAvailabilityProtocol\n */\ncontract PolygonValidiumEtrog is PolygonRollupBaseEtrog, IPolygonValidium {\n    using SafeERC20Upgradeable for IERC20Upgradeable;\n\n    /**\n     * @notice Struct which will be used to call sequenceBatches\n     * @param transactionsHash keccak256 hash of the L2 ethereum transactions EIP-155 or pre-EIP-155 with signature:\n     * EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data, chainid, 0, 0,) || v || r || s\n     * pre-EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data) || v || r || s\n     * @param forcedGlobalExitRoot Global exit root, empty when sequencing a non forced batch\n     * @param forcedTimestamp Minimum timestamp of the force batch data, empty when sequencing a non forced batch\n     * @param forcedBlockHashL1 blockHash snapshot of the force batch data, empty when sequencing a non forced batch\n     */\n    struct ValidiumBatchData {\n        bytes32 transactionsHash;\n        bytes32 forcedGlobalExitRoot;\n        uint64 forcedTimestamp;\n        bytes32 forcedBlockHashL1;\n    }\n\n    // Data Availability Protocol Address\n    IDataAvailabilityProtocol public dataAvailabilityProtocol;\n\n    // Indicates if sequence with data avialability is allowed\n    // This allow the sequencer to post the data and skip the Data comittee\n    bool public isSequenceWithDataAvailabilityAllowed;\n\n    /**\n     * @dev Emitted when the admin updates the data availability protocol\n     */\n    event SetDataAvailabilityProtocol(address newDataAvailabilityProtocol);\n\n    /**\n     * @dev Emitted when switch the ability to sequence with data availability\n     */\n    event SwitchSequenceWithDataAvailability();\n\n    /**\n     * @param _globalExitRootManager Global exit root manager address\n     * @param _pol POL token address\n     * @param _bridgeAddress Bridge address\n     * @param _rollupManager Global exit root manager address\n     */\n    constructor(\n        IPolygonZkEVMGlobalExitRootV2 _globalExitRootManager,\n        IERC20Upgradeable _pol,\n        IPolygonZkEVMBridgeV2 _bridgeAddress,\n        PolygonRollupManager _rollupManager\n    )\n        PolygonRollupBaseEtrog(\n            _globalExitRootManager,\n            _pol,\n            _bridgeAddress,\n            _rollupManager\n        )\n    {}\n\n    /////////////////////////////////////\n    // Sequence/Verify batches functions\n    ////////////////////////////////////\n\n    /**\n     * @notice Allows a sequencer to send multiple batches\n     * @param batches Struct array which holds the necessary data to append new batches to the sequence\n     * @param maxSequenceTimestamp Max timestamp of the sequence. This timestamp must be inside a safety range (actual + 36 seconds).\n     * This timestamp should be equal or higher of the last block inside the sequence, otherwise this batch will be invalidated by circuit.\n     * @param initSequencedBatch This parameter must match the current last batch sequenced.\n     * This will be a protection for the sequencer to avoid sending undesired data\n     * @param l2Coinbase Address that will receive the fees from L2\n     * @param dataAvailabilityMessage Byte array containing the signatures and all the addresses of the committee in ascending order\n     * [signature 0, ..., signature requiredAmountOfSignatures -1, address 0, ... address N]\n     * note that each ECDSA signatures are used, therefore each one must be 65 bytes\n     * note Pol is not a reentrant token\n     */\n    function sequenceBatchesValidium(\n        ValidiumBatchData[] calldata batches,\n        uint64 maxSequenceTimestamp,\n        uint64 initSequencedBatch,\n        address l2Coinbase,\n        bytes calldata dataAvailabilityMessage\n    ) external onlyTrustedSequencer {\n        uint256 batchesNum = batches.length;\n        if (batchesNum == 0) {\n            revert SequenceZeroBatches();\n        }\n\n        if (batchesNum > _MAX_VERIFY_BATCHES) {\n            revert ExceedMaxVerifyBatches();\n        }\n\n        // Check max sequence timestamp inside of range\n        if (\n            uint256(maxSequenceTimestamp) > (block.timestamp + TIMESTAMP_RANGE)\n        ) {\n            revert MaxTimestampSequenceInvalid();\n        }\n\n        // Update global exit root if there are new deposits\n        bridgeAddress.updateGlobalExitRoot();\n\n        // Get global batch variables\n        bytes32 l1InfoRoot = globalExitRootManager.getRoot();\n\n        // Store storage variables in memory, to save gas, because will be overrided multiple times\n        uint64 currentLastForceBatchSequenced = lastForceBatchSequenced;\n        bytes32 currentAccInputHash = lastAccInputHash;\n\n        // Store in a temporal variable, for avoid access again the storage slot\n        uint64 initLastForceBatchSequenced = currentLastForceBatchSequenced;\n\n        // Accumulated sequenced transaction hash to verify them afterward against the dataAvailabilityProtocol\n        bytes32 accumulatedNonForcedTransactionsHash = bytes32(0);\n\n        for (uint256 i = 0; i < batchesNum; i++) {\n            // Load current sequence\n            ValidiumBatchData memory currentBatch = batches[i];\n\n            // Check if it's a forced batch\n            if (currentBatch.forcedTimestamp > 0) {\n                currentLastForceBatchSequenced++;\n\n                // Check forced data matches\n                bytes32 hashedForcedBatchData = keccak256(\n                    abi.encodePacked(\n                        currentBatch.transactionsHash,\n                        currentBatch.forcedGlobalExitRoot,\n                        currentBatch.forcedTimestamp,\n                        currentBatch.forcedBlockHashL1\n                    )\n                );\n\n                if (\n                    hashedForcedBatchData !=\n                    forcedBatches[currentLastForceBatchSequenced]\n                ) {\n                    revert ForcedDataDoesNotMatch();\n                }\n\n                // Calculate next accumulated input hash\n                currentAccInputHash = keccak256(\n                    abi.encodePacked(\n                        currentAccInputHash,\n                        currentBatch.transactionsHash,\n                        currentBatch.forcedGlobalExitRoot,\n                        currentBatch.forcedTimestamp,\n                        l2Coinbase,\n                        currentBatch.forcedBlockHashL1\n                    )\n                );\n\n                // Delete forceBatch data since won't be used anymore\n                delete forcedBatches[currentLastForceBatchSequenced];\n            } else {\n                // Accumulate non forced transactions hash\n                accumulatedNonForcedTransactionsHash = keccak256(\n                    abi.encodePacked(\n                        accumulatedNonForcedTransactionsHash,\n                        currentBatch.transactionsHash\n                    )\n                );\n\n                // Note that forcedGlobalExitRoot and forcedBlockHashL1 remain unused and unchecked in this path\n                // The synchronizer should be aware of that\n\n                // Calculate next accumulated input hash\n                currentAccInputHash = keccak256(\n                    abi.encodePacked(\n                        currentAccInputHash,\n                        currentBatch.transactionsHash,\n                        l1InfoRoot,\n                        maxSequenceTimestamp,\n                        l2Coinbase,\n                        bytes32(0)\n                    )\n                );\n            }\n        }\n\n        // Sanity check, should be unreachable\n        if (currentLastForceBatchSequenced > lastForceBatch) {\n            revert ForceBatchesOverflow();\n        }\n\n        // Store back the storage variables\n        lastAccInputHash = currentAccInputHash;\n\n        uint256 nonForcedBatchesSequenced = batchesNum;\n\n        // Check if there has been forced batches\n        if (currentLastForceBatchSequenced != initLastForceBatchSequenced) {\n            uint64 forcedBatchesSequenced = currentLastForceBatchSequenced -\n                initLastForceBatchSequenced;\n            // substract forced batches\n            nonForcedBatchesSequenced -= forcedBatchesSequenced;\n\n            // Transfer pol for every forced batch submitted\n            pol.safeTransfer(\n                address(rollupManager),\n                calculatePolPerForceBatch() * (forcedBatchesSequenced)\n            );\n\n            // Store new last force batch sequenced\n            lastForceBatchSequenced = currentLastForceBatchSequenced;\n        }\n\n        // Pay collateral for every non-forced batch submitted\n        if (nonForcedBatchesSequenced != 0) {\n            pol.safeTransferFrom(\n                msg.sender,\n                address(rollupManager),\n                rollupManager.getBatchFee() * nonForcedBatchesSequenced\n            );\n\n            // Validate that the data availability protocol accepts the dataAvailabilityMessage\n            // note This is a view function, so there's not much risk even if this contract was vulnerable to reentrant attacks\n            dataAvailabilityProtocol.verifyMessage(\n                accumulatedNonForcedTransactionsHash,\n                dataAvailabilityMessage\n            );\n        }\n\n        uint64 currentBatchSequenced = rollupManager.onSequenceBatches(\n            uint64(batchesNum),\n            currentAccInputHash\n        );\n\n        // Check init sequenced batch\n        if (\n            initSequencedBatch != (currentBatchSequenced - uint64(batchesNum))\n        ) {\n            revert InitSequencedBatchDoesNotMatch();\n        }\n\n        emit SequenceBatches(currentBatchSequenced, l1InfoRoot);\n    }\n\n    /**\n     * @notice Allows a sequencer to send multiple batches\n     * @param batches Struct array which holds the necessary data to append new batches to the sequence\n     * @param maxSequenceTimestamp Max timestamp of the sequence. This timestamp must be inside a safety range (actual + 36 seconds).\n     * This timestamp should be equal or higher of the last block inside the sequence, otherwise this batch will be invalidated by circuit.\n     * @param initSequencedBatch This parameter must match the current last batch sequenced.\n     * This will be a protection for the sequencer to avoid sending undesired data\n     * @param l2Coinbase Address that will receive the fees from L2\n     * note Pol is not a reentrant token\n     */\n    function sequenceBatches(\n        BatchData[] calldata batches,\n        uint64 maxSequenceTimestamp,\n        uint64 initSequencedBatch,\n        address l2Coinbase\n    ) public override {\n        if (!isSequenceWithDataAvailabilityAllowed) {\n            revert SequenceWithDataAvailabilityNotAllowed();\n        }\n        super.sequenceBatches(\n            batches,\n            maxSequenceTimestamp,\n            initSequencedBatch,\n            l2Coinbase\n        );\n    }\n\n    //////////////////\n    // admin functions\n    //////////////////\n\n    /**\n     * @notice Allow the admin to set a new data availability protocol\n     * @param newDataAvailabilityProtocol Address of the new data availability protocol\n     */\n    function setDataAvailabilityProtocol(\n        IDataAvailabilityProtocol newDataAvailabilityProtocol\n    ) external onlyAdmin {\n        dataAvailabilityProtocol = newDataAvailabilityProtocol;\n\n        emit SetDataAvailabilityProtocol(address(newDataAvailabilityProtocol));\n    }\n\n    /**\n     * @notice Allow the admin to switch the sequence with data availability\n     * @param newIsSequenceWithDataAvailabilityAllowed Boolean to switch\n     */\n    function switchSequenceWithDataAvailability(\n        bool newIsSequenceWithDataAvailabilityAllowed\n    ) external onlyAdmin {\n        if (\n            newIsSequenceWithDataAvailabilityAllowed ==\n            isSequenceWithDataAvailabilityAllowed\n        ) {\n            revert SwitchToSameValue();\n        }\n        isSequenceWithDataAvailabilityAllowed = newIsSequenceWithDataAvailabilityAllowed;\n        emit SwitchSequenceWithDataAvailability();\n    }\n}\n"
      },
      "contracts/v2/consensus/zkEVM/PolygonZkEVMExistentEtrog.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.20;\n\nimport \"../../lib/PolygonRollupBaseEtrog.sol\";\n\n/**\n * Contract responsible for managing the states and the updates of L2 network.\n * There will be a trusted sequencer, which is able to send transactions.\n * Any user can force some transaction and the sequencer will have a timeout to add them in the queue.\n * The sequenced state is deterministic and can be precalculated before it's actually verified by a zkProof.\n * The aggregators will be able to verify the sequenced state with zkProofs and therefore make available the withdrawals from L2 network.\n * To enter and exit of the L2 network will be used a PolygonZkEVMBridge smart contract that will be deployed in both networks.\n */\ncontract PolygonZkEVMExistentEtrog is PolygonRollupBaseEtrog {\n    // Transaction that will be injected as a forced transaction, to setup the timestamp on the state root, we just need a well encoded RLP transaction\n    // It's ok if the transaction is not processable\n    /* Encoded transaction:\n      {\n        \"from\": \"0x617b3a3528F9cDd6630fd3301B9c8911F7Bf063D\",\n        \"to\": \"0x4d5Cf5032B2a844602278b01199ED191A86c93ff\",\n        \"nonce\": 42,\n        \"data\": \"0x\",\n        \"value\": \"0\",\n        \"gasLimit\": 0,\n        \"gasPrice\": \"0\",\n        \"chainId\": 4242,\n        \"overwrite\": {\n          \"v\": \"0x1b\",\n          \"r\": \"0x00000000000000000000000000000000000000000000000000000005ca1ab1e0\",\n          \"s\": \"0x00000000000000000000000000000000000000000000000000000005ca1ab1e0\"\n        }\n      }\n    */\n    bytes public constant SET_UP_ETROG_TX =\n        hex\"df2a8080944d5cf5032b2a844602278b01199ed191a86c93ff8080821092808000000000000000000000000000000000000000000000000000000005ca1ab1e000000000000000000000000000000000000000000000000000000005ca1ab1e01bff\";\n\n    /**\n     * @dev Emitted when the system is updated to a etrog using this contract, contain the set up etrog transaction\n     */\n    event UpdateEtrogSequence(\n        uint64 numBatch,\n        bytes transactions,\n        bytes32 lastGlobalExitRoot,\n        address sequencer\n    );\n\n    /**\n     * @param _globalExitRootManager Global exit root manager address\n     * @param _pol POL token address\n     * @param _bridgeAddress Bridge address\n     * @param _rollupManager Global exit root manager address\n     */\n    constructor(\n        IPolygonZkEVMGlobalExitRootV2 _globalExitRootManager,\n        IERC20Upgradeable _pol,\n        IPolygonZkEVMBridgeV2 _bridgeAddress,\n        PolygonRollupManager _rollupManager\n    )\n        PolygonRollupBaseEtrog(\n            _globalExitRootManager,\n            _pol,\n            _bridgeAddress,\n            _rollupManager\n        )\n    {}\n\n    /**\n     * note This initializer will be called instead of the PolygonRollupBase\n     * This is a especial initializer since the zkEVM it's an already created network\n     * @param _admin Admin address\n     * @param _trustedSequencer Trusted sequencer address\n     * @param _trustedSequencerURL Trusted sequencer URL\n     * @param _networkName L2 network name\n     * @param _lastAccInputHash Acc input hash\n     */\n    function initializeUpgrade(\n        address _admin,\n        address _trustedSequencer,\n        string memory _trustedSequencerURL,\n        string memory _networkName,\n        bytes32 _lastAccInputHash\n    ) external onlyRollupManager initializer {\n        // Set up etrog Tx\n        bytes memory transaction = SET_UP_ETROG_TX;\n        bytes32 currentTransactionsHash = keccak256(transaction);\n\n        // Get current timestamp and global exit root\n        uint64 currentTimestamp = uint64(block.timestamp);\n        bytes32 lastGlobalExitRoot = globalExitRootManager\n            .getLastGlobalExitRoot();\n\n        // Add the transaction to the sequence as if it was a force transaction\n        bytes32 newAccInputHash = keccak256(\n            abi.encodePacked(\n                _lastAccInputHash, // Last acc Input hash\n                currentTransactionsHash,\n                lastGlobalExitRoot, // Global exit root\n                currentTimestamp,\n                _trustedSequencer,\n                blockhash(block.number - 1)\n            )\n        );\n\n        // Set acumulated input hash\n        lastAccInputHash = newAccInputHash;\n\n        uint64 currentBatchSequenced = rollupManager.onSequenceBatches(\n            uint64(1), // num total batches\n            newAccInputHash\n        );\n\n        // Set zkEVM variables\n        admin = _admin;\n        trustedSequencer = _trustedSequencer;\n\n        trustedSequencerURL = _trustedSequencerURL;\n        networkName = _networkName;\n\n        forceBatchAddress = _admin;\n\n        // Constant variables\n        forceBatchTimeout = 5 days;\n\n        // Both gasTokenAddress and gasTokenNetwork are 0, since it uses ether as gas token\n        // Therefore is not necessary to set the variables\n\n        emit UpdateEtrogSequence(\n            currentBatchSequenced,\n            transaction,\n            lastGlobalExitRoot,\n            _trustedSequencer\n        );\n    }\n}\n"
      },
      "contracts/v2/interfaces/IDataAvailabilityProtocol.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\ninterface IDataAvailabilityProtocol {\n    function getProcotolName() external view returns (string memory);\n\n    function verifyMessage(\n        bytes32 hash,\n        bytes calldata dataAvailabilityMessage\n    ) external view;\n}\n"
      },
      "contracts/v2/interfaces/IPolygonRollupBase.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\ninterface IPolygonRollupBase {\n    function initialize(\n        address _admin,\n        address sequencer,\n        uint32 networkID,\n        address gasTokenAddress,\n        string memory sequencerURL,\n        string memory _networkName\n    ) external;\n\n    function onVerifyBatches(\n        uint64 lastVerifiedBatch,\n        bytes32 newStateRoot,\n        address aggregator\n    ) external;\n}\n"
      },
      "contracts/v2/interfaces/IPolygonRollupManager.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\ninterface IPolygonRollupManager {\n    /**\n     * @dev Thrown when sender is not the PolygonZkEVM address\n     */\n    error UpdateToSameRollupTypeID();\n\n    /**\n     * @dev Thrown when sender is not the PolygonZkEVM address\n     */\n    error RollupMustExist();\n\n    /**\n     * @dev Thrown when sender is not the PolygonZkEVM address\n     */\n    error SenderMustBeRollup();\n\n    /**\n     * @dev Thrown when sender is not the PolygonZkEVM address\n     */\n    error TrustedAggregatorTimeoutNotExpired();\n\n    /**\n     * @dev Thrown when sender is not the PolygonZkEVM address\n     */\n    error ExceedMaxVerifyBatches();\n\n    /**\n     * @dev Thrown when attempting to access a pending state that does not exist\n     */\n    error PendingStateDoesNotExist();\n\n    /**\n     * @dev Thrown when the init num batch does not match with the one in the pending state\n     */\n    error InitNumBatchDoesNotMatchPendingState();\n\n    /**\n     * @dev Thrown when the old state root of a certain batch does not exist\n     */\n    error OldStateRootDoesNotExist();\n\n    /**\n     * @dev Thrown when the init verification batch is above the last verification batch\n     */\n    error InitNumBatchAboveLastVerifiedBatch();\n\n    /**\n     * @dev Thrown when the final verification batch is below or equal the last verification batch\n     */\n    error FinalNumBatchBelowLastVerifiedBatch();\n\n    /**\n     * @dev Thrown when the zkproof is not valid\n     */\n    error InvalidProof();\n\n    /**\n     * @dev Thrown when attempting to consolidate a pending state not yet consolidable\n     */\n    error PendingStateNotConsolidable();\n\n    /**\n     * @dev Thrown when attempting to consolidate a pending state that is already consolidated or does not exist\n     */\n    error PendingStateInvalid();\n\n    /**\n     * @dev Thrown when the new accumulate input hash does not exist\n     */\n    error NewAccInputHashDoesNotExist();\n\n    /**\n     * @dev Thrown when the new state root is not inside prime\n     */\n    error NewStateRootNotInsidePrime();\n\n    /**\n     * @dev Thrown when the final pending state num is not in a valid range\n     */\n    error FinalPendingStateNumInvalid();\n\n    /**\n     * @dev Thrown when the final num batch does not match with the one in the pending state\n     */\n    error FinalNumBatchDoesNotMatchPendingState();\n\n    /**\n     * @dev Thrown when the stored root matches the new root proving a different state\n     */\n    error StoredRootMustBeDifferentThanNewRoot();\n\n    /**\n     * @dev Thrown when the halt timeout is not expired when attempting to activate the emergency state\n     */\n    error HaltTimeoutNotExpired();\n\n    /**\n     * @dev Thrown when the old accumulate input hash does not exist\n     */\n    error OldAccInputHashDoesNotExist();\n\n    /**\n     * @dev Thrown when attempting to set a new trusted aggregator timeout equal or bigger than current one\n     */\n    error NewTrustedAggregatorTimeoutMustBeLower();\n\n    /**\n     * @dev Thrown when attempting to set a new pending state timeout equal or bigger than current one\n     */\n    error NewPendingStateTimeoutMustBeLower();\n\n    /**\n     * @dev Thrown when attempting to set a new multiplier batch fee in a invalid range of values\n     */\n    error InvalidRangeMultiplierBatchFee();\n\n    /**\n     * @dev Thrown when attempting to set a batch time target in an invalid range of values\n     */\n    error InvalidRangeBatchTimeTarget();\n\n    /**\n     * @dev Thrown when the caller is not the pending admin\n     */\n    error ChainIDAlreadyExist();\n\n    /**\n     * @dev Thrown when the caller is not the pending admin\n     */\n    error MustSequenceSomeBatch();\n\n    /**\n     * @dev When a rollup type does not exist\n     */\n    error RollupTypeDoesNotExist();\n\n    /**\n     * @dev When a rollup type does not exist\n     */\n    error RollupTypeObsolete();\n\n    /**\n     * @dev When a rollup type does not exist\n     */\n    error InitBatchMustMatchCurrentForkID();\n\n    /**\n     * @dev When a rollup type does not exist\n     */\n    error UpdateNotCompatible();\n\n    /**\n     * @dev When a rollup type does not exist\n     */\n    error BatchFeeOutOfRange();\n\n    /**\n     * @dev When a rollup type does not exist\n     */\n    error AllzkEVMSequencedBatchesMustBeVerified();\n\n    /**\n     * @dev When adding an existing rollup where the rollup address already was added\n     */\n    error RollupAddressAlreadyExist();\n}\n"
      },
      "contracts/v2/interfaces/IPolygonValidium.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\ninterface IPolygonValidium {\n    /**\n     * @dev Thrown when try to activate force batches when they are already active\n     */\n    error SequenceWithDataAvailabilityNotAllowed();\n\n    /**\n     * @dev Thrown when try to switch SequenceWithDataAvailability to the same value\n     */\n    error SwitchToSameValue();\n}\n"
      },
      "contracts/v2/interfaces/IPolygonZkEVMBridgeV2.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\nimport \"../../interfaces/IBasePolygonZkEVMGlobalExitRoot.sol\";\n\ninterface IPolygonZkEVMBridgeV2 {\n    /**\n     * @dev Thrown when the destination network is invalid\n     */\n    error DestinationNetworkInvalid();\n\n    /**\n     * @dev Thrown when the amount does not match msg.value\n     */\n    error AmountDoesNotMatchMsgValue();\n\n    /**\n     * @dev Thrown when user is bridging tokens and is also sending a value\n     */\n    error MsgValueNotZero();\n\n    /**\n     * @dev Thrown when the Ether transfer on claimAsset fails\n     */\n    error EtherTransferFailed();\n\n    /**\n     * @dev Thrown when the message transaction on claimMessage fails\n     */\n    error MessageFailed();\n\n    /**\n     * @dev Thrown when the global exit root does not exist\n     */\n    error GlobalExitRootInvalid();\n\n    /**\n     * @dev Thrown when the smt proof does not match\n     */\n    error InvalidSmtProof();\n\n    /**\n     * @dev Thrown when an index is already claimed\n     */\n    error AlreadyClaimed();\n\n    /**\n     * @dev Thrown when the owner of permit does not match the sender\n     */\n    error NotValidOwner();\n\n    /**\n     * @dev Thrown when the spender of the permit does not match this contract address\n     */\n    error NotValidSpender();\n\n    /**\n     * @dev Thrown when the amount of the permit does not match\n     */\n    error NotValidAmount();\n\n    /**\n     * @dev Thrown when the permit data contains an invalid signature\n     */\n    error NotValidSignature();\n\n    /**\n     * @dev Thrown when sender is not the rollup manager\n     */\n    error OnlyRollupManager();\n\n    /**\n     * @dev Thrown when the permit data contains an invalid signature\n     */\n    error NativeTokenIsEther();\n\n    /**\n     * @dev Thrown when the permit data contains an invalid signature\n     */\n    error NoValueInMessagesOnGasTokenNetworks();\n\n    /**\n     * @dev Thrown when the permit data contains an invalid signature\n     */\n    error GasTokenNetworkMustBeZeroOnEther();\n\n    /**\n     * @dev Thrown when the wrapped token deployment fails\n     */\n    error FailedTokenWrappedDeployment();\n\n    function wrappedTokenToTokenInfo(\n        address destinationAddress\n    ) external view returns (uint32, address);\n\n    function updateGlobalExitRoot() external;\n\n    function activateEmergencyState() external;\n\n    function deactivateEmergencyState() external;\n\n    function bridgeAsset(\n        uint32 destinationNetwork,\n        address destinationAddress,\n        uint256 amount,\n        address token,\n        bool forceUpdateGlobalExitRoot,\n        bytes calldata permitData\n    ) external payable;\n\n    function bridgeMessage(\n        uint32 destinationNetwork,\n        address destinationAddress,\n        bool forceUpdateGlobalExitRoot,\n        bytes calldata metadata\n    ) external payable;\n\n    function bridgeMessageWETH(\n        uint32 destinationNetwork,\n        address destinationAddress,\n        uint256 amountWETH,\n        bool forceUpdateGlobalExitRoot,\n        bytes calldata metadata\n    ) external;\n\n    function claimAsset(\n        bytes32[32] calldata smtProofLocalExitRoot,\n        bytes32[32] calldata smtProofRollupExitRoot,\n        uint256 globalIndex,\n        bytes32 mainnetExitRoot,\n        bytes32 rollupExitRoot,\n        uint32 originNetwork,\n        address originTokenAddress,\n        uint32 destinationNetwork,\n        address destinationAddress,\n        uint256 amount,\n        bytes calldata metadata\n    ) external;\n\n    function claimMessage(\n        bytes32[32] calldata smtProofLocalExitRoot,\n        bytes32[32] calldata smtProofRollupExitRoot,\n        uint256 globalIndex,\n        bytes32 mainnetExitRoot,\n        bytes32 rollupExitRoot,\n        uint32 originNetwork,\n        address originAddress,\n        uint32 destinationNetwork,\n        address destinationAddress,\n        uint256 amount,\n        bytes calldata metadata\n    ) external;\n\n    function initialize(\n        uint32 _networkID,\n        address _gasTokenAddress,\n        uint32 _gasTokenNetwork,\n        IBasePolygonZkEVMGlobalExitRoot _globalExitRootManager,\n        address _polygonRollupManager,\n        bytes memory _gasTokenMetadata\n    ) external;\n\n    function getTokenMetadata(\n        address token\n    ) external view returns (bytes memory);\n}\n"
      },
      "contracts/v2/interfaces/IPolygonZkEVMGlobalExitRootV2.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\nimport \"../../interfaces/IBasePolygonZkEVMGlobalExitRoot.sol\";\n\ninterface IPolygonZkEVMGlobalExitRootV2 is IBasePolygonZkEVMGlobalExitRoot {\n    function getLastGlobalExitRoot() external view returns (bytes32);\n\n    function getRoot() external view returns (bytes32);\n}\n"
      },
      "contracts/v2/interfaces/IPolygonZkEVMVEtrogErrors.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\nimport \"../../interfaces/IPolygonZkEVMErrors.sol\";\n\ninterface IPolygonZkEVMVEtrogErrors is IPolygonZkEVMErrors {\n    /**\n     * @dev Thrown when the caller is not the trusted sequencer\n     */\n    error OnlyRollupManager();\n\n    /**\n     * @dev Thrown when the caller is not the trusted sequencer\n     */\n    error NotEnoughPOLAmount();\n\n    /**\n     * @dev Thrown when the caller is not the trusted sequencer\n     */\n    error InvalidInitializeTransaction();\n\n    /**\n     * @dev Thrown when the caller is not the trusted sequencer\n     */\n    error GasTokenNetworkMustBeZeroOnEther();\n\n    /**\n     * @dev Thrown when the try to initialize with a gas token with huge metadata\n     */\n    error HugeTokenMetadataNotSupported();\n\n    /**\n     * @dev Thrown when trying force a batch during emergency state\n     */\n    error ForceBatchesNotAllowedOnEmergencyState();\n\n    /**\n     * @dev Thrown when the try to sequence force batches before the halt timeout period\n     */\n    error HaltTimeoutNotExpiredAfterEmergencyState();\n\n    /**\n     * @dev Thrown when the try to update the force batch address once is set to address(0)\n     */\n    error ForceBatchesDecentralized();\n\n    /**\n     * @dev Thrown when the last sequenced batch nmber does not match the init sequeced batch number\n     */\n    error InitSequencedBatchDoesNotMatch();\n\n    /**\n     * @dev Thrown when the max timestamp is out of range\n     */\n    error MaxTimestampSequenceInvalid();\n}\n"
      },
      "contracts/v2/lib/LegacyZKEVMStateVariables.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\n\n/**\n * Since the current contract of PolygonZkEVM will be upgraded to a PolygonRollupManager there's defined\n * all the legacy public variables in order to not use previous used storage slots\n * The variables will be used by the RollupManager only for initialize the zkEVM inside the initializer function\n */\ncontract LegacyZKEVMStateVariables {\n    /**\n     * @notice Struct which will be stored for every batch sequence\n     * @param accInputHash Hash chain that contains all the information to process a batch:\n     * Before etrog: keccak256(bytes32 oldAccInputHash, keccak256(bytes transactions), bytes32 globalExitRoot, uint64 timestamp, address seqAddress)\n     * Etrog: keccak256(bytes32 oldAccInputHash, keccak256(bytes transactions), bytes32 l1InfoRoot/forcedGlobalExitRoot, uint64 currentTimestamp/forcedTimestamp, address l2Coinbase, bytes32 0/forcedBlockHashL1)\n     * @param sequencedTimestamp Sequenced timestamp\n     * @param previousLastBatchSequenced Previous last batch sequenced before the current one, this is used to properly calculate the fees\n     */\n    struct SequencedBatchData {\n        bytes32 accInputHash;\n        uint64 sequencedTimestamp;\n        uint64 previousLastBatchSequenced;\n    }\n\n    /**\n     * @notice Struct to store the pending states\n     * Pending state will be an intermediary state, that after a timeout can be consolidated, which means that will be added\n     * to the state root mapping, and the global exit root will be updated\n     * This is a protection mechanism against soundness attacks, that will be turned off in the future\n     * @param timestamp Timestamp where the pending state is added to the queue\n     * @param lastVerifiedBatch Last batch verified batch of this pending state\n     * @param exitRoot Pending exit root\n     * @param stateRoot Pending state root\n     */\n    struct PendingState {\n        uint64 timestamp;\n        uint64 lastVerifiedBatch;\n        bytes32 exitRoot;\n        bytes32 stateRoot;\n    }\n\n    // Time target of the verification of a batch\n    // Adaptatly the batchFee will be updated to achieve this target\n    /// @custom:oz-renamed-from verifyBatchTimeTarget\n    uint64 internal _legacyVerifyBatchTimeTarget;\n\n    // Batch fee multiplier with 3 decimals that goes from 1000 - 1023\n    /// @custom:oz-renamed-from multiplierBatchFee\n    uint16 internal _legacyMultiplierBatchFee;\n\n    // Trusted sequencer address\n    /// @custom:oz-renamed-from trustedSequencer\n    address internal _legacyTrustedSequencer;\n\n    // Current matic fee per batch sequenced\n    /// @custom:oz-renamed-from batchFee\n    uint256 internal _legacyBatchFee;\n\n    // Queue of forced batches with their associated data\n    // ForceBatchNum --> hashedForcedBatchData\n    // hashedForcedBatchData: hash containing the necessary information to force a batch:\n    // keccak256(keccak256(bytes transactions), bytes32 globalExitRoot, unint64 minForcedTimestamp)\n    /// @custom:oz-renamed-from forcedBatches\n    mapping(uint64 => bytes32) internal _legacyForcedBatches;\n\n    // Queue of batches that defines the virtual state\n    // SequenceBatchNum --> SequencedBatchData\n    /// @custom:oz-renamed-from sequencedBatches\n    mapping(uint64 => SequencedBatchData) internal _legacySequencedBatches;\n\n    // Last sequenced timestamp\n    /// @custom:oz-renamed-from lastTimestamp\n    uint64 internal _legacyLastTimestamp;\n\n    // Last batch sent by the sequencers\n    /// @custom:oz-renamed-from lastBatchSequenced\n    uint64 internal _legacylastBatchSequenced;\n\n    // Last forced batch included in the sequence\n    /// @custom:oz-renamed-from lastForceBatchSequenced\n    uint64 internal _legacyLastForceBatchSequenced;\n\n    // Last forced batch\n    /// @custom:oz-renamed-from lastForceBatch\n    uint64 internal _legacyLastForceBatch;\n\n    // Last batch verified by the aggregators\n    /// @custom:oz-renamed-from lastVerifiedBatch\n    uint64 internal _legacyLastVerifiedBatch;\n\n    // Trusted aggregator address\n    /// @custom:oz-renamed-from trustedAggregator\n    address internal _legacyTrustedAggregator;\n\n    // State root mapping\n    // BatchNum --> state root\n    /// @custom:oz-renamed-from batchNumToStateRoot\n    mapping(uint64 => bytes32) internal _legacyBatchNumToStateRoot;\n\n    // Trusted sequencer URL\n    /// @custom:oz-renamed-from trustedSequencerURL\n    string internal _legacyTrustedSequencerURL;\n\n    // L2 network name\n    /// @custom:oz-renamed-from networkName\n    string internal _legacyNetworkName;\n\n    // Pending state mapping\n    // pendingStateNumber --> PendingState\n    /// @custom:oz-renamed-from pendingStateTransitions\n    mapping(uint256 => PendingState) internal _legacyPendingStateTransitions;\n\n    // Last pending state\n    /// @custom:oz-renamed-from lastPendingState\n    uint64 internal _legacyLastPendingState;\n\n    // Last pending state consolidated\n    /// @custom:oz-renamed-from lastPendingStateConsolidated\n    uint64 internal _legacyLastPendingStateConsolidated;\n\n    // Once a pending state exceeds this timeout it can be consolidated\n    /// @custom:oz-renamed-from pendingStateTimeout\n    uint64 internal _legacyPendingStateTimeout;\n\n    // Trusted aggregator timeout, if a sequence is not verified in this time frame,\n    // everyone can verify that sequence\n    /// @custom:oz-renamed-from trustedAggregatorTimeout\n    uint64 internal _legacyTrustedAggregatorTimeout;\n\n    // Address that will be able to adjust contract parameters or stop the emergency state\n    /// @custom:oz-renamed-from admin\n    address internal _legacyAdmin;\n\n    // This account will be able to accept the admin role\n    /// @custom:oz-renamed-from pendingAdmin\n    address internal _legacyPendingAdmin;\n\n    // Force batch timeout\n    /// @custom:oz-renamed-from forceBatchTimeout\n    uint64 internal _legacyForceBatchTimeout;\n\n    // Indicates if forced batches are disallowed\n    /// @custom:oz-renamed-from isForcedBatchDisallowed\n    bool internal _legacyIsForcedBatchDisallowed;\n\n    // Indicates the current version\n    /// @custom:oz-renamed-from version\n    uint256 internal _legacyVersion;\n\n    // Last batch verified before the last upgrade\n    /// @custom:oz-renamed-from lastVerifiedBatchBeforeUpgrade\n    uint256 internal _legacyLastVerifiedBatchBeforeUpgrade;\n}\n"
      },
      "contracts/v2/lib/PolygonAccessControlUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.20;\n\nimport \"@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract AccessControlUpgradeable from Openzeppelin with the following modifications:\n * - Delete ERC165Upgradeable dependencies, which is not important to our contract and save us the \"gap\"\n * variables and let us have consistent storage\n * - Add the legacy Owner variable, to be consistent with the previous one\n * - Add custom errors\n * - Replace _msgSender() with msg.sender\n */\nabstract contract PolygonAccessControlUpgradeable is\n    Initializable,\n    ContextUpgradeable,\n    IAccessControlUpgradeable\n{\n    function __AccessControl_init() internal onlyInitializing {}\n\n    // Legacy variable\n    /// @custom:oz-renamed-from _owner\n    address internal _legacyOwner;\n\n    struct RoleData {\n        mapping(address => bool) members;\n        bytes32 adminRole;\n    }\n\n    mapping(bytes32 => RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n    /**\n     * @dev Thrown when the addres does not have the required role\n     */\n    error AddressDoNotHaveRequiredRole();\n\n    /**\n     * @dev Thrown when the renounce address is not the message sender\n     */\n    error AccessControlOnlyCanRenounceRolesForSelf();\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with a standardized message including the required role.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     *\n     * _Available since v4.1._\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(\n        bytes32 role,\n        address account\n    ) public view virtual override returns (bool) {\n        return _roles[role].members[account];\n    }\n\n    /**\n     * @dev Revert with a standard message if `msg.sender` is missing `role`.\n     * Overriding this function changes the behavior of the {onlyRole} modifier.\n     *\n     * Format of the revert message is described in {_checkRole}.\n     *\n     * _Available since v4.6._\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, msg.sender);\n    }\n\n    /**\n     * @dev Revert with a standard message if `account` is missing `role`.\n     *\n     * The format of the revert reason is given by the following regular expression:\n     *\n     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert AddressDoNotHaveRequiredRole();\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(\n        bytes32 role\n    ) public view virtual override returns (bytes32) {\n        return _roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function grantRole(\n        bytes32 role,\n        address account\n    ) public virtual override onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(\n        bytes32 role,\n        address account\n    ) public virtual override onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `account`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(\n        bytes32 role,\n        address account\n    ) public virtual override {\n        if (account != msg.sender) {\n            revert AccessControlOnlyCanRenounceRolesForSelf();\n        }\n\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event. Note that unlike {grantRole}, this function doesn't perform any\n     * checks on the calling account.\n     *\n     * May emit a {RoleGranted} event.\n     *\n     * [WARNING]\n     * ====\n     * This function should only be called from the constructor when setting\n     * up the initial roles for the system.\n     *\n     * Using this function in any other way is effectively circumventing the admin\n     * system imposed by {AccessControl}.\n     * ====\n     *\n     * NOTE: This function is deprecated in favor of {_grantRole}.\n     */\n    function _setupRole(bytes32 role, address account) internal virtual {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        _roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual {\n        if (!hasRole(role, account)) {\n            _roles[role].members[account] = true;\n            emit RoleGranted(role, account, msg.sender);\n        }\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual {\n        if (hasRole(role, account)) {\n            _roles[role].members[account] = false;\n            emit RoleRevoked(role, account, msg.sender);\n        }\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[48] private __gap;\n}\n"
      },
      "contracts/v2/lib/PolygonConstantsBase.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.20;\n\n/**\n * This contract will contain the constants used across different contracts\n */\ncontract PolygonConstantsBase {\n    // If the system a does not verify a batch inside this time window, the contract enters in emergency mode\n    uint64 internal constant _HALT_AGGREGATION_TIMEOUT = 1 weeks;\n\n    // Maximum batches that can be verified in one call. It depends on our current metrics\n    // This should be a protection against someone that tries to generate huge chunk of invalid batches, and we can't prove otherwise before the pending timeout expires\n    uint64 internal constant _MAX_VERIFY_BATCHES = 1000;\n}\n"
      },
      "contracts/v2/lib/PolygonRollupBaseEtrog.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.20;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"../interfaces/IPolygonZkEVMGlobalExitRootV2.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"../../interfaces/IPolygonZkEVMErrors.sol\";\nimport \"../interfaces/IPolygonZkEVMVEtrogErrors.sol\";\nimport \"../PolygonRollupManager.sol\";\nimport \"../interfaces/IPolygonRollupBase.sol\";\nimport \"../interfaces/IPolygonZkEVMBridgeV2.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"./PolygonConstantsBase.sol\";\n\n/**\n * Contract responsible for managing the states and the updates of L2 network.\n * There will be a trusted sequencer, which is able to send transactions.\n * Any user can force some transaction and the sequencer will have a timeout to add them in the queue.\n * The sequenced state is deterministic and can be precalculated before it's actually verified by a zkProof.\n * The aggregators will be able to verify the sequenced state with zkProofs and therefore make available the withdrawals from L2 network.\n * To enter and exit of the L2 network will be used a PolygonZkEVMBridge smart contract that will be deployed in both networks.\n */\nabstract contract PolygonRollupBaseEtrog is\n    Initializable,\n    PolygonConstantsBase,\n    IPolygonZkEVMVEtrogErrors,\n    IPolygonRollupBase\n{\n    using SafeERC20Upgradeable for IERC20Upgradeable;\n\n    /**\n     * @notice Struct which will be used to call sequenceBatches\n     * @param transactions L2 ethereum transactions EIP-155 or pre-EIP-155 with signature:\n     * EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data, chainid, 0, 0,) || v || r || s\n     * pre-EIP-155: rlp(nonce, gasprice, gasLimit, to, value, data) || v || r || s\n     * @param forcedGlobalExitRoot Global exit root, empty when sequencing a non forced batch\n     * @param forcedTimestamp Minimum timestamp of the force batch data, empty when sequencing a non forced batch\n     * @param forcedBlockHashL1 blockHash snapshot of the force batch data, empty when sequencing a non forced batch\n     */\n    struct BatchData {\n        bytes transactions;\n        bytes32 forcedGlobalExitRoot;\n        uint64 forcedTimestamp;\n        bytes32 forcedBlockHashL1;\n    }\n\n    // Max transactions bytes that can be added in a single batch\n    // Max keccaks circuit = (2**23 / 155286) * 44 = 2376\n    // Bytes per keccak = 136\n    // Minimum Static keccaks batch = 2\n    // Max bytes allowed = (2376 - 2) * 136 = 322864 bytes - 1 byte padding\n    // Rounded to 300000 bytes\n    // In order to process the transaction, the data is approximately hashed twice for ecrecover:\n    // 300000 bytes / 2 = 150000 bytes\n    // Since geth pool currently only accepts at maximum 128kb transactions:\n    // https://github.com/ethereum/go-ethereum/blob/master/core/txpool/txpool.go#L54\n    // We will limit this length to be compliant with the geth restrictions since our node will use it\n    // We let 8kb as a sanity margin\n    uint256 internal constant _MAX_TRANSACTIONS_BYTE_LENGTH = 120000;\n\n    // Max force batch transaction length\n    // This is used to avoid huge calldata attacks, where the attacker call force batches from another contract\n    uint256 internal constant _MAX_FORCE_BATCH_BYTE_LENGTH = 5000;\n\n    // In order to encode the initialize transaction of the bridge there's have a constant part and the metadata which is variable\n    // Note the total transaction will be constrained to 65535 to avoid attacks and simplify the implementation\n\n    // List rlp: 1 listLenLen \"0xf9\" (0xf7 + 2), + listLen 2 (32 bytes + txData bytes) (do not accept more than 65535 bytes)\n\n    // First byte of the initialize bridge tx, indicates a list with a lengt of 2 bytes\n    // Since the minimum constant bytes will be: 259 (tx data empty) + 31 (tx parameters) = 259 (0x103) will always take 2 bytes to express the lenght of the rlp\n    // Note that more than 2 bytes of list len is not supported, since it's constrained to 65535\n    uint8 public constant INITIALIZE_TX_BRIDGE_LIST_LEN_LEN = 0xf9;\n\n    // Tx parameters until the bridge address\n    bytes public constant INITIALIZE_TX_BRIDGE_PARAMS = hex\"80808401c9c38094\";\n\n    // RLP encoded metadata (non empty)\n\n    // TxData bytes: 164 bytes data ( signature 4 bytes + 5 parameters*32bytes +\n    // (abi encoded metadata: 32 bytes position + 32 bytes len + 32 bytes position name + 32 bytes length name + 32 bytes position Symbol + 32 bytes length Symbol\n    //+ 32 bytes decimal )) min 7*32 bytes =\n    // = 164 bytes + 224 bytes = 388 (0x0184) minimum\n    // Extra data: nameLen padded to 32 bytes + symbol len padded to 32 bytes\n\n    // Constant bytes:  1 nonce \"0x80\" + 1 gasPrice \"0x80\" + 5 gasLimit \"0x8401c9c380\" (30M gas)\n    // + 21 to (\"0x94\" + bridgeAddress\")  + 1 value \"0x80\" + 1 stringLenLen \"0xb9\" (0xb7 + 2) +\n    // stringLen (0x0184 + nameLen padded to 32 bytes + symbol len padded to 32 bytes) + txData bytes = 32 bytes + txData bytes\n    uint16 public constant INITIALIZE_TX_CONSTANT_BYTES = 32;\n\n    // Tx parameters after the bridge address\n    bytes public constant INITIALIZE_TX_BRIDGE_PARAMS_AFTER_BRIDGE_ADDRESS =\n        hex\"80b9\";\n\n    // RLP empty metadata\n\n    // TxData empty metadata bytes: 164 bytes data ( signature 4 bytes + 5 parameters*32bytes +\n    // (abi encoded metadata: 32 bytes position + 32 bytes len = 2*32 bytes =\n    // = 164 bytes + 64 bytes = 228 (0xe4)\n\n    // Constant bytes empty metadata :  1 nonce \"0x80\" + 1 gasPrice \"0x80\" + 5 gasLimit \"0x8401c9c380\" (30M gas)\n    // + 21 to (\"0x94\" + bridgeAddress\")  + 1 value \"0x80\" + 1 stringLenLen \"0xb8\" (0xb7 + 1) +\n    // 1 stringLen (0xe4) + txData bytes = 31 bytes + txData bytes empty metadata 228 = 259\n    uint16 public constant INITIALIZE_TX_CONSTANT_BYTES_EMPTY_METADATA = 31;\n\n    uint8 public constant INITIALIZE_TX_DATA_LEN_EMPTY_METADATA = 228; // 0xe4\n\n    // Tx parameters after the bridge address\n    bytes\n        public constant INITIALIZE_TX_BRIDGE_PARAMS_AFTER_BRIDGE_ADDRESS_EMPTY_METADATA =\n        hex\"80b8\";\n\n    // Signature used to initialize the bridge\n\n    // V parameter of the initialize signature\n    uint8 public constant SIGNATURE_INITIALIZE_TX_V = 27;\n\n    // R parameter of the initialize signature\n    bytes32 public constant SIGNATURE_INITIALIZE_TX_R =\n        0x00000000000000000000000000000000000000000000000000000005ca1ab1e0;\n\n    // S parameter of the initialize signature\n    bytes32 public constant SIGNATURE_INITIALIZE_TX_S =\n        0x000000000000000000000000000000000000000000000000000000005ca1ab1e;\n\n    // Effective percentage of the initalize transaction\n    bytes1 public constant INITIALIZE_TX_EFFECTIVE_PERCENTAGE = 0xFF;\n\n    // Global Exit Root address L2\n    IBasePolygonZkEVMGlobalExitRoot\n        public constant GLOBAL_EXIT_ROOT_MANAGER_L2 =\n        IBasePolygonZkEVMGlobalExitRoot(\n            0xa40D5f56745a118D0906a34E69aeC8C0Db1cB8fA\n        );\n\n    // Timestamp range that's given to the sequencer as a safety measure to avoid reverts if the transaction is mined to quickly\n    uint256 public constant TIMESTAMP_RANGE = 36;\n\n    // POL token address\n    IERC20Upgradeable public immutable pol;\n\n    // Global Exit Root interface\n    IPolygonZkEVMGlobalExitRootV2 public immutable globalExitRootManager;\n\n    // PolygonZkEVM Bridge Address\n    IPolygonZkEVMBridgeV2 public immutable bridgeAddress;\n\n    // Rollup manager\n    PolygonRollupManager public immutable rollupManager;\n\n    // Address that will be able to adjust contract parameters\n    address public admin;\n\n    // This account will be able to accept the admin role\n    address public pendingAdmin;\n\n    // Trusted sequencer address\n    address public trustedSequencer;\n\n    // Trusted sequencer URL\n    string public trustedSequencerURL;\n\n    // L2 network name\n    string public networkName;\n\n    // Current accumulate input hash\n    bytes32 public lastAccInputHash;\n\n    // Queue of forced batches with their associated data\n    // ForceBatchNum --> hashedForcedBatchData\n    // hashedForcedBatchData: hash containing the necessary information to force a batch:\n    // keccak256(keccak256(bytes transactions), bytes32 forcedGlobalExitRoot, unint64 forcedTimestamp, bytes32 forcedBlockHashL1)\n    mapping(uint64 => bytes32) public forcedBatches;\n\n    // Last forced batch\n    uint64 public lastForceBatch;\n\n    // Last forced batch included in the sequence\n    uint64 public lastForceBatchSequenced;\n\n    // Force batch timeout\n    uint64 public forceBatchTimeout;\n\n    // Indicates what address is able to do forced batches\n    // If the address is set to 0, forced batches are open to everyone\n    address public forceBatchAddress;\n\n    // Token address that will be used to pay gas fees in this rollup. This variable it's just for read purposes\n    address public gasTokenAddress;\n\n    // Native network of the token address of the gas tokena address. This variable it's just for read purposes\n    uint32 public gasTokenNetwork;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     */\n    uint256[50] private _gap;\n\n    /**\n     * @dev Emitted when the trusted sequencer sends a new batch of transactions\n     */\n    event SequenceBatches(uint64 indexed numBatch, bytes32 l1InfoRoot);\n\n    /**\n     * @dev Emitted when a batch is forced\n     */\n    event ForceBatch(\n        uint64 indexed forceBatchNum,\n        bytes32 lastGlobalExitRoot,\n        address sequencer,\n        bytes transactions\n    );\n\n    /**\n     * @dev Emitted when forced batches are sequenced by not the trusted sequencer\n     */\n    event SequenceForceBatches(uint64 indexed numBatch);\n\n    /**\n     * @dev Emitted when the contract is initialized, contain the first sequenced transaction\n     */\n    event InitialSequenceBatches(\n        bytes transactions,\n        bytes32 lastGlobalExitRoot,\n        address sequencer\n    );\n\n    /**\n     * @dev Emitted when a aggregator verifies batches\n     */\n    event VerifyBatches(\n        uint64 indexed numBatch,\n        bytes32 stateRoot,\n        address indexed aggregator\n    );\n\n    /**\n     * @dev Emitted when the admin updates the trusted sequencer address\n     */\n    event SetTrustedSequencer(address newTrustedSequencer);\n\n    /**\n     * @dev Emitted when the admin updates the sequencer URL\n     */\n    event SetTrustedSequencerURL(string newTrustedSequencerURL);\n\n    /**\n     * @dev Emitted when the admin update the force batch timeout\n     */\n    event SetForceBatchTimeout(uint64 newforceBatchTimeout);\n\n    /**\n     * @dev Emitted when the admin update the force batch address\n     */\n    event SetForceBatchAddress(address newForceBatchAddress);\n\n    /**\n     * @dev Emitted when the admin starts the two-step transfer role setting a new pending admin\n     */\n    event TransferAdminRole(address newPendingAdmin);\n\n    /**\n     * @dev Emitted when the pending admin accepts the admin role\n     */\n    event AcceptAdminRole(address newAdmin);\n\n    // General parameters that will have in common all networks that deploys rollup manager\n\n    /**\n     * @param _globalExitRootManager Global exit root manager address\n     * @param _pol POL token address\n     * @param _bridgeAddress Bridge address\n     * @param _rollupManager Global exit root manager address\n     */\n    constructor(\n        IPolygonZkEVMGlobalExitRootV2 _globalExitRootManager,\n        IERC20Upgradeable _pol,\n        IPolygonZkEVMBridgeV2 _bridgeAddress,\n        PolygonRollupManager _rollupManager\n    ) {\n        globalExitRootManager = _globalExitRootManager;\n        pol = _pol;\n        bridgeAddress = _bridgeAddress;\n        rollupManager = _rollupManager;\n    }\n\n    /**\n     * @param _admin Admin address\n     * @param sequencer Trusted sequencer address\n     * @param networkID Indicates the network identifier that will be used in the bridge\n     * @param _gasTokenAddress Indicates the token address in mainnet that will be used as a gas token\n     * Note if a wrapped token of the bridge is used, the original network and address of this wrapped are used instead\n     * @param sequencerURL Trusted sequencer URL\n     * @param _networkName L2 network name\n     */\n    function initialize(\n        address _admin,\n        address sequencer,\n        uint32 networkID,\n        address _gasTokenAddress,\n        string memory sequencerURL,\n        string memory _networkName\n    ) external virtual onlyRollupManager initializer {\n        bytes memory gasTokenMetadata;\n\n        if (_gasTokenAddress != address(0)) {\n            // Ask for token metadata, the same way is enconded in the bridge\n            // Note that this function will revert if the token is not in this network\n            // Note that this could be a possible reentrant call, but cannot make changes on the state since are static call\n            gasTokenMetadata = bridgeAddress.getTokenMetadata(_gasTokenAddress);\n\n            // Check gas token address on the bridge\n            (\n                uint32 originWrappedNetwork,\n                address originWrappedAddress\n            ) = bridgeAddress.wrappedTokenToTokenInfo(_gasTokenAddress);\n\n            if (originWrappedNetwork != 0) {\n                // It's a wrapped token, get the wrapped parameters\n                gasTokenAddress = originWrappedAddress;\n                gasTokenNetwork = originWrappedNetwork;\n            } else {\n                // gasTokenNetwork will be mainnet, for instance 0\n                gasTokenAddress = _gasTokenAddress;\n            }\n        }\n        // Sequence transaction to initilize the bridge\n\n        // Calculate transaction to initialize the bridge\n        bytes memory transaction = generateInitializeTransaction(\n            networkID,\n            gasTokenAddress,\n            gasTokenNetwork,\n            gasTokenMetadata\n        );\n\n        bytes32 currentTransactionsHash = keccak256(transaction);\n\n        // Get current timestamp and global exit root\n        uint64 currentTimestamp = uint64(block.timestamp);\n        bytes32 lastGlobalExitRoot = globalExitRootManager\n            .getLastGlobalExitRoot();\n\n        // Add the transaction to the sequence as if it was a force transaction\n        bytes32 newAccInputHash = keccak256(\n            abi.encodePacked(\n                bytes32(0), // Current acc Input hash\n                currentTransactionsHash,\n                lastGlobalExitRoot, // Global exit root\n                currentTimestamp,\n                sequencer,\n                blockhash(block.number - 1)\n            )\n        );\n\n        lastAccInputHash = newAccInputHash;\n\n        rollupManager.onSequenceBatches(\n            uint64(1), // num total batches\n            newAccInputHash\n        );\n\n        // Set initialize variables\n        admin = _admin;\n        trustedSequencer = sequencer;\n\n        trustedSequencerURL = sequencerURL;\n        networkName = _networkName;\n\n        forceBatchAddress = _admin;\n\n        // Constant deployment variables\n        forceBatchTimeout = 5 days;\n\n        emit InitialSequenceBatches(transaction, lastGlobalExitRoot, sequencer);\n    }\n\n    modifier onlyAdmin() {\n        if (admin != msg.sender) {\n            revert OnlyAdmin();\n        }\n        _;\n    }\n\n    modifier onlyTrustedSequencer() {\n        if (trustedSequencer != msg.sender) {\n            revert OnlyTrustedSequencer();\n        }\n        _;\n    }\n\n    modifier isSenderAllowedToForceBatches() {\n        address cacheForceBatchAddress = forceBatchAddress;\n        if (\n            cacheForceBatchAddress != address(0) &&\n            cacheForceBatchAddress != msg.sender\n        ) {\n            revert ForceBatchNotAllowed();\n        }\n        _;\n    }\n\n    modifier onlyRollupManager() {\n        if (address(rollupManager) != msg.sender) {\n            revert OnlyRollupManager();\n        }\n        _;\n    }\n\n    /////////////////////////////////////\n    // Sequence/Verify batches functions\n    ////////////////////////////////////\n\n    /**\n     * @notice Allows a sequencer to send multiple batches\n     * @param batches Struct array which holds the necessary data to append new batches to the sequence\n     * @param maxSequenceTimestamp Max timestamp of the sequence. This timestamp must be inside a safety range (actual + 36 seconds).\n     * This timestamp should be equal or higher of the last block inside the sequence, otherwise this batch will be invalidated by circuit.\n     * @param initSequencedBatch This parameter must match the current last batch sequenced.\n     * This will be a protection for the sequencer to avoid sending undesired data\n     * @param l2Coinbase Address that will receive the fees from L2\n     * note Pol is not a reentrant token\n     */\n    function sequenceBatches(\n        BatchData[] calldata batches,\n        uint64 maxSequenceTimestamp,\n        uint64 initSequencedBatch,\n        address l2Coinbase\n    ) public virtual onlyTrustedSequencer {\n        uint256 batchesNum = batches.length;\n        if (batchesNum == 0) {\n            revert SequenceZeroBatches();\n        }\n\n        if (batchesNum > _MAX_VERIFY_BATCHES) {\n            revert ExceedMaxVerifyBatches();\n        }\n\n        // Check max sequence timestamp inside of range\n        if (\n            uint256(maxSequenceTimestamp) > (block.timestamp + TIMESTAMP_RANGE)\n        ) {\n            revert MaxTimestampSequenceInvalid();\n        }\n\n        // Update global exit root if there are new deposits\n        bridgeAddress.updateGlobalExitRoot();\n\n        // Get global batch variables\n        bytes32 l1InfoRoot = globalExitRootManager.getRoot();\n\n        // Store storage variables in memory, to save gas, because will be overrided multiple times\n        uint64 currentLastForceBatchSequenced = lastForceBatchSequenced;\n        bytes32 currentAccInputHash = lastAccInputHash;\n\n        // Store in a temporal variable, for avoid access again the storage slot\n        uint64 initLastForceBatchSequenced = currentLastForceBatchSequenced;\n\n        for (uint256 i = 0; i < batchesNum; i++) {\n            // Load current sequence\n            BatchData memory currentBatch = batches[i];\n\n            // Store the current transactions hash since can be used more than once for gas saving\n            bytes32 currentTransactionsHash = keccak256(\n                currentBatch.transactions\n            );\n\n            // Check if it's a forced batch\n            if (currentBatch.forcedTimestamp > 0) {\n                currentLastForceBatchSequenced++;\n\n                // Check forced data matches\n                bytes32 hashedForcedBatchData = keccak256(\n                    abi.encodePacked(\n                        currentTransactionsHash,\n                        currentBatch.forcedGlobalExitRoot,\n                        currentBatch.forcedTimestamp,\n                        currentBatch.forcedBlockHashL1\n                    )\n                );\n\n                if (\n                    hashedForcedBatchData !=\n                    forcedBatches[currentLastForceBatchSequenced]\n                ) {\n                    revert ForcedDataDoesNotMatch();\n                }\n\n                // Calculate next accumulated input hash\n                currentAccInputHash = keccak256(\n                    abi.encodePacked(\n                        currentAccInputHash,\n                        currentTransactionsHash,\n                        currentBatch.forcedGlobalExitRoot,\n                        currentBatch.forcedTimestamp,\n                        l2Coinbase,\n                        currentBatch.forcedBlockHashL1\n                    )\n                );\n\n                // Delete forceBatch data since won't be used anymore\n                delete forcedBatches[currentLastForceBatchSequenced];\n            } else {\n                // Note that forcedGlobalExitRoot and forcedBlockHashL1 remain unused and unchecked in this path\n                // The synchronizer should be aware of that\n                if (\n                    currentBatch.transactions.length >\n                    _MAX_TRANSACTIONS_BYTE_LENGTH\n                ) {\n                    revert TransactionsLengthAboveMax();\n                }\n\n                // Calculate next accumulated input hash\n                currentAccInputHash = keccak256(\n                    abi.encodePacked(\n                        currentAccInputHash,\n                        currentTransactionsHash,\n                        l1InfoRoot,\n                        maxSequenceTimestamp,\n                        l2Coinbase,\n                        bytes32(0)\n                    )\n                );\n            }\n        }\n\n        // Sanity check, should be unreachable\n        if (currentLastForceBatchSequenced > lastForceBatch) {\n            revert ForceBatchesOverflow();\n        }\n\n        // Store back the storage variables\n        lastAccInputHash = currentAccInputHash;\n\n        uint256 nonForcedBatchesSequenced = batchesNum;\n\n        // Check if there has been forced batches\n        if (currentLastForceBatchSequenced != initLastForceBatchSequenced) {\n            uint64 forcedBatchesSequenced = currentLastForceBatchSequenced -\n                initLastForceBatchSequenced;\n            // substract forced batches\n            nonForcedBatchesSequenced -= forcedBatchesSequenced;\n\n            // Transfer pol for every forced batch submitted\n            pol.safeTransfer(\n                address(rollupManager),\n                calculatePolPerForceBatch() * (forcedBatchesSequenced)\n            );\n\n            // Store new last force batch sequenced\n            lastForceBatchSequenced = currentLastForceBatchSequenced;\n        }\n\n        // Pay collateral for every non-forced batch submitted\n        pol.safeTransferFrom(\n            msg.sender,\n            address(rollupManager),\n            rollupManager.getBatchFee() * nonForcedBatchesSequenced\n        );\n\n        uint64 currentBatchSequenced = rollupManager.onSequenceBatches(\n            uint64(batchesNum),\n            currentAccInputHash\n        );\n\n        // Check init sequenced batch\n        if (\n            initSequencedBatch != (currentBatchSequenced - uint64(batchesNum))\n        ) {\n            revert InitSequencedBatchDoesNotMatch();\n        }\n\n        emit SequenceBatches(currentBatchSequenced, l1InfoRoot);\n    }\n\n    /**\n     * @notice Callback on verify batches, can only be called by the rollup manager\n     * @param lastVerifiedBatch Last verified batch\n     * @param newStateRoot new state root\n     * @param aggregator Aggregator address\n     */\n    function onVerifyBatches(\n        uint64 lastVerifiedBatch,\n        bytes32 newStateRoot,\n        address aggregator\n    ) public virtual override onlyRollupManager {\n        emit VerifyBatches(lastVerifiedBatch, newStateRoot, aggregator);\n    }\n\n    ////////////////////////////\n    // Force batches functions\n    ////////////////////////////\n\n    /**\n     * @notice Allows a sequencer/user to force a batch of L2 transactions.\n     * This should be used only in extreme cases where the trusted sequencer does not work as expected\n     * Note The sequencer has certain degree of control on how non-forced and forced batches are ordered\n     * In order to assure that users force transactions will be processed properly, user must not sign any other transaction\n     * with the same nonce\n     * @param transactions L2 ethereum transactions EIP-155 or pre-EIP-155 with signature:\n     * @param polAmount Max amount of pol tokens that the sender is willing to pay\n     */\n    function forceBatch(\n        bytes calldata transactions,\n        uint256 polAmount\n    ) public virtual isSenderAllowedToForceBatches {\n        // Check if rollup manager is on emergency state\n        if (rollupManager.isEmergencyState()) {\n            revert ForceBatchesNotAllowedOnEmergencyState();\n        }\n\n        // Calculate pol collateral\n        uint256 polFee = rollupManager.getForcedBatchFee();\n\n        if (polFee > polAmount) {\n            revert NotEnoughPOLAmount();\n        }\n\n        if (transactions.length > _MAX_FORCE_BATCH_BYTE_LENGTH) {\n            revert TransactionsLengthAboveMax();\n        }\n\n        // keep the pol fees on this contract until forced it's sequenced\n        pol.safeTransferFrom(msg.sender, address(this), polFee);\n\n        // Get globalExitRoot global exit root\n        bytes32 lastGlobalExitRoot = globalExitRootManager\n            .getLastGlobalExitRoot();\n\n        // Update forcedBatches mapping\n        lastForceBatch++;\n\n        forcedBatches[lastForceBatch] = keccak256(\n            abi.encodePacked(\n                keccak256(transactions),\n                lastGlobalExitRoot,\n                uint64(block.timestamp),\n                blockhash(block.number - 1)\n            )\n        );\n\n        if (msg.sender == tx.origin) {\n            // Getting the calldata from an EOA is easy so no need to put the `transactions` in the event\n            emit ForceBatch(lastForceBatch, lastGlobalExitRoot, msg.sender, \"\");\n        } else {\n            // Getting internal transaction calldata is complicated (because it requires an archive node)\n            // Therefore it's worth it to put the `transactions` in the event, which is easy to query\n            emit ForceBatch(\n                lastForceBatch,\n                lastGlobalExitRoot,\n                msg.sender,\n                transactions\n            );\n        }\n    }\n\n    /**\n     * @notice Allows anyone to sequence forced Batches if the trusted sequencer has not done so in the timeout period\n     * @param batches Struct array which holds the necessary data to append force batches\n     */\n    function sequenceForceBatches(\n        BatchData[] calldata batches\n    ) external virtual isSenderAllowedToForceBatches {\n        // Check if rollup manager is on emergency state\n        if (\n            rollupManager.lastDeactivatedEmergencyStateTimestamp() +\n                _HALT_AGGREGATION_TIMEOUT >\n            block.timestamp\n        ) {\n            revert HaltTimeoutNotExpiredAfterEmergencyState();\n        }\n\n        uint256 batchesNum = batches.length;\n\n        if (batchesNum == 0) {\n            revert SequenceZeroBatches();\n        }\n\n        if (batchesNum > _MAX_VERIFY_BATCHES) {\n            revert ExceedMaxVerifyBatches();\n        }\n\n        if (\n            uint256(lastForceBatchSequenced) + batchesNum >\n            uint256(lastForceBatch)\n        ) {\n            revert ForceBatchesOverflow();\n        }\n\n        // Store storage variables in memory, to save gas, because will be overrided multiple times\n        uint64 currentLastForceBatchSequenced = lastForceBatchSequenced;\n        bytes32 currentAccInputHash = lastAccInputHash;\n\n        // Sequence force batches\n        for (uint256 i = 0; i < batchesNum; i++) {\n            // Load current sequence\n            BatchData memory currentBatch = batches[i];\n            currentLastForceBatchSequenced++;\n\n            // Store the current transactions hash since it's used more than once for gas saving\n            bytes32 currentTransactionsHash = keccak256(\n                currentBatch.transactions\n            );\n\n            // Check forced data matches\n            bytes32 hashedForcedBatchData = keccak256(\n                abi.encodePacked(\n                    currentTransactionsHash,\n                    currentBatch.forcedGlobalExitRoot,\n                    currentBatch.forcedTimestamp,\n                    currentBatch.forcedBlockHashL1\n                )\n            );\n\n            if (\n                hashedForcedBatchData !=\n                forcedBatches[currentLastForceBatchSequenced]\n            ) {\n                revert ForcedDataDoesNotMatch();\n            }\n\n            // Delete forceBatch data since won't be used anymore\n            delete forcedBatches[currentLastForceBatchSequenced];\n\n            if (i == (batchesNum - 1)) {\n                // The last batch will have the most restrictive timestamp\n                if (\n                    currentBatch.forcedTimestamp + forceBatchTimeout >\n                    block.timestamp\n                ) {\n                    revert ForceBatchTimeoutNotExpired();\n                }\n            }\n            // Calculate next acc input hash\n            currentAccInputHash = keccak256(\n                abi.encodePacked(\n                    currentAccInputHash,\n                    currentTransactionsHash,\n                    currentBatch.forcedGlobalExitRoot,\n                    currentBatch.forcedTimestamp,\n                    msg.sender,\n                    currentBatch.forcedBlockHashL1\n                )\n            );\n        }\n\n        // Transfer pol for every forced batch submitted\n        pol.safeTransfer(\n            address(rollupManager),\n            calculatePolPerForceBatch() * (batchesNum)\n        );\n\n        // Store back the storage variables\n        lastAccInputHash = currentAccInputHash;\n        lastForceBatchSequenced = currentLastForceBatchSequenced;\n\n        uint64 currentBatchSequenced = rollupManager.onSequenceBatches(\n            uint64(batchesNum),\n            currentAccInputHash\n        );\n\n        emit SequenceForceBatches(currentBatchSequenced);\n    }\n\n    //////////////////\n    // admin functions\n    //////////////////\n\n    /**\n     * @notice Allow the admin to set a new trusted sequencer\n     * @param newTrustedSequencer Address of the new trusted sequencer\n     */\n    function setTrustedSequencer(\n        address newTrustedSequencer\n    ) external onlyAdmin {\n        trustedSequencer = newTrustedSequencer;\n\n        emit SetTrustedSequencer(newTrustedSequencer);\n    }\n\n    /**\n     * @notice Allow the admin to set the trusted sequencer URL\n     * @param newTrustedSequencerURL URL of trusted sequencer\n     */\n    function setTrustedSequencerURL(\n        string memory newTrustedSequencerURL\n    ) external onlyAdmin {\n        trustedSequencerURL = newTrustedSequencerURL;\n\n        emit SetTrustedSequencerURL(newTrustedSequencerURL);\n    }\n\n    /**\n     * @notice Allow the admin to change the force batch address, that will be allowed to force batches\n     * If address 0 is set, then everyone is able to force batches, this action is irreversible\n     * @param newForceBatchAddress New force batch address\n     */\n    function setForceBatchAddress(\n        address newForceBatchAddress\n    ) external onlyAdmin {\n        if (forceBatchAddress == address(0)) {\n            revert ForceBatchesDecentralized();\n        }\n        forceBatchAddress = newForceBatchAddress;\n\n        emit SetForceBatchAddress(newForceBatchAddress);\n    }\n\n    /**\n     * @notice Allow the admin to set the forcedBatchTimeout\n     * The new value can only be lower, except if emergency state is active\n     * @param newforceBatchTimeout New force batch timeout\n     */\n    function setForceBatchTimeout(\n        uint64 newforceBatchTimeout\n    ) external onlyAdmin {\n        if (newforceBatchTimeout > _HALT_AGGREGATION_TIMEOUT) {\n            revert InvalidRangeForceBatchTimeout();\n        }\n\n        if (!rollupManager.isEmergencyState()) {\n            if (newforceBatchTimeout >= forceBatchTimeout) {\n                revert InvalidRangeForceBatchTimeout();\n            }\n        }\n\n        forceBatchTimeout = newforceBatchTimeout;\n        emit SetForceBatchTimeout(newforceBatchTimeout);\n    }\n\n    /**\n     * @notice Starts the admin role transfer\n     * This is a two step process, the pending admin must accepted to finalize the process\n     * @param newPendingAdmin Address of the new pending admin\n     */\n    function transferAdminRole(address newPendingAdmin) external onlyAdmin {\n        pendingAdmin = newPendingAdmin;\n        emit TransferAdminRole(newPendingAdmin);\n    }\n\n    /**\n     * @notice Allow the current pending admin to accept the admin role\n     */\n    function acceptAdminRole() external {\n        if (pendingAdmin != msg.sender) {\n            revert OnlyPendingAdmin();\n        }\n\n        admin = pendingAdmin;\n        emit AcceptAdminRole(pendingAdmin);\n    }\n\n    //////////////////\n    // view/pure functions\n    //////////////////\n\n    /**\n     * @notice Function to calculate the reward for a forced batch\n     */\n    function calculatePolPerForceBatch() public view returns (uint256) {\n        uint256 currentBalance = pol.balanceOf(address(this));\n\n        // Pending forced Batches = last forced batch added - last forced batch sequenced\n        uint256 pendingForcedBatches = lastForceBatch - lastForceBatchSequenced;\n\n        if (pendingForcedBatches == 0) return 0;\n        return currentBalance / pendingForcedBatches;\n    }\n\n    /**\n     * @notice Generate Initialize transaction for hte bridge on L2\n     * @param networkID Indicates the network identifier that will be used in the bridge\n     * @param _gasTokenAddress Indicates the token address that will be used to pay gas fees in the new rollup\n     * @param _gasTokenNetwork Indicates the native network of the token address\n     * @param _gasTokenMetadata Abi encoded gas token metadata\n     */\n    function generateInitializeTransaction(\n        uint32 networkID,\n        address _gasTokenAddress,\n        uint32 _gasTokenNetwork,\n        bytes memory _gasTokenMetadata\n    ) public view returns (bytes memory) {\n        bytes memory initializeBrigeData = abi.encodeCall(\n            IPolygonZkEVMBridgeV2.initialize,\n            (\n                networkID,\n                _gasTokenAddress,\n                _gasTokenNetwork,\n                GLOBAL_EXIT_ROOT_MANAGER_L2,\n                address(0), // Rollup manager on L2 does not exist\n                _gasTokenMetadata\n            )\n        );\n\n        bytes memory bytesToSign;\n\n        if (_gasTokenMetadata.length == 0) {\n            bytesToSign = abi.encodePacked(\n                INITIALIZE_TX_BRIDGE_LIST_LEN_LEN,\n                uint16(initializeBrigeData.length) +\n                    INITIALIZE_TX_CONSTANT_BYTES_EMPTY_METADATA, // do not support more than 2 bytes of length, intended to revert on overflow\n                INITIALIZE_TX_BRIDGE_PARAMS,\n                bridgeAddress,\n                INITIALIZE_TX_BRIDGE_PARAMS_AFTER_BRIDGE_ADDRESS_EMPTY_METADATA,\n                INITIALIZE_TX_DATA_LEN_EMPTY_METADATA,\n                initializeBrigeData\n            );\n        } else {\n            // Do not support more than 65535 bytes\n            if (initializeBrigeData.length > type(uint16).max) {\n                revert HugeTokenMetadataNotSupported();\n            }\n            uint16 initializeBrigeDataLen = uint16(initializeBrigeData.length);\n\n            bytesToSign = abi.encodePacked(\n                INITIALIZE_TX_BRIDGE_LIST_LEN_LEN,\n                uint16(initializeBrigeData.length) +\n                    INITIALIZE_TX_CONSTANT_BYTES, // do not support more than 2 bytes of length, intended to revert on overflow\n                INITIALIZE_TX_BRIDGE_PARAMS,\n                bridgeAddress,\n                INITIALIZE_TX_BRIDGE_PARAMS_AFTER_BRIDGE_ADDRESS,\n                initializeBrigeDataLen,\n                initializeBrigeData\n            );\n        }\n\n        // Sanity check that the ecrecover will work\n        // Should never happen that giving a valid signature, ecrecover \"breaks\"\n        address signer = ecrecover(\n            keccak256(bytesToSign),\n            SIGNATURE_INITIALIZE_TX_V,\n            SIGNATURE_INITIALIZE_TX_R,\n            SIGNATURE_INITIALIZE_TX_S\n        );\n\n        if (signer == address(0)) {\n            revert InvalidInitializeTransaction();\n        }\n\n        bytes memory transaction = abi.encodePacked(\n            bytesToSign,\n            SIGNATURE_INITIALIZE_TX_R,\n            SIGNATURE_INITIALIZE_TX_S,\n            SIGNATURE_INITIALIZE_TX_V,\n            INITIALIZE_TX_EFFECTIVE_PERCENTAGE\n        );\n\n        return transaction;\n    }\n}\n"
      },
      "contracts/v2/lib/PolygonTransparentProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC1967Utils} from \"@openzeppelin/contracts5/proxy/ERC1967/ERC1967Utils.sol\";\nimport {ERC1967Proxy} from \"@openzeppelin/contracts5/proxy/ERC1967/ERC1967Proxy.sol\";\nimport {IERC1967} from \"@openzeppelin/contracts5/interfaces/IERC1967.sol\";\nimport {ProxyAdmin} from \"@openzeppelin/contracts5/proxy/transparent/ProxyAdmin.sol\";\nimport {ITransparentUpgradeableProxy} from \"@openzeppelin/contracts5/proxy/transparent/TransparentUpgradeableProxy.sol\";\n\n/**\n * @dev Contrac TransparentUpgradeableProxy from Openzeppelin v5 with the following modifications:\n * - Admin is a parameter in the constructor ( like previous versions) isntead of being deployed\n * - Let the admin get access to the proxy\n * - Replace _msgSender() with msg.sender\n */\ncontract PolygonTransparentProxy is ERC1967Proxy {\n    // An immutable address for the admin to avoid unnecessary SLOADs before each call\n    // at the expense of removing the ability to change the admin once it's set.\n    // This is acceptable if the admin is always a ProxyAdmin instance or similar contract\n    // with its own ability to transfer the permissions to another account.\n    address private immutable _admin;\n\n    /**\n     * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,\n     * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in\n     * {ERC1967Proxy-constructor}.\n     */\n    constructor(\n        address _logic,\n        address admin,\n        bytes memory _data\n    ) payable ERC1967Proxy(_logic, _data) {\n        _admin = admin;\n        // Set the storage value and emit an event for ERC-1967 compatibility\n        ERC1967Utils.changeAdmin(_proxyAdmin());\n    }\n\n    /**\n     * @dev Returns the admin of this proxy.\n     */\n    function _proxyAdmin() internal virtual returns (address) {\n        return _admin;\n    }\n\n    /**\n     * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.\n     */\n    function _fallback() internal virtual override {\n        if (msg.sender == _proxyAdmin()) {\n            if (\n                msg.sig !=\n                ITransparentUpgradeableProxy.upgradeToAndCall.selector\n            ) {\n                super._fallback();\n            } else {\n                _dispatchUpgradeToAndCall();\n            }\n        } else {\n            super._fallback();\n        }\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.\n     *\n     * Requirements:\n     *\n     * - If `data` is empty, `msg.value` must be zero.\n     */\n    function _dispatchUpgradeToAndCall() private {\n        (address newImplementation, bytes memory data) = abi.decode(\n            msg.data[4:],\n            (address, bytes)\n        );\n        ERC1967Utils.upgradeToAndCall(newImplementation, data);\n    }\n}\n"
      },
      "contracts/v2/PolygonRollupManager.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity 0.8.20;\n\nimport \"./interfaces/IPolygonRollupManager.sol\";\nimport \"./interfaces/IPolygonZkEVMGlobalExitRootV2.sol\";\nimport \"../interfaces/IPolygonZkEVMBridge.sol\";\nimport \"./interfaces/IPolygonRollupBase.sol\";\nimport \"../interfaces/IVerifierRollup.sol\";\nimport \"../lib/EmergencyManager.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"./lib/PolygonTransparentProxy.sol\";\nimport \"./lib/PolygonAccessControlUpgradeable.sol\";\nimport \"./lib/LegacyZKEVMStateVariables.sol\";\nimport \"./consensus/zkEVM/PolygonZkEVMExistentEtrog.sol\";\nimport \"./lib/PolygonConstantsBase.sol\";\n\n/**\n * Contract responsible for managing rollups and the verification of their batches.\n * This contract will create and update rollups and store all the hashed sequenced data from them.\n * The logic for sequence batches is moved to the `consensus` contracts, while the verification of all of\n * them will be done in this one. In this way, the proof aggregation of the rollups will be easier on a close future.\n */\ncontract PolygonRollupManager is\n    PolygonAccessControlUpgradeable,\n    EmergencyManager,\n    LegacyZKEVMStateVariables,\n    PolygonConstantsBase,\n    IPolygonRollupManager\n{\n    using SafeERC20Upgradeable for IERC20Upgradeable;\n\n    /**\n     * @notice Struct which to store the rollup type data\n     * @param consensusImplementation Consensus implementation ( contains the consensus logic for the transaparent proxy)\n     * @param verifier verifier\n     * @param forkID fork ID\n     * @param rollupCompatibilityID Rollup compatibility ID, to check upgradability between rollup types\n     * @param obsolete Indicates if the rollup type is obsolete\n     * @param genesis Genesis block of the rollup, note that will only be used on creating new rollups, not upgrade them\n     */\n    struct RollupType {\n        address consensusImplementation;\n        IVerifierRollup verifier;\n        uint64 forkID;\n        uint8 rollupCompatibilityID;\n        bool obsolete;\n        bytes32 genesis;\n    }\n\n    /**\n     * @notice Struct which to store the rollup data of each chain\n     * @param rollupContract Rollup consensus contract, which manages everything\n     * related to sequencing transactions\n     * @param chainID Chain ID of the rollup\n     * @param verifier Verifier contract\n     * @param forkID ForkID of the rollup\n     * @param batchNumToStateRoot State root mapping\n     * @param sequencedBatches Queue of batches that defines the virtual state\n     * @param pendingStateTransitions Pending state mapping\n     * @param lastLocalExitRoot Last exit root verified, used for compute the rollupExitRoot\n     * @param lastBatchSequenced Last batch sent by the consensus contract\n     * @param lastVerifiedBatch Last batch verified\n     * @param lastPendingState Last pending state\n     * @param lastPendingStateConsolidated Last pending state consolidated\n     * @param lastVerifiedBatchBeforeUpgrade Last batch verified before the last upgrade\n     * @param rollupTypeID Rollup type ID, can be 0 if it was added as an existing rollup\n     * @param rollupCompatibilityID Rollup ID used for compatibility checks when upgrading\n     */\n    struct RollupData {\n        IPolygonRollupBase rollupContract;\n        uint64 chainID;\n        IVerifierRollup verifier;\n        uint64 forkID;\n        mapping(uint64 batchNum => bytes32) batchNumToStateRoot;\n        mapping(uint64 batchNum => SequencedBatchData) sequencedBatches;\n        mapping(uint256 pendingStateNum => PendingState) pendingStateTransitions;\n        bytes32 lastLocalExitRoot;\n        uint64 lastBatchSequenced;\n        uint64 lastVerifiedBatch;\n        uint64 lastPendingState;\n        uint64 lastPendingStateConsolidated;\n        uint64 lastVerifiedBatchBeforeUpgrade;\n        uint64 rollupTypeID;\n        uint8 rollupCompatibilityID;\n    }\n\n    // Modulus zkSNARK\n    uint256 internal constant _RFIELD =\n        21888242871839275222246405745257275088548364400416034343698204186575808495617;\n\n    // Max batch multiplier per verification\n    uint256 internal constant _MAX_BATCH_MULTIPLIER = 12;\n\n    // Max batch fee value\n    uint256 internal constant _MAX_BATCH_FEE = 1000 ether;\n\n    // Min value batch fee\n    uint256 internal constant _MIN_BATCH_FEE = 0 gwei;\n\n    // Goldilocks prime field\n    uint256 internal constant _GOLDILOCKS_PRIME_FIELD = 0xFFFFFFFF00000001; // 2 ** 64 - 2 ** 32 + 1\n\n    // Max uint64\n    uint256 internal constant _MAX_UINT_64 = type(uint64).max; // 0xFFFFFFFFFFFFFFFF\n\n    // Exit merkle tree levels\n    uint256 internal constant _EXIT_TREE_DEPTH = 32;\n\n    // Roles\n\n    // Be able to add a new rollup type\n    bytes32 internal constant _ADD_ROLLUP_TYPE_ROLE =\n        keccak256(\"ADD_ROLLUP_TYPE_ROLE\");\n\n    // Be able to obsolete a rollup type, which means that new rollups cannot use this type\n    bytes32 internal constant _OBSOLETE_ROLLUP_TYPE_ROLE =\n        keccak256(\"OBSOLETE_ROLLUP_TYPE_ROLE\");\n\n    // Be able to create a new rollup using a rollup type\n    bytes32 internal constant _CREATE_ROLLUP_ROLE =\n        keccak256(\"CREATE_ROLLUP_ROLE\");\n\n    // Be able to create a new rollup which does not have to follow any rollup type.\n    // Also sets the genesis block for that network\n    bytes32 internal constant _ADD_EXISTING_ROLLUP_ROLE =\n        keccak256(\"ADD_EXISTING_ROLLUP_ROLE\");\n\n    // Be able to update a rollup to a new rollup type that it's compatible\n    bytes32 internal constant _UPDATE_ROLLUP_ROLE =\n        keccak256(\"UPDATE_ROLLUP_ROLE\");\n\n    // Be able to that has priority to verify batches and consolidates the state instantly\n    bytes32 internal constant _TRUSTED_AGGREGATOR_ROLE =\n        keccak256(\"TRUSTED_AGGREGATOR_ROLE\");\n\n    // Be able to set the trusted aggregator address\n    bytes32 internal constant _TRUSTED_AGGREGATOR_ROLE_ADMIN =\n        keccak256(\"TRUSTED_AGGREGATOR_ROLE_ADMIN\");\n\n    // Be able to tweak parameters\n    bytes32 internal constant _TWEAK_PARAMETERS_ROLE =\n        keccak256(\"TWEAK_PARAMETERS_ROLE\");\n\n    // Be able to set the current batch fee\n    bytes32 internal constant _SET_FEE_ROLE = keccak256(\"SET_FEE_ROLE\");\n\n    // Be able to stop the emergency state\n    bytes32 internal constant _STOP_EMERGENCY_ROLE =\n        keccak256(\"STOP_EMERGENCY_ROLE\");\n\n    // Be able to activate the emergency state without any further condition\n    bytes32 internal constant _EMERGENCY_COUNCIL_ROLE =\n        keccak256(\"EMERGENCY_COUNCIL_ROLE\");\n\n    // Be able to set the emergency council address\n    bytes32 internal constant _EMERGENCY_COUNCIL_ADMIN =\n        keccak256(\"EMERGENCY_COUNCIL_ADMIN\");\n\n    // Global Exit Root address\n    IPolygonZkEVMGlobalExitRootV2 public immutable globalExitRootManager;\n\n    // PolygonZkEVM Bridge Address\n    IPolygonZkEVMBridge public immutable bridgeAddress;\n\n    // POL token address\n    IERC20Upgradeable public immutable pol;\n\n    // Number of rollup types added, every new type will be assigned sequencially a new ID\n    uint32 public rollupTypeCount;\n\n    // Rollup type mapping\n    mapping(uint32 rollupTypeID => RollupType) public rollupTypeMap;\n\n    // Number of rollups added, every new rollup will be assigned sequencially a new ID\n    uint32 public rollupCount;\n\n    // Rollups ID mapping\n    mapping(uint32 rollupID => RollupData) public rollupIDToRollupData;\n\n    // Rollups address mapping\n    mapping(address rollupAddress => uint32 rollupID) public rollupAddressToID;\n\n    // Chain ID mapping for nullifying\n    // note we will take care to avoid that current known chainIDs are not reused in our networks (example: 1)\n    mapping(uint64 chainID => uint32 rollupID) public chainIDToRollupID;\n\n    // Total sequenced batches across all rollups\n    uint64 public totalSequencedBatches;\n\n    // Total verified batches across all rollups\n    uint64 public totalVerifiedBatches;\n\n    // Last timestamp when an aggregation happen\n    uint64 public lastAggregationTimestamp;\n\n    // Trusted aggregator timeout, if a sequence is not verified in this time frame,\n    // everyone can verify that sequence\n    uint64 public trustedAggregatorTimeout;\n\n    // Once a pending state exceeds this timeout it can be consolidated\n    uint64 public pendingStateTimeout;\n\n    // Time target of the verification of a batch\n    // Adaptively the batchFee will be updated to achieve this target\n    uint64 public verifyBatchTimeTarget;\n\n    // Batch fee multiplier with 3 decimals that goes from 1000 - 1023\n    uint16 public multiplierBatchFee;\n\n    // Current POL fee per batch sequenced\n    // note This variable is internal, since the view function getBatchFee is likely to be upgraded\n    uint256 internal _batchFee;\n\n    // Timestamp when the last emergency state was deactivated\n    uint64 public lastDeactivatedEmergencyStateTimestamp;\n\n    /**\n     * @dev Emitted when a new rollup type is added\n     */\n    event AddNewRollupType(\n        uint32 indexed rollupTypeID,\n        address consensusImplementation,\n        address verifier,\n        uint64 forkID,\n        uint8 rollupCompatibilityID,\n        bytes32 genesis,\n        string description\n    );\n\n    /**\n     * @dev Emitted when a a rolup type is obsoleted\n     */\n    event ObsoleteRollupType(uint32 indexed rollupTypeID);\n\n    /**\n     * @dev Emitted when a new rollup is created based on a rollupType\n     */\n    event CreateNewRollup(\n        uint32 indexed rollupID,\n        uint32 rollupTypeID,\n        address rollupAddress,\n        uint64 chainID,\n        address gasTokenAddress\n    );\n\n    /**\n     * @dev Emitted when an existing rollup is added\n     */\n    event AddExistingRollup(\n        uint32 indexed rollupID,\n        uint64 forkID,\n        address rollupAddress,\n        uint64 chainID,\n        uint8 rollupCompatibilityID,\n        uint64 lastVerifiedBatchBeforeUpgrade\n    );\n\n    /**\n     * @dev Emitted when a rollup is udpated\n     */\n    event UpdateRollup(\n        uint32 indexed rollupID,\n        uint32 newRollupTypeID,\n        uint64 lastVerifiedBatchBeforeUpgrade\n    );\n\n    /**\n     * @dev Emitted when a new verifier is added\n     */\n    event OnSequenceBatches(uint32 indexed rollupID, uint64 lastBatchSequenced);\n\n    /**\n     * @dev Emitted when an aggregator verifies batches\n     */\n    event VerifyBatches(\n        uint32 indexed rollupID,\n        uint64 numBatch,\n        bytes32 stateRoot,\n        bytes32 exitRoot,\n        address indexed aggregator\n    );\n\n    /**\n     * @dev Emitted when the trusted aggregator verifies batches\n     */\n    event VerifyBatchesTrustedAggregator(\n        uint32 indexed rollupID,\n        uint64 numBatch,\n        bytes32 stateRoot,\n        bytes32 exitRoot,\n        address indexed aggregator\n    );\n\n    /**\n     * @dev Emitted when pending state is consolidated\n     */\n    event ConsolidatePendingState(\n        uint32 indexed rollupID,\n        uint64 numBatch,\n        bytes32 stateRoot,\n        bytes32 exitRoot,\n        uint64 pendingStateNum\n    );\n\n    /**\n     * @dev Emitted when is proved a different state given the same batches\n     */\n    event ProveNonDeterministicPendingState(\n        bytes32 storedStateRoot,\n        bytes32 provedStateRoot\n    );\n\n    /**\n     * @dev Emitted when the trusted aggregator overrides pending state\n     */\n    event OverridePendingState(\n        uint32 indexed rollupID,\n        uint64 numBatch,\n        bytes32 stateRoot,\n        bytes32 exitRoot,\n        address aggregator\n    );\n\n    /**\n     * @dev Emitted when is updated the trusted aggregator timeout\n     */\n    event SetTrustedAggregatorTimeout(uint64 newTrustedAggregatorTimeout);\n\n    /**\n     * @dev Emitted when is updated the pending state timeout\n     */\n    event SetPendingStateTimeout(uint64 newPendingStateTimeout);\n\n    /**\n     * @dev Emitted when is updated the multiplier batch fee\n     */\n    event SetMultiplierBatchFee(uint16 newMultiplierBatchFee);\n\n    /**\n     * @dev Emitted when is updated the verify batch timeout\n     */\n    event SetVerifyBatchTimeTarget(uint64 newVerifyBatchTimeTarget);\n\n    /**\n     * @dev Emitted when is updated the trusted aggregator address\n     */\n    event SetTrustedAggregator(address newTrustedAggregator);\n\n    /**\n     * @dev Emitted when is updated the batch fee\n     */\n    event SetBatchFee(uint256 newBatchFee);\n\n    /**\n     * @param _globalExitRootManager Global exit root manager address\n     * @param _pol POL token address\n     * @param _bridgeAddress Bridge address\n     */\n    constructor(\n        IPolygonZkEVMGlobalExitRootV2 _globalExitRootManager,\n        IERC20Upgradeable _pol,\n        IPolygonZkEVMBridge _bridgeAddress\n    ) {\n        globalExitRootManager = _globalExitRootManager;\n        pol = _pol;\n        bridgeAddress = _bridgeAddress;\n\n        // Disable initalizers on the implementation following the best practices\n        _disableInitializers();\n    }\n\n    /**\n     * @param trustedAggregator Trusted aggregator address\n     * @param _pendingStateTimeout Pending state timeout\n     * @param _trustedAggregatorTimeout Trusted aggregator timeout\n     * @param admin Admin of the rollup manager\n     * @param timelock Timelock address\n     * @param emergencyCouncil Emergency council address\n     * @param polygonZkEVM New deployed Polygon zkEVM which will be initialized wiht previous values\n     * @param zkEVMVerifier Verifier of the new zkEVM deployed\n     * @param zkEVMForkID Fork id of the new zkEVM deployed\n     * @param zkEVMChainID Chain id of the new zkEVM deployed\n     */\n    function initialize(\n        address trustedAggregator,\n        uint64 _pendingStateTimeout,\n        uint64 _trustedAggregatorTimeout,\n        address admin,\n        address timelock,\n        address emergencyCouncil,\n        PolygonZkEVMExistentEtrog polygonZkEVM,\n        IVerifierRollup zkEVMVerifier,\n        uint64 zkEVMForkID,\n        uint64 zkEVMChainID\n    ) external virtual reinitializer(2) {\n        pendingStateTimeout = _pendingStateTimeout;\n        trustedAggregatorTimeout = _trustedAggregatorTimeout;\n\n        // Constant deployment variables\n        _batchFee = 0 ether; // 0 POL\n        verifyBatchTimeTarget = 30 minutes;\n        multiplierBatchFee = 1002;\n\n        // Initialize OZ contracts\n        __AccessControl_init();\n\n        // setup roles\n\n        // trusted aggregator role\n        _setupRole(_TRUSTED_AGGREGATOR_ROLE, trustedAggregator);\n\n        // Timelock roles\n        _setupRole(DEFAULT_ADMIN_ROLE, timelock);\n        _setupRole(_ADD_ROLLUP_TYPE_ROLE, timelock);\n        _setupRole(_ADD_EXISTING_ROLLUP_ROLE, timelock);\n\n        // note even this role can only update to an already added verifier/consensus\n        // Could break the compatibility of them, changing the virtual state\n        _setupRole(_UPDATE_ROLLUP_ROLE, timelock);\n\n        // admin roles\n        _setupRole(_OBSOLETE_ROLLUP_TYPE_ROLE, admin);\n        _setupRole(_CREATE_ROLLUP_ROLE, admin);\n        _setupRole(_STOP_EMERGENCY_ROLE, admin);\n        _setupRole(_TWEAK_PARAMETERS_ROLE, admin);\n\n        // admin should be able to update the trusted aggregator address\n        _setRoleAdmin(_TRUSTED_AGGREGATOR_ROLE, _TRUSTED_AGGREGATOR_ROLE_ADMIN);\n        _setupRole(_TRUSTED_AGGREGATOR_ROLE_ADMIN, admin);\n        _setupRole(_SET_FEE_ROLE, admin);\n\n        // Emergency council roles\n        _setRoleAdmin(_EMERGENCY_COUNCIL_ROLE, _EMERGENCY_COUNCIL_ADMIN);\n        _setupRole(_EMERGENCY_COUNCIL_ROLE, emergencyCouncil);\n        _setupRole(_EMERGENCY_COUNCIL_ADMIN, emergencyCouncil);\n\n        // Check last verified batch\n        uint64 zkEVMLastBatchSequenced = _legacylastBatchSequenced;\n        uint64 zkEVMLastVerifiedBatch = _legacyLastVerifiedBatch;\n        if (zkEVMLastBatchSequenced != zkEVMLastVerifiedBatch) {\n            revert AllzkEVMSequencedBatchesMustBeVerified();\n        }\n\n        // Initialize current zkEVM\n        RollupData storage currentZkEVM = _addExistingRollup(\n            IPolygonRollupBase(polygonZkEVM),\n            zkEVMVerifier,\n            zkEVMForkID,\n            zkEVMChainID,\n            0, // Rollup compatibility ID is 0\n            _legacyLastVerifiedBatch\n        );\n\n        // Copy variables from legacy\n        currentZkEVM.batchNumToStateRoot[\n            zkEVMLastVerifiedBatch\n        ] = _legacyBatchNumToStateRoot[zkEVMLastVerifiedBatch];\n\n        // note previousLastBatchSequenced of the SequencedBatchData will be inconsistent,\n        // since there will not be a previous sequence stored in the sequence mapping.\n        // However since lastVerifiedBatch is equal to the lastBatchSequenced\n        // won't affect in any case\n        currentZkEVM.sequencedBatches[\n            zkEVMLastBatchSequenced\n        ] = _legacySequencedBatches[zkEVMLastBatchSequenced];\n\n        currentZkEVM.lastBatchSequenced = zkEVMLastBatchSequenced;\n        currentZkEVM.lastVerifiedBatch = zkEVMLastVerifiedBatch;\n        currentZkEVM.lastVerifiedBatchBeforeUpgrade = zkEVMLastVerifiedBatch;\n        // rollupType and rollupCompatibilityID will be both 0\n\n        // Initialize polygon zkevm\n        polygonZkEVM.initializeUpgrade(\n            _legacyAdmin,\n            _legacyTrustedSequencer,\n            _legacyTrustedSequencerURL,\n            _legacyNetworkName,\n            _legacySequencedBatches[zkEVMLastBatchSequenced].accInputHash\n        );\n    }\n\n    ///////////////////////////////////////\n    // Rollups management functions\n    ///////////////////////////////////////\n\n    /**\n     * @notice Add a new rollup type\n     * @param consensusImplementation Consensus implementation\n     * @param verifier Verifier address\n     * @param forkID ForkID of the verifier\n     * @param genesis Genesis block of the rollup\n     * @param description Description of the rollup type\n     */\n    function addNewRollupType(\n        address consensusImplementation,\n        IVerifierRollup verifier,\n        uint64 forkID,\n        uint8 rollupCompatibilityID,\n        bytes32 genesis,\n        string memory description\n    ) external onlyRole(_ADD_ROLLUP_TYPE_ROLE) {\n        uint32 rollupTypeID = ++rollupTypeCount;\n\n        rollupTypeMap[rollupTypeID] = RollupType({\n            consensusImplementation: consensusImplementation,\n            verifier: verifier,\n            forkID: forkID,\n            rollupCompatibilityID: rollupCompatibilityID,\n            obsolete: false,\n            genesis: genesis\n        });\n\n        emit AddNewRollupType(\n            rollupTypeID,\n            consensusImplementation,\n            address(verifier),\n            forkID,\n            rollupCompatibilityID,\n            genesis,\n            description\n        );\n    }\n\n    /**\n     * @notice Obsolete Rollup type\n     * @param rollupTypeID Rollup type to obsolete\n     */\n    function obsoleteRollupType(\n        uint32 rollupTypeID\n    ) external onlyRole(_OBSOLETE_ROLLUP_TYPE_ROLE) {\n        // Check that rollup type exists\n        if (rollupTypeID == 0 || rollupTypeID > rollupTypeCount) {\n            revert RollupTypeDoesNotExist();\n        }\n\n        // Check rollup type is not obsolete\n        RollupType storage currentRollupType = rollupTypeMap[rollupTypeID];\n        if (currentRollupType.obsolete == true) {\n            revert RollupTypeObsolete();\n        }\n\n        currentRollupType.obsolete = true;\n\n        emit ObsoleteRollupType(rollupTypeID);\n    }\n\n    /**\n     * @notice Create a new rollup\n     * @param rollupTypeID Rollup type to deploy\n     * @param chainID ChainID of the rollup, must be a new one\n     * @param admin Admin of the new created rollup\n     * @param sequencer Sequencer of the new created rollup\n     * @param gasTokenAddress Indicates the token address that will be used to pay gas fees in the new rollup\n     * Note if a wrapped token of the bridge is used, the original network and address of this wrapped will be used instead\n     * @param sequencerURL Sequencer URL of the new created rollup\n     * @param networkName Network name of the new created rollup\n     */\n    function createNewRollup(\n        uint32 rollupTypeID,\n        uint64 chainID,\n        address admin,\n        address sequencer,\n        address gasTokenAddress,\n        string memory sequencerURL,\n        string memory networkName\n    ) external onlyRole(_CREATE_ROLLUP_ROLE) {\n        // Check that rollup type exists\n        if (rollupTypeID == 0 || rollupTypeID > rollupTypeCount) {\n            revert RollupTypeDoesNotExist();\n        }\n\n        // Check rollup type is not obsolete\n        RollupType storage rollupType = rollupTypeMap[rollupTypeID];\n        if (rollupType.obsolete == true) {\n            revert RollupTypeObsolete();\n        }\n\n        // Check chainID nullifier\n        if (chainIDToRollupID[chainID] != 0) {\n            revert ChainIDAlreadyExist();\n        }\n\n        // Create a new Rollup, using a transparent proxy pattern\n        // Consensus will be the implementation, and this contract the admin\n        uint32 rollupID = ++rollupCount;\n        address rollupAddress = address(\n            new PolygonTransparentProxy(\n                rollupType.consensusImplementation,\n                address(this),\n                new bytes(0)\n            )\n        );\n\n        // Set chainID nullifier\n        chainIDToRollupID[chainID] = rollupID;\n\n        // Store rollup data\n        rollupAddressToID[rollupAddress] = rollupID;\n\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n\n        rollup.rollupContract = IPolygonRollupBase(rollupAddress);\n        rollup.forkID = rollupType.forkID;\n        rollup.verifier = rollupType.verifier;\n        rollup.chainID = chainID;\n        rollup.batchNumToStateRoot[0] = rollupType.genesis;\n        rollup.rollupTypeID = rollupTypeID;\n        rollup.rollupCompatibilityID = rollupType.rollupCompatibilityID;\n\n        emit CreateNewRollup(\n            rollupID,\n            rollupTypeID,\n            rollupAddress,\n            chainID,\n            gasTokenAddress\n        );\n\n        // Initialize new rollup\n        IPolygonRollupBase(rollupAddress).initialize(\n            admin,\n            sequencer,\n            rollupID,\n            gasTokenAddress,\n            sequencerURL,\n            networkName\n        );\n    }\n\n    /**\n     * @notice Add an already deployed rollup\n     * note that this rollup does not follow any rollupType\n     * @param rollupAddress Rollup address\n     * @param verifier Verifier address, must be added before\n     * @param forkID Fork id of the added rollup\n     * @param chainID Chain id of the added rollup\n     * @param genesis Genesis block for this rollup\n     * @param rollupCompatibilityID Compatibility ID for the added rollup\n     */\n    function addExistingRollup(\n        IPolygonRollupBase rollupAddress,\n        IVerifierRollup verifier,\n        uint64 forkID,\n        uint64 chainID,\n        bytes32 genesis,\n        uint8 rollupCompatibilityID\n    ) external onlyRole(_ADD_EXISTING_ROLLUP_ROLE) {\n        // Check chainID nullifier\n        if (chainIDToRollupID[chainID] != 0) {\n            revert ChainIDAlreadyExist();\n        }\n\n        // Check if rollup address was already added\n        if (rollupAddressToID[address(rollupAddress)] != 0) {\n            revert RollupAddressAlreadyExist();\n        }\n\n        RollupData storage rollup = _addExistingRollup(\n            rollupAddress,\n            verifier,\n            forkID,\n            chainID,\n            rollupCompatibilityID,\n            0 // last verified batch it's always 0\n        );\n        rollup.batchNumToStateRoot[0] = genesis;\n    }\n\n    /**\n     * @notice Add an already deployed rollup\n     * note that this rollup does not follow any rollupType\n     * @param rollupAddress Rollup address\n     * @param verifier Verifier address, must be added before\n     * @param forkID Fork id of the added rollup\n     * @param chainID Chain id of the added rollup\n     * @param rollupCompatibilityID Compatibility ID for the added rollup\n     * @param lastVerifiedBatch Last verified batch before adding the rollup\n     */\n    function _addExistingRollup(\n        IPolygonRollupBase rollupAddress,\n        IVerifierRollup verifier,\n        uint64 forkID,\n        uint64 chainID,\n        uint8 rollupCompatibilityID,\n        uint64 lastVerifiedBatch\n    ) internal returns (RollupData storage rollup) {\n        uint32 rollupID = ++rollupCount;\n\n        // Set chainID nullifier\n        chainIDToRollupID[chainID] = rollupID;\n\n        // Store rollup data\n        rollupAddressToID[address(rollupAddress)] = rollupID;\n\n        rollup = rollupIDToRollupData[rollupID];\n        rollup.rollupContract = rollupAddress;\n        rollup.forkID = forkID;\n        rollup.verifier = verifier;\n        rollup.chainID = chainID;\n        rollup.rollupCompatibilityID = rollupCompatibilityID;\n        // rollup type is 0, since it does not follow any rollup type\n\n        emit AddExistingRollup(\n            rollupID,\n            forkID,\n            address(rollupAddress),\n            chainID,\n            rollupCompatibilityID,\n            lastVerifiedBatch\n        );\n    }\n\n    /**\n     * @notice Upgrade an existing rollup\n     * @param rollupContract Rollup consensus proxy address\n     * @param newRollupTypeID New rolluptypeID to upgrade to\n     * @param upgradeData Upgrade data\n     */\n    function updateRollup(\n        ITransparentUpgradeableProxy rollupContract,\n        uint32 newRollupTypeID,\n        bytes calldata upgradeData\n    ) external onlyRole(_UPDATE_ROLLUP_ROLE) {\n        // Check that rollup type exists\n        if (newRollupTypeID == 0 || newRollupTypeID > rollupTypeCount) {\n            revert RollupTypeDoesNotExist();\n        }\n\n        // Check the rollup exists\n        uint32 rollupID = rollupAddressToID[address(rollupContract)];\n        if (rollupID == 0) {\n            revert RollupMustExist();\n        }\n\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n\n        // The update must be to a new rollup type\n        if (rollup.rollupTypeID == newRollupTypeID) {\n            revert UpdateToSameRollupTypeID();\n        }\n\n        RollupType storage newRollupType = rollupTypeMap[newRollupTypeID];\n\n        // Check rollup type is not obsolete\n        if (newRollupType.obsolete == true) {\n            revert RollupTypeObsolete();\n        }\n\n        // Check compatibility of the rollups\n        if (\n            rollup.rollupCompatibilityID != newRollupType.rollupCompatibilityID\n        ) {\n            revert UpdateNotCompatible();\n        }\n\n        // Update rollup parameters\n        rollup.verifier = newRollupType.verifier;\n        rollup.forkID = newRollupType.forkID;\n        rollup.rollupTypeID = newRollupTypeID;\n\n        uint64 lastVerifiedBatch = getLastVerifiedBatch(rollupID);\n        rollup.lastVerifiedBatchBeforeUpgrade = lastVerifiedBatch;\n\n        // Upgrade rollup\n        rollupContract.upgradeToAndCall(\n            newRollupType.consensusImplementation,\n            upgradeData\n        );\n\n        emit UpdateRollup(rollupID, newRollupTypeID, lastVerifiedBatch);\n    }\n\n    /////////////////////////////////////\n    // Sequence/Verify batches functions\n    ////////////////////////////////////\n\n    /**\n     * @notice Sequence batches, callback called by one of the consensus managed by this contract\n     * @param newSequencedBatches Number of batches sequenced\n     * @param newAccInputHash New accumulate input hash\n     */\n    function onSequenceBatches(\n        uint64 newSequencedBatches,\n        bytes32 newAccInputHash\n    ) external ifNotEmergencyState returns (uint64) {\n        // Check that the msg.sender is an added rollup\n        uint32 rollupID = rollupAddressToID[msg.sender];\n        if (rollupID == 0) {\n            revert SenderMustBeRollup();\n        }\n\n        // This prevents overwritting sequencedBatches\n        if (newSequencedBatches == 0) {\n            revert MustSequenceSomeBatch();\n        }\n\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n\n        // Update total sequence parameters\n        totalSequencedBatches += newSequencedBatches;\n\n        // Update sequenced batches of the current rollup\n        uint64 previousLastBatchSequenced = rollup.lastBatchSequenced;\n        uint64 newLastBatchSequenced = previousLastBatchSequenced +\n            newSequencedBatches;\n\n        rollup.lastBatchSequenced = newLastBatchSequenced;\n        rollup.sequencedBatches[newLastBatchSequenced] = SequencedBatchData({\n            accInputHash: newAccInputHash,\n            sequencedTimestamp: uint64(block.timestamp),\n            previousLastBatchSequenced: previousLastBatchSequenced\n        });\n\n        // Consolidate pending state if possible\n        _tryConsolidatePendingState(rollup);\n\n        emit OnSequenceBatches(rollupID, newLastBatchSequenced);\n\n        return newLastBatchSequenced;\n    }\n\n    /**\n     * @notice Allows an aggregator to verify multiple batches\n     * @param rollupID Rollup identifier\n     * @param pendingStateNum Init pending state, 0 if consolidated state is used\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot New local exit root once the batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     * @param beneficiary Address that will receive the verification reward\n     * @param proof Fflonk proof\n     */\n    function verifyBatches(\n        uint32 rollupID,\n        uint64 pendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        address beneficiary,\n        bytes32[24] calldata proof\n    ) external ifNotEmergencyState {\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n\n        // Check if the trusted aggregator timeout expired,\n        // Note that the sequencedBatches struct must exists for this finalNewBatch, if not newAccInputHash will be 0\n        if (\n            rollup.sequencedBatches[finalNewBatch].sequencedTimestamp +\n                trustedAggregatorTimeout >\n            block.timestamp\n        ) {\n            revert TrustedAggregatorTimeoutNotExpired();\n        }\n\n        if (finalNewBatch - initNumBatch > _MAX_VERIFY_BATCHES) {\n            revert ExceedMaxVerifyBatches();\n        }\n\n        _verifyAndRewardBatches(\n            rollup,\n            pendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            beneficiary,\n            proof\n        );\n\n        // Update batch fees\n        _updateBatchFee(rollup, finalNewBatch);\n\n        if (pendingStateTimeout == 0) {\n            // Consolidate state\n            rollup.lastVerifiedBatch = finalNewBatch;\n            rollup.batchNumToStateRoot[finalNewBatch] = newStateRoot;\n            rollup.lastLocalExitRoot = newLocalExitRoot;\n\n            // Clean pending state if any\n            if (rollup.lastPendingState > 0) {\n                rollup.lastPendingState = 0;\n                rollup.lastPendingStateConsolidated = 0;\n            }\n\n            // Interact with globalExitRootManager\n            globalExitRootManager.updateExitRoot(getRollupExitRoot());\n        } else {\n            // Consolidate pending state if possible\n            _tryConsolidatePendingState(rollup);\n\n            // Update pending state\n            rollup.lastPendingState++;\n            rollup.pendingStateTransitions[\n                rollup.lastPendingState\n            ] = PendingState({\n                timestamp: uint64(block.timestamp),\n                lastVerifiedBatch: finalNewBatch,\n                exitRoot: newLocalExitRoot,\n                stateRoot: newStateRoot\n            });\n        }\n\n        emit VerifyBatches(\n            rollupID,\n            finalNewBatch,\n            newStateRoot,\n            newLocalExitRoot,\n            msg.sender\n        );\n    }\n\n    /**\n     * @notice Allows a trusted aggregator to verify multiple batches\n     * @param rollupID Rollup identifier\n     * @param pendingStateNum Init pending state, 0 if consolidated state is used\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot New local exit root once the batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     * @param beneficiary Address that will receive the verification reward\n     * @param proof Fflonk proof\n     */\n    function verifyBatchesTrustedAggregator(\n        uint32 rollupID,\n        uint64 pendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        address beneficiary,\n        bytes32[24] calldata proof\n    ) external onlyRole(_TRUSTED_AGGREGATOR_ROLE) {\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n\n        _verifyAndRewardBatches(\n            rollup,\n            pendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            beneficiary,\n            proof\n        );\n\n        // Consolidate state\n        rollup.lastVerifiedBatch = finalNewBatch;\n        rollup.batchNumToStateRoot[finalNewBatch] = newStateRoot;\n        rollup.lastLocalExitRoot = newLocalExitRoot;\n\n        // Clean pending state if any\n        if (rollup.lastPendingState > 0) {\n            rollup.lastPendingState = 0;\n            rollup.lastPendingStateConsolidated = 0;\n        }\n\n        // Interact with globalExitRootManager\n        globalExitRootManager.updateExitRoot(getRollupExitRoot());\n\n        emit VerifyBatchesTrustedAggregator(\n            rollupID,\n            finalNewBatch,\n            newStateRoot,\n            newLocalExitRoot,\n            msg.sender\n        );\n    }\n\n    /**\n     * @notice Verify and reward batches internal function\n     * @param rollup Rollup Data storage pointer that will be used to the verification\n     * @param pendingStateNum Init pending state, 0 if consolidated state is used\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot New local exit root once the batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     * @param beneficiary Address that will receive the verification reward\n     * @param proof Fflonk proof\n     */\n    function _verifyAndRewardBatches(\n        RollupData storage rollup,\n        uint64 pendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        address beneficiary,\n        bytes32[24] calldata proof\n    ) internal virtual {\n        bytes32 oldStateRoot;\n        uint64 currentLastVerifiedBatch = _getLastVerifiedBatch(rollup);\n\n        if (initNumBatch < rollup.lastVerifiedBatchBeforeUpgrade) {\n            revert InitBatchMustMatchCurrentForkID();\n        }\n\n        // Use pending state if specified, otherwise use consolidated state\n        if (pendingStateNum != 0) {\n            // Check that pending state exist\n            // Already consolidated pending states can be used aswell\n            if (pendingStateNum > rollup.lastPendingState) {\n                revert PendingStateDoesNotExist();\n            }\n\n            // Check choosen pending state\n            PendingState storage currentPendingState = rollup\n                .pendingStateTransitions[pendingStateNum];\n\n            // Get oldStateRoot from pending batch\n            oldStateRoot = currentPendingState.stateRoot;\n\n            // Check initNumBatch matches the pending state\n            if (initNumBatch != currentPendingState.lastVerifiedBatch) {\n                revert InitNumBatchDoesNotMatchPendingState();\n            }\n        } else {\n            // Use consolidated state\n            oldStateRoot = rollup.batchNumToStateRoot[initNumBatch];\n\n            if (oldStateRoot == bytes32(0)) {\n                revert OldStateRootDoesNotExist();\n            }\n\n            // Check initNumBatch is inside the range, sanity check\n            if (initNumBatch > currentLastVerifiedBatch) {\n                revert InitNumBatchAboveLastVerifiedBatch();\n            }\n        }\n\n        // Check final batch\n        if (finalNewBatch <= currentLastVerifiedBatch) {\n            revert FinalNumBatchBelowLastVerifiedBatch();\n        }\n\n        // Get snark bytes\n        bytes memory snarkHashBytes = _getInputSnarkBytes(\n            rollup,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            oldStateRoot,\n            newStateRoot\n        );\n\n        // Calulate the snark input\n        uint256 inputSnark = uint256(sha256(snarkHashBytes)) % _RFIELD;\n\n        // Verify proof\n        if (!rollup.verifier.verifyProof(proof, [inputSnark])) {\n            revert InvalidProof();\n        }\n\n        // Pay POL rewards\n        uint64 newVerifiedBatches = finalNewBatch - currentLastVerifiedBatch;\n\n        pol.safeTransfer(\n            beneficiary,\n            calculateRewardPerBatch() * newVerifiedBatches\n        );\n\n        // Update aggregation parameters\n        totalVerifiedBatches += newVerifiedBatches;\n        lastAggregationTimestamp = uint64(block.timestamp);\n\n        // Callback to the rollup address\n        rollup.rollupContract.onVerifyBatches(\n            finalNewBatch,\n            newStateRoot,\n            msg.sender\n        );\n    }\n\n    /**\n     * @notice Internal function to consolidate the state automatically once sequence or verify batches are called\n     * It tries to consolidate the first and the middle pending state in the queue\n     */\n    function _tryConsolidatePendingState(RollupData storage rollup) internal {\n        // Check if there's any state to consolidate\n        if (rollup.lastPendingState > rollup.lastPendingStateConsolidated) {\n            // Check if it's possible to consolidate the next pending state\n            uint64 nextPendingState = rollup.lastPendingStateConsolidated + 1;\n            if (_isPendingStateConsolidable(rollup, nextPendingState)) {\n                // Check middle pending state ( binary search of 1 step)\n                uint64 middlePendingState = nextPendingState +\n                    (rollup.lastPendingState - nextPendingState) /\n                    2;\n\n                // Try to consolidate it, and if not, consolidate the nextPendingState\n                if (_isPendingStateConsolidable(rollup, middlePendingState)) {\n                    _consolidatePendingState(rollup, middlePendingState);\n                } else {\n                    _consolidatePendingState(rollup, nextPendingState);\n                }\n            }\n        }\n    }\n\n    /**\n     * @notice Allows to consolidate any pending state that has already exceed the pendingStateTimeout\n     * Can be called by the trusted aggregator, which can consolidate any state without the timeout restrictions\n     * @param rollupID Rollup identifier\n     * @param pendingStateNum Pending state to consolidate\n     */\n    function consolidatePendingState(\n        uint32 rollupID,\n        uint64 pendingStateNum\n    ) external {\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n        // Check if pending state can be consolidated\n        // If trusted aggregator is the sender, do not check the timeout or the emergency state\n        if (!hasRole(_TRUSTED_AGGREGATOR_ROLE, msg.sender)) {\n            if (isEmergencyState) {\n                revert OnlyNotEmergencyState();\n            }\n\n            if (!_isPendingStateConsolidable(rollup, pendingStateNum)) {\n                revert PendingStateNotConsolidable();\n            }\n        }\n        _consolidatePendingState(rollup, pendingStateNum);\n    }\n\n    /**\n     * @notice Internal function to consolidate any pending state that has already exceed the pendingStateTimeout\n     * @param rollup Rollup data storage pointer\n     * @param pendingStateNum Pending state to consolidate\n     */\n    function _consolidatePendingState(\n        RollupData storage rollup,\n        uint64 pendingStateNum\n    ) internal {\n        // Check if pendingStateNum is in correct range\n        // - not consolidated (implicity checks that is not 0)\n        // - exist ( has been added)\n        if (\n            pendingStateNum <= rollup.lastPendingStateConsolidated ||\n            pendingStateNum > rollup.lastPendingState\n        ) {\n            revert PendingStateInvalid();\n        }\n\n        PendingState storage currentPendingState = rollup\n            .pendingStateTransitions[pendingStateNum];\n\n        // Update state\n        uint64 newLastVerifiedBatch = currentPendingState.lastVerifiedBatch;\n        rollup.lastVerifiedBatch = newLastVerifiedBatch;\n        rollup.batchNumToStateRoot[newLastVerifiedBatch] = currentPendingState\n            .stateRoot;\n        rollup.lastLocalExitRoot = currentPendingState.exitRoot;\n\n        // Update pending state\n        rollup.lastPendingStateConsolidated = pendingStateNum;\n\n        // Interact with globalExitRootManager\n        globalExitRootManager.updateExitRoot(getRollupExitRoot());\n\n        emit ConsolidatePendingState(\n            rollupAddressToID[address(rollup.rollupContract)],\n            newLastVerifiedBatch,\n            currentPendingState.stateRoot,\n            currentPendingState.exitRoot,\n            pendingStateNum\n        );\n    }\n\n    /////////////////////////////////\n    // Soundness protection functions\n    /////////////////////////////////\n\n    /**\n     * @notice Allows the trusted aggregator to override the pending state\n     * if it's possible to prove a different state root given the same batches\n     * @param rollupID Rollup identifier\n     * @param initPendingStateNum Init pending state, 0 if consolidated state is used\n     * @param finalPendingStateNum Final pending state, that will be used to compare with the newStateRoot\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot  New local exit root once the batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     * @param proof Fflonk proof\n     */\n    function overridePendingState(\n        uint32 rollupID,\n        uint64 initPendingStateNum,\n        uint64 finalPendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        bytes32[24] calldata proof\n    ) external onlyRole(_TRUSTED_AGGREGATOR_ROLE) {\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n\n        _proveDistinctPendingState(\n            rollup,\n            initPendingStateNum,\n            finalPendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            proof\n        );\n\n        // Consolidate state\n        rollup.lastVerifiedBatch = finalNewBatch;\n        rollup.batchNumToStateRoot[finalNewBatch] = newStateRoot;\n        rollup.lastLocalExitRoot = newLocalExitRoot;\n\n        // Clean pending state if any\n        if (rollup.lastPendingState > 0) {\n            rollup.lastPendingState = 0;\n            rollup.lastPendingStateConsolidated = 0;\n        }\n\n        // Interact with globalExitRootManager\n        globalExitRootManager.updateExitRoot(getRollupExitRoot());\n\n        // Update trusted aggregator timeout to max\n        trustedAggregatorTimeout = _HALT_AGGREGATION_TIMEOUT;\n\n        emit OverridePendingState(\n            rollupID,\n            finalNewBatch,\n            newStateRoot,\n            newLocalExitRoot,\n            msg.sender\n        );\n    }\n\n    /**\n     * @notice Allows activate the emergency state if its possible to prove a different state root given the same batches\n     * @param rollupID Rollup identifier\n     * @param initPendingStateNum Init pending state, 0 if consolidated state is used\n     * @param finalPendingStateNum Final pending state, that will be used to compare with the newStateRoot\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot  New local exit root once the batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     * @param proof Fflonk proof\n     */\n    function proveNonDeterministicPendingState(\n        uint32 rollupID,\n        uint64 initPendingStateNum,\n        uint64 finalPendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        bytes32[24] calldata proof\n    ) external ifNotEmergencyState {\n        RollupData storage rollup = rollupIDToRollupData[rollupID];\n\n        _proveDistinctPendingState(\n            rollup,\n            initPendingStateNum,\n            finalPendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            proof\n        );\n\n        emit ProveNonDeterministicPendingState(\n            rollup.pendingStateTransitions[finalPendingStateNum].stateRoot,\n            newStateRoot\n        );\n\n        // Activate emergency state\n        _activateEmergencyState();\n    }\n\n    /**\n     * @notice Internal function that proves a different state root given the same batches to verify\n     * @param rollup Rollup Data struct that will be checked\n     * @param initPendingStateNum Init pending state, 0 if consolidated state is used\n     * @param finalPendingStateNum Final pending state, that will be used to compare with the newStateRoot\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot  New local exit root once the batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     * @param proof Fflonk proof\n     */\n    function _proveDistinctPendingState(\n        RollupData storage rollup,\n        uint64 initPendingStateNum,\n        uint64 finalPendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        bytes32[24] calldata proof\n    ) internal view virtual {\n        bytes32 oldStateRoot;\n\n        if (initNumBatch < rollup.lastVerifiedBatchBeforeUpgrade) {\n            revert InitBatchMustMatchCurrentForkID();\n        }\n\n        // Use pending state if specified, otherwise use consolidated state\n        if (initPendingStateNum != 0) {\n            // Check that pending state exist\n            // Already consolidated pending states can be used aswell\n            if (initPendingStateNum > rollup.lastPendingState) {\n                revert PendingStateDoesNotExist();\n            }\n\n            // Check choosen pending state\n            PendingState storage initPendingState = rollup\n                .pendingStateTransitions[initPendingStateNum];\n\n            // Get oldStateRoot from init pending state\n            oldStateRoot = initPendingState.stateRoot;\n\n            // Check initNumBatch matches the init pending state\n            if (initNumBatch != initPendingState.lastVerifiedBatch) {\n                revert InitNumBatchDoesNotMatchPendingState();\n            }\n        } else {\n            // Use consolidated state\n            oldStateRoot = rollup.batchNumToStateRoot[initNumBatch];\n            if (oldStateRoot == bytes32(0)) {\n                revert OldStateRootDoesNotExist();\n            }\n\n            // Check initNumBatch is inside the range, sanity check\n            if (initNumBatch > rollup.lastVerifiedBatch) {\n                revert InitNumBatchAboveLastVerifiedBatch();\n            }\n        }\n\n        // Assert final pending state num is in correct range\n        // - exist ( has been added)\n        // - bigger than the initPendingstate\n        // - not consolidated\n        if (\n            finalPendingStateNum > rollup.lastPendingState ||\n            finalPendingStateNum <= initPendingStateNum ||\n            finalPendingStateNum <= rollup.lastPendingStateConsolidated\n        ) {\n            revert FinalPendingStateNumInvalid();\n        }\n\n        // Check final num batch\n        if (\n            finalNewBatch !=\n            rollup\n                .pendingStateTransitions[finalPendingStateNum]\n                .lastVerifiedBatch\n        ) {\n            revert FinalNumBatchDoesNotMatchPendingState();\n        }\n\n        // Get snark bytes\n        bytes memory snarkHashBytes = _getInputSnarkBytes(\n            rollup,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            oldStateRoot,\n            newStateRoot\n        );\n\n        // Calulate the snark input\n        uint256 inputSnark = uint256(sha256(snarkHashBytes)) % _RFIELD;\n\n        // Verify proof\n        if (!rollup.verifier.verifyProof(proof, [inputSnark])) {\n            revert InvalidProof();\n        }\n\n        if (\n            rollup.pendingStateTransitions[finalPendingStateNum].stateRoot ==\n            newStateRoot\n        ) {\n            revert StoredRootMustBeDifferentThanNewRoot();\n        }\n    }\n\n    /**\n     * @notice Function to update the batch fee based on the new verified batches\n     * The batch fee will not be updated when the trusted aggregator verifies batches\n     * @param newLastVerifiedBatch New last verified batch\n     */\n    function _updateBatchFee(\n        RollupData storage rollup,\n        uint64 newLastVerifiedBatch\n    ) internal {\n        uint64 currentLastVerifiedBatch = _getLastVerifiedBatch(rollup);\n        uint64 currentBatch = newLastVerifiedBatch;\n\n        uint256 totalBatchesAboveTarget;\n        uint256 newBatchesVerified = newLastVerifiedBatch -\n            currentLastVerifiedBatch;\n\n        uint256 targetTimestamp = block.timestamp - verifyBatchTimeTarget;\n\n        while (currentBatch != currentLastVerifiedBatch) {\n            // Load sequenced batchdata\n            SequencedBatchData storage currentSequencedBatchData = rollup\n                .sequencedBatches[currentBatch];\n\n            // Check if timestamp is below the verifyBatchTimeTarget\n            if (\n                targetTimestamp < currentSequencedBatchData.sequencedTimestamp\n            ) {\n                // update currentBatch\n                currentBatch = currentSequencedBatchData\n                    .previousLastBatchSequenced;\n            } else {\n                // The rest of batches will be above\n                totalBatchesAboveTarget =\n                    currentBatch -\n                    currentLastVerifiedBatch;\n                break;\n            }\n        }\n\n        uint256 totalBatchesBelowTarget = newBatchesVerified -\n            totalBatchesAboveTarget;\n\n        // _MAX_BATCH_FEE --> (< 70 bits)\n        // multiplierBatchFee --> (< 10 bits)\n        // _MAX_BATCH_MULTIPLIER = 12\n        // multiplierBatchFee ** _MAX_BATCH_MULTIPLIER --> (< 128 bits)\n        // batchFee * (multiplierBatchFee ** _MAX_BATCH_MULTIPLIER)-->\n        // (< 70 bits) * (< 128 bits) = < 256 bits\n\n        // Since all the following operations cannot overflow, we can optimize this operations with unchecked\n        unchecked {\n            if (totalBatchesBelowTarget < totalBatchesAboveTarget) {\n                // There are more batches above target, fee is multiplied\n                uint256 diffBatches = totalBatchesAboveTarget -\n                    totalBatchesBelowTarget;\n\n                diffBatches = diffBatches > _MAX_BATCH_MULTIPLIER\n                    ? _MAX_BATCH_MULTIPLIER\n                    : diffBatches;\n\n                // For every multiplierBatchFee multiplication we must shift 3 zeroes since we have 3 decimals\n                _batchFee =\n                    (_batchFee * (uint256(multiplierBatchFee) ** diffBatches)) /\n                    (uint256(1000) ** diffBatches);\n            } else {\n                // There are more batches below target, fee is divided\n                uint256 diffBatches = totalBatchesBelowTarget -\n                    totalBatchesAboveTarget;\n\n                diffBatches = diffBatches > _MAX_BATCH_MULTIPLIER\n                    ? _MAX_BATCH_MULTIPLIER\n                    : diffBatches;\n\n                // For every multiplierBatchFee multiplication we must shift 3 zeroes since we have 3 decimals\n                uint256 accDivisor = (uint256(1 ether) *\n                    (uint256(multiplierBatchFee) ** diffBatches)) /\n                    (uint256(1000) ** diffBatches);\n\n                // multiplyFactor = multiplierBatchFee ** diffBatches / 10 ** (diffBatches * 3)\n                // accDivisor = 1E18 * multiplyFactor\n                // 1E18 * batchFee / accDivisor = batchFee / multiplyFactor\n                // < 60 bits * < 70 bits / ~60 bits --> overflow not possible\n                _batchFee = (uint256(1 ether) * _batchFee) / accDivisor;\n            }\n        }\n\n        // Batch fee must remain inside a range\n        if (_batchFee > _MAX_BATCH_FEE) {\n            _batchFee = _MAX_BATCH_FEE;\n        } else if (_batchFee < _MIN_BATCH_FEE) {\n            _batchFee = _MIN_BATCH_FEE;\n        }\n    }\n\n    ////////////////////////\n    // Emergency state functions\n    ////////////////////////\n\n    /**\n     * @notice Function to activate emergency state, which also enables the emergency mode on both PolygonRollupManager and PolygonZkEVMBridge contracts\n     * If not called by the owner must not have been aggregated in a _HALT_AGGREGATION_TIMEOUT period and an emergency state was not happened in the same period\n     */\n    function activateEmergencyState() external {\n        if (!hasRole(_EMERGENCY_COUNCIL_ROLE, msg.sender)) {\n            if (\n                lastAggregationTimestamp == 0 ||\n                lastAggregationTimestamp + _HALT_AGGREGATION_TIMEOUT >\n                block.timestamp ||\n                lastDeactivatedEmergencyStateTimestamp +\n                    _HALT_AGGREGATION_TIMEOUT >\n                block.timestamp\n            ) {\n                revert HaltTimeoutNotExpired();\n            }\n        }\n        _activateEmergencyState();\n    }\n\n    /**\n     * @notice Function to deactivate emergency state on both PolygonRollupManager and PolygonZkEVMBridge contracts\n     */\n    function deactivateEmergencyState()\n        external\n        onlyRole(_STOP_EMERGENCY_ROLE)\n    {\n        // Set last deactivated emergency state\n        lastDeactivatedEmergencyStateTimestamp = uint64(block.timestamp);\n\n        // Deactivate emergency state on PolygonZkEVMBridge\n        bridgeAddress.deactivateEmergencyState();\n\n        // Deactivate emergency state on this contract\n        super._deactivateEmergencyState();\n    }\n\n    /**\n     * @notice Internal function to activate emergency state on both PolygonRollupManager and PolygonZkEVMBridge contracts\n     */\n    function _activateEmergencyState() internal override {\n        // Activate emergency state on PolygonZkEVM Bridge\n        bridgeAddress.activateEmergencyState();\n\n        // Activate emergency state on this contract\n        super._activateEmergencyState();\n    }\n\n    //////////////////\n    // Setter functions\n    //////////////////\n\n    /**\n     * @notice Set a new pending state timeout\n     * The timeout can only be lowered, except if emergency state is active\n     * @param newTrustedAggregatorTimeout Trusted aggregator timeout\n     */\n    function setTrustedAggregatorTimeout(\n        uint64 newTrustedAggregatorTimeout\n    ) external onlyRole(_TWEAK_PARAMETERS_ROLE) {\n        if (!isEmergencyState) {\n            if (newTrustedAggregatorTimeout >= trustedAggregatorTimeout) {\n                revert NewTrustedAggregatorTimeoutMustBeLower();\n            }\n        }\n\n        trustedAggregatorTimeout = newTrustedAggregatorTimeout;\n        emit SetTrustedAggregatorTimeout(newTrustedAggregatorTimeout);\n    }\n\n    /**\n     * @notice Set a new trusted aggregator timeout\n     * The timeout can only be lowered, except if emergency state is active\n     * @param newPendingStateTimeout Trusted aggregator timeout\n     */\n    function setPendingStateTimeout(\n        uint64 newPendingStateTimeout\n    ) external onlyRole(_TWEAK_PARAMETERS_ROLE) {\n        if (!isEmergencyState) {\n            if (newPendingStateTimeout >= pendingStateTimeout) {\n                revert NewPendingStateTimeoutMustBeLower();\n            }\n        }\n\n        pendingStateTimeout = newPendingStateTimeout;\n        emit SetPendingStateTimeout(newPendingStateTimeout);\n    }\n\n    /**\n     * @notice Set a new multiplier batch fee\n     * @param newMultiplierBatchFee multiplier batch fee\n     */\n    function setMultiplierBatchFee(\n        uint16 newMultiplierBatchFee\n    ) external onlyRole(_TWEAK_PARAMETERS_ROLE) {\n        if (newMultiplierBatchFee < 1000 || newMultiplierBatchFee > 1023) {\n            revert InvalidRangeMultiplierBatchFee();\n        }\n\n        multiplierBatchFee = newMultiplierBatchFee;\n        emit SetMultiplierBatchFee(newMultiplierBatchFee);\n    }\n\n    /**\n     * @notice Set a new verify batch time target\n     * This value will only be relevant once the aggregation is decentralized, so\n     * the trustedAggregatorTimeout should be zero or very close to zero\n     * @param newVerifyBatchTimeTarget Verify batch time target\n     */\n    function setVerifyBatchTimeTarget(\n        uint64 newVerifyBatchTimeTarget\n    ) external onlyRole(_TWEAK_PARAMETERS_ROLE) {\n        if (newVerifyBatchTimeTarget > 1 days) {\n            revert InvalidRangeBatchTimeTarget();\n        }\n        verifyBatchTimeTarget = newVerifyBatchTimeTarget;\n        emit SetVerifyBatchTimeTarget(newVerifyBatchTimeTarget);\n    }\n\n    /**\n     * @notice Set the current batch fee\n     * @param newBatchFee new batch fee\n     */\n    function setBatchFee(uint256 newBatchFee) external onlyRole(_SET_FEE_ROLE) {\n        // check fees min and max\n        if (newBatchFee > _MAX_BATCH_FEE || newBatchFee < _MIN_BATCH_FEE) {\n            revert BatchFeeOutOfRange();\n        }\n        _batchFee = newBatchFee;\n        emit SetBatchFee(newBatchFee);\n    }\n\n    ////////////////////////\n    // view/pure functions\n    ///////////////////////\n\n    /**\n     * @notice Get the current rollup exit root\n     * Compute using all the local exit roots of all rollups the rollup exit root\n     * Since it's expected to have no more than 10 rollups in this first version, even if this approach\n     * has a gas consumption that scales linearly with the rollups added, it's ok\n     * In a future versions this computation will be done inside the circuit\n     */\n    function getRollupExitRoot() public view returns (bytes32) {\n        uint256 currentNodes = rollupCount;\n\n        // If there are no nodes return 0\n        if (currentNodes == 0) {\n            return bytes32(0);\n        }\n\n        // This array will contain the nodes of the current iteration\n        bytes32[] memory tmpTree = new bytes32[](currentNodes);\n\n        // In the first iteration the nodes will be the leafs which are the local exit roots of each network\n        for (uint256 i = 0; i < currentNodes; i++) {\n            // The first rollup ID starts on 1\n            tmpTree[i] = rollupIDToRollupData[uint32(i + 1)].lastLocalExitRoot;\n        }\n\n        // This variable will keep track of the zero hashes\n        bytes32 currentZeroHashHeight = 0;\n\n        // This variable will keep track of the reamining levels to compute\n        uint256 remainingLevels = _EXIT_TREE_DEPTH;\n\n        // Calculate the root of the sub-tree that contains all the localExitRoots\n        while (currentNodes != 1) {\n            uint256 nextIterationNodes = currentNodes / 2 + (currentNodes % 2);\n            bytes32[] memory nextTmpTree = new bytes32[](nextIterationNodes);\n            for (uint256 i = 0; i < nextIterationNodes; i++) {\n                // if we are on the last iteration of the current level and the nodes are odd\n                if (i == nextIterationNodes - 1 && (currentNodes % 2) == 1) {\n                    nextTmpTree[i] = keccak256(\n                        abi.encodePacked(tmpTree[i * 2], currentZeroHashHeight)\n                    );\n                } else {\n                    nextTmpTree[i] = keccak256(\n                        abi.encodePacked(tmpTree[i * 2], tmpTree[(i * 2) + 1])\n                    );\n                }\n            }\n\n            // Update tree variables\n            tmpTree = nextTmpTree;\n            currentNodes = nextIterationNodes;\n            currentZeroHashHeight = keccak256(\n                abi.encodePacked(currentZeroHashHeight, currentZeroHashHeight)\n            );\n            remainingLevels--;\n        }\n\n        bytes32 currentRoot = tmpTree[0];\n\n        // Calculate remaining levels, since it's a sequencial merkle tree, the rest of the tree are zeroes\n        for (uint256 i = 0; i < remainingLevels; i++) {\n            currentRoot = keccak256(\n                abi.encodePacked(currentRoot, currentZeroHashHeight)\n            );\n            currentZeroHashHeight = keccak256(\n                abi.encodePacked(currentZeroHashHeight, currentZeroHashHeight)\n            );\n        }\n        return currentRoot;\n    }\n\n    /**\n     * @notice Get the last verified batch\n     */\n    function getLastVerifiedBatch(\n        uint32 rollupID\n    ) public view returns (uint64) {\n        return _getLastVerifiedBatch(rollupIDToRollupData[rollupID]);\n    }\n\n    /**\n     * @notice Get the last verified batch\n     */\n    function _getLastVerifiedBatch(\n        RollupData storage rollup\n    ) internal view returns (uint64) {\n        if (rollup.lastPendingState > 0) {\n            return\n                rollup\n                    .pendingStateTransitions[rollup.lastPendingState]\n                    .lastVerifiedBatch;\n        } else {\n            return rollup.lastVerifiedBatch;\n        }\n    }\n\n    /**\n     * @notice Returns a boolean that indicates if the pendingStateNum is or not consolidable\n     * @param rollupID Rollup id\n     * @param pendingStateNum Pending state number to check\n     * Note that his function does not check if the pending state currently exists, or if it's consolidated already\n     */\n    function isPendingStateConsolidable(\n        uint32 rollupID,\n        uint64 pendingStateNum\n    ) public view returns (bool) {\n        return\n            _isPendingStateConsolidable(\n                rollupIDToRollupData[rollupID],\n                pendingStateNum\n            );\n    }\n\n    /**\n     * @notice Returns a boolean that indicates if the pendingStateNum is or not consolidable\n     * @param rollup Rollup data storage pointer\n     * @param pendingStateNum Pending state number to check\n     * Note that his function does not check if the pending state currently exists, or if it's consolidated already\n     */\n    function _isPendingStateConsolidable(\n        RollupData storage rollup,\n        uint64 pendingStateNum\n    ) internal view returns (bool) {\n        return (rollup.pendingStateTransitions[pendingStateNum].timestamp +\n            pendingStateTimeout <=\n            block.timestamp);\n    }\n\n    /**\n     * @notice Function to calculate the reward to verify a single batch\n     */\n    function calculateRewardPerBatch() public view returns (uint256) {\n        uint256 currentBalance = pol.balanceOf(address(this));\n\n        // Total Batches to be verified = total Sequenced Batches - total verified Batches\n        uint256 totalBatchesToVerify = totalSequencedBatches -\n            totalVerifiedBatches;\n\n        if (totalBatchesToVerify == 0) return 0;\n        return currentBalance / totalBatchesToVerify;\n    }\n\n    /**\n     * @notice Get batch fee\n     * This function is used instad of the automatic public view one,\n     * because in a future might change the behaviour and we will be able to mantain the interface\n     */\n    function getBatchFee() public view returns (uint256) {\n        return _batchFee;\n    }\n\n    /**\n     * @notice Get forced batch fee\n     */\n    function getForcedBatchFee() public view returns (uint256) {\n        return _batchFee * 100;\n    }\n\n    /**\n     * @notice Function to calculate the input snark bytes\n     * @param rollupID Rollup id used to calculate the input snark bytes\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot New local exit root once the batch is processed\n     * @param oldStateRoot State root before batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     */\n    function getInputSnarkBytes(\n        uint32 rollupID,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 oldStateRoot,\n        bytes32 newStateRoot\n    ) public view returns (bytes memory) {\n        return\n            _getInputSnarkBytes(\n                rollupIDToRollupData[rollupID],\n                initNumBatch,\n                finalNewBatch,\n                newLocalExitRoot,\n                oldStateRoot,\n                newStateRoot\n            );\n    }\n\n    /**\n     * @notice Function to calculate the input snark bytes\n     * @param rollup Rollup data storage pointer\n     * @param initNumBatch Batch which the aggregator starts the verification\n     * @param finalNewBatch Last batch aggregator intends to verify\n     * @param newLocalExitRoot New local exit root once the batch is processed\n     * @param oldStateRoot State root before batch is processed\n     * @param newStateRoot New State root once the batch is processed\n     */\n    function _getInputSnarkBytes(\n        RollupData storage rollup,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 oldStateRoot,\n        bytes32 newStateRoot\n    ) internal view returns (bytes memory) {\n        // Sanity check\n        bytes32 oldAccInputHash = rollup\n            .sequencedBatches[initNumBatch]\n            .accInputHash;\n\n        bytes32 newAccInputHash = rollup\n            .sequencedBatches[finalNewBatch]\n            .accInputHash;\n\n        // Sanity check\n        if (initNumBatch != 0 && oldAccInputHash == bytes32(0)) {\n            revert OldAccInputHashDoesNotExist();\n        }\n\n        if (newAccInputHash == bytes32(0)) {\n            revert NewAccInputHashDoesNotExist();\n        }\n\n        // Check that new state root is inside goldilocks field\n        if (!_checkStateRootInsidePrime(uint256(newStateRoot))) {\n            revert NewStateRootNotInsidePrime();\n        }\n\n        return\n            abi.encodePacked(\n                msg.sender,\n                oldStateRoot,\n                oldAccInputHash,\n                initNumBatch,\n                rollup.chainID,\n                rollup.forkID,\n                newStateRoot,\n                newAccInputHash,\n                newLocalExitRoot,\n                finalNewBatch\n            );\n    }\n\n    /**\n     * @notice Function to check if the state root is inside of the prime field\n     * @param newStateRoot New State root once the batch is processed\n     */\n    function _checkStateRootInsidePrime(\n        uint256 newStateRoot\n    ) internal pure returns (bool) {\n        if (\n            ((newStateRoot & _MAX_UINT_64) < _GOLDILOCKS_PRIME_FIELD) &&\n            (((newStateRoot >> 64) & _MAX_UINT_64) < _GOLDILOCKS_PRIME_FIELD) &&\n            (((newStateRoot >> 128) & _MAX_UINT_64) <\n                _GOLDILOCKS_PRIME_FIELD) &&\n            ((newStateRoot >> 192) < _GOLDILOCKS_PRIME_FIELD)\n        ) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @notice Get rollup state root given a batch number\n     * @param rollupID Rollup identifier\n     * @param batchNum Batch number\n     */\n    function getRollupBatchNumToStateRoot(\n        uint32 rollupID,\n        uint64 batchNum\n    ) public view returns (bytes32) {\n        return rollupIDToRollupData[rollupID].batchNumToStateRoot[batchNum];\n    }\n\n    /**\n     * @notice Get rollup sequence batches struct given a batch number\n     * @param rollupID Rollup identifier\n     * @param batchNum Batch number\n     */\n    function getRollupSequencedBatches(\n        uint32 rollupID,\n        uint64 batchNum\n    ) public view returns (SequencedBatchData memory) {\n        return rollupIDToRollupData[rollupID].sequencedBatches[batchNum];\n    }\n\n    /**\n     * @notice Get rollup sequence pending state struct given a batch number\n     * @param rollupID Rollup identifier\n     * @param batchNum Batch number\n     */\n    function getRollupPendingStateTransitions(\n        uint32 rollupID,\n        uint64 batchNum\n    ) public view returns (PendingState memory) {\n        return rollupIDToRollupData[rollupID].pendingStateTransitions[batchNum];\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 999999
      },
      "evmVersion": "shanghai",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}