creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.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 * By default, the owner account will be the one that deploys the contract. This\n * can 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 OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\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        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing 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        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\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    /**\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[49] private __gap;\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/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/access/AccessControl.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\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 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 See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n        return _roles[role].members[account];\n    }\n\n    /**\n     * @dev Revert with a standard message if `_msgSender()` 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, _msgSender());\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(\n                string(\n                    abi.encodePacked(\n                        \"AccessControl: account \",\n                        Strings.toHexString(account),\n                        \" is missing role \",\n                        Strings.toHexString(uint256(role), 32)\n                    )\n                )\n            );\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(bytes32 role) 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(bytes32 role, address account) 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(bytes32 role, address account) 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(bytes32 role, address account) public virtual override {\n        require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\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, _msgSender());\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, _msgSender());\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/access/IAccessControl.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 IAccessControl {\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/governance/TimelockController.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.2) (governance/TimelockController.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../access/AccessControl.sol\";\nimport \"../token/ERC721/IERC721Receiver.sol\";\nimport \"../token/ERC1155/IERC1155Receiver.sol\";\nimport \"../utils/Address.sol\";\n\n/**\n * @dev Contract module which acts as a timelocked controller. When set as the\n * owner of an `Ownable` smart contract, it enforces a timelock on all\n * `onlyOwner` maintenance operations. This gives time for users of the\n * controlled contract to exit before a potentially dangerous maintenance\n * operation is applied.\n *\n * By default, this contract is self administered, meaning administration tasks\n * have to go through the timelock process. The proposer (resp executor) role\n * is in charge of proposing (resp executing) operations. A common use case is\n * to position this {TimelockController} as the owner of a smart contract, with\n * a multisig or a DAO as the sole proposer.\n *\n * _Available since v3.3._\n */\ncontract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver {\n    bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256(\"TIMELOCK_ADMIN_ROLE\");\n    bytes32 public constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n    bytes32 public constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n    bytes32 public constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n    uint256 internal constant _DONE_TIMESTAMP = uint256(1);\n\n    mapping(bytes32 => uint256) private _timestamps;\n    uint256 private _minDelay;\n\n    /**\n     * @dev Emitted when a call is scheduled as part of operation `id`.\n     */\n    event CallScheduled(\n        bytes32 indexed id,\n        uint256 indexed index,\n        address target,\n        uint256 value,\n        bytes data,\n        bytes32 predecessor,\n        uint256 delay\n    );\n\n    /**\n     * @dev Emitted when a call is performed as part of operation `id`.\n     */\n    event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);\n\n    /**\n     * @dev Emitted when operation `id` is cancelled.\n     */\n    event Cancelled(bytes32 indexed id);\n\n    /**\n     * @dev Emitted when the minimum delay for future operations is modified.\n     */\n    event MinDelayChange(uint256 oldDuration, uint256 newDuration);\n\n    /**\n     * @dev Initializes the contract with the following parameters:\n     *\n     * - `minDelay`: initial minimum delay for operations\n     * - `proposers`: accounts to be granted proposer and canceller roles\n     * - `executors`: accounts to be granted executor role\n     * - `admin`: optional account to be granted admin role; disable with zero address\n     *\n     * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment\n     * without being subject to delay, but this role should be subsequently renounced in favor of\n     * administration through timelocked proposals. Previous versions of this contract would assign\n     * this admin to the deployer automatically and should be renounced as well.\n     */\n    constructor(\n        uint256 minDelay,\n        address[] memory proposers,\n        address[] memory executors,\n        address admin\n    ) {\n        _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);\n        _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);\n        _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);\n        _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);\n\n        // self administration\n        _setupRole(TIMELOCK_ADMIN_ROLE, address(this));\n\n        // optional admin\n        if (admin != address(0)) {\n            _setupRole(TIMELOCK_ADMIN_ROLE, admin);\n        }\n\n        // register proposers and cancellers\n        for (uint256 i = 0; i < proposers.length; ++i) {\n            _setupRole(PROPOSER_ROLE, proposers[i]);\n            _setupRole(CANCELLER_ROLE, proposers[i]);\n        }\n\n        // register executors\n        for (uint256 i = 0; i < executors.length; ++i) {\n            _setupRole(EXECUTOR_ROLE, executors[i]);\n        }\n\n        _minDelay = minDelay;\n        emit MinDelayChange(0, minDelay);\n    }\n\n    /**\n     * @dev Modifier to make a function callable only by a certain role. In\n     * addition to checking the sender's role, `address(0)` 's role is also\n     * considered. Granting a role to `address(0)` is equivalent to enabling\n     * this role for everyone.\n     */\n    modifier onlyRoleOrOpenRole(bytes32 role) {\n        if (!hasRole(role, address(0))) {\n            _checkRole(role, _msgSender());\n        }\n        _;\n    }\n\n    /**\n     * @dev Contract might receive/hold ETH as part of the maintenance process.\n     */\n    receive() external payable {}\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl) returns (bool) {\n        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns whether an id correspond to a registered operation. This\n     * includes both Pending, Ready and Done operations.\n     */\n    function isOperation(bytes32 id) public view virtual returns (bool registered) {\n        return getTimestamp(id) > 0;\n    }\n\n    /**\n     * @dev Returns whether an operation is pending or not.\n     */\n    function isOperationPending(bytes32 id) public view virtual returns (bool pending) {\n        return getTimestamp(id) > _DONE_TIMESTAMP;\n    }\n\n    /**\n     * @dev Returns whether an operation is ready or not.\n     */\n    function isOperationReady(bytes32 id) public view virtual returns (bool ready) {\n        uint256 timestamp = getTimestamp(id);\n        return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;\n    }\n\n    /**\n     * @dev Returns whether an operation is done or not.\n     */\n    function isOperationDone(bytes32 id) public view virtual returns (bool done) {\n        return getTimestamp(id) == _DONE_TIMESTAMP;\n    }\n\n    /**\n     * @dev Returns the timestamp at with an operation becomes ready (0 for\n     * unset operations, 1 for done operations).\n     */\n    function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {\n        return _timestamps[id];\n    }\n\n    /**\n     * @dev Returns the minimum delay for an operation to become valid.\n     *\n     * This value can be changed by executing an operation that calls `updateDelay`.\n     */\n    function getMinDelay() public view virtual returns (uint256 duration) {\n        return _minDelay;\n    }\n\n    /**\n     * @dev Returns the identifier of an operation containing a single\n     * transaction.\n     */\n    function hashOperation(\n        address target,\n        uint256 value,\n        bytes calldata data,\n        bytes32 predecessor,\n        bytes32 salt\n    ) public pure virtual returns (bytes32 hash) {\n        return keccak256(abi.encode(target, value, data, predecessor, salt));\n    }\n\n    /**\n     * @dev Returns the identifier of an operation containing a batch of\n     * transactions.\n     */\n    function hashOperationBatch(\n        address[] calldata targets,\n        uint256[] calldata values,\n        bytes[] calldata payloads,\n        bytes32 predecessor,\n        bytes32 salt\n    ) public pure virtual returns (bytes32 hash) {\n        return keccak256(abi.encode(targets, values, payloads, predecessor, salt));\n    }\n\n    /**\n     * @dev Schedule an operation containing a single transaction.\n     *\n     * Emits a {CallScheduled} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have the 'proposer' role.\n     */\n    function schedule(\n        address target,\n        uint256 value,\n        bytes calldata data,\n        bytes32 predecessor,\n        bytes32 salt,\n        uint256 delay\n    ) public virtual onlyRole(PROPOSER_ROLE) {\n        bytes32 id = hashOperation(target, value, data, predecessor, salt);\n        _schedule(id, delay);\n        emit CallScheduled(id, 0, target, value, data, predecessor, delay);\n    }\n\n    /**\n     * @dev Schedule an operation containing a batch of transactions.\n     *\n     * Emits one {CallScheduled} event per transaction in the batch.\n     *\n     * Requirements:\n     *\n     * - the caller must have the 'proposer' role.\n     */\n    function scheduleBatch(\n        address[] calldata targets,\n        uint256[] calldata values,\n        bytes[] calldata payloads,\n        bytes32 predecessor,\n        bytes32 salt,\n        uint256 delay\n    ) public virtual onlyRole(PROPOSER_ROLE) {\n        require(targets.length == values.length, \"TimelockController: length mismatch\");\n        require(targets.length == payloads.length, \"TimelockController: length mismatch\");\n\n        bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);\n        _schedule(id, delay);\n        for (uint256 i = 0; i < targets.length; ++i) {\n            emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);\n        }\n    }\n\n    /**\n     * @dev Schedule an operation that is to becomes valid after a given delay.\n     */\n    function _schedule(bytes32 id, uint256 delay) private {\n        require(!isOperation(id), \"TimelockController: operation already scheduled\");\n        require(delay >= getMinDelay(), \"TimelockController: insufficient delay\");\n        _timestamps[id] = block.timestamp + delay;\n    }\n\n    /**\n     * @dev Cancel an operation.\n     *\n     * Requirements:\n     *\n     * - the caller must have the 'canceller' role.\n     */\n    function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {\n        require(isOperationPending(id), \"TimelockController: operation cannot be cancelled\");\n        delete _timestamps[id];\n\n        emit Cancelled(id);\n    }\n\n    /**\n     * @dev Execute an (ready) operation containing a single transaction.\n     *\n     * Emits a {CallExecuted} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have the 'executor' role.\n     */\n    // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n    // thus any modifications to the operation during reentrancy should be caught.\n    // slither-disable-next-line reentrancy-eth\n    function execute(\n        address target,\n        uint256 value,\n        bytes calldata payload,\n        bytes32 predecessor,\n        bytes32 salt\n    ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n        bytes32 id = hashOperation(target, value, payload, predecessor, salt);\n\n        _beforeCall(id, predecessor);\n        _execute(target, value, payload);\n        emit CallExecuted(id, 0, target, value, payload);\n        _afterCall(id);\n    }\n\n    /**\n     * @dev Execute an (ready) operation containing a batch of transactions.\n     *\n     * Emits one {CallExecuted} event per transaction in the batch.\n     *\n     * Requirements:\n     *\n     * - the caller must have the 'executor' role.\n     */\n    // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,\n    // thus any modifications to the operation during reentrancy should be caught.\n    // slither-disable-next-line reentrancy-eth\n    function executeBatch(\n        address[] calldata targets,\n        uint256[] calldata values,\n        bytes[] calldata payloads,\n        bytes32 predecessor,\n        bytes32 salt\n    ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {\n        require(targets.length == values.length, \"TimelockController: length mismatch\");\n        require(targets.length == payloads.length, \"TimelockController: length mismatch\");\n\n        bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);\n\n        _beforeCall(id, predecessor);\n        for (uint256 i = 0; i < targets.length; ++i) {\n            address target = targets[i];\n            uint256 value = values[i];\n            bytes calldata payload = payloads[i];\n            _execute(target, value, payload);\n            emit CallExecuted(id, i, target, value, payload);\n        }\n        _afterCall(id);\n    }\n\n    /**\n     * @dev Execute an operation's call.\n     */\n    function _execute(\n        address target,\n        uint256 value,\n        bytes calldata data\n    ) internal virtual {\n        (bool success, ) = target.call{value: value}(data);\n        require(success, \"TimelockController: underlying transaction reverted\");\n    }\n\n    /**\n     * @dev Checks before execution of an operation's calls.\n     */\n    function _beforeCall(bytes32 id, bytes32 predecessor) private view {\n        require(isOperationReady(id), \"TimelockController: operation is not ready\");\n        require(predecessor == bytes32(0) || isOperationDone(predecessor), \"TimelockController: missing dependency\");\n    }\n\n    /**\n     * @dev Checks after execution of an operation's calls.\n     */\n    function _afterCall(bytes32 id) private {\n        require(isOperationReady(id), \"TimelockController: operation is not ready\");\n        _timestamps[id] = _DONE_TIMESTAMP;\n    }\n\n    /**\n     * @dev Changes the minimum timelock duration for future operations.\n     *\n     * Emits a {MinDelayChange} event.\n     *\n     * Requirements:\n     *\n     * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing\n     * an operation where the timelock is the target and the data is the ABI-encoded call to this function.\n     */\n    function updateDelay(uint256 newDelay) external virtual {\n        require(msg.sender == address(this), \"TimelockController: caller must be timelock\");\n        emit MinDelayChange(_minDelay, newDelay);\n        _minDelay = newDelay;\n    }\n\n    /**\n     * @dev See {IERC721Receiver-onERC721Received}.\n     */\n    function onERC721Received(\n        address,\n        address,\n        uint256,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC721Received.selector;\n    }\n\n    /**\n     * @dev See {IERC1155Receiver-onERC1155Received}.\n     */\n    function onERC1155Received(\n        address,\n        address,\n        uint256,\n        uint256,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC1155Received.selector;\n    }\n\n    /**\n     * @dev See {IERC1155Receiver-onERC1155BatchReceived}.\n     */\n    function onERC1155BatchReceived(\n        address,\n        address,\n        uint256[] memory,\n        uint256[] memory,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC1155BatchReceived.selector;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n    /**\n     * @dev Handles the receipt of a single ERC1155 token type. This function is\n     * called at the end of a `safeTransferFrom` after the balance has been updated.\n     *\n     * NOTE: To accept the transfer, this must return\n     * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n     * (i.e. 0xf23a6e61, or its own function selector).\n     *\n     * @param operator The address which initiated the transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param id The ID of the token being transferred\n     * @param value The amount of tokens being transferred\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n     */\n    function onERC1155Received(\n        address operator,\n        address from,\n        uint256 id,\n        uint256 value,\n        bytes calldata data\n    ) external returns (bytes4);\n\n    /**\n     * @dev Handles the receipt of a multiple ERC1155 token types. This function\n     * is called at the end of a `safeBatchTransferFrom` after the balances have\n     * been updated.\n     *\n     * NOTE: To accept the transfer(s), this must return\n     * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n     * (i.e. 0xbc197c81, or its own function selector).\n     *\n     * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param ids An array containing ids of each token being transferred (order and length must match values array)\n     * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n     */\n    function onERC1155BatchReceived(\n        address operator,\n        address from,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.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 Address {\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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(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/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\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/contracts/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.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 ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/IERC165.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 IERC165 {\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/utils/math/Math.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 Math {\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/utils/Strings.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/Math.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\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 = Math.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, Math.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"
      },
      "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/IPolygonZkEVMGlobalExitRoot.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\n\npragma solidity ^0.8.20;\nimport \"./IBasePolygonZkEVMGlobalExitRoot.sol\";\n\ninterface IPolygonZkEVMGlobalExitRoot is IBasePolygonZkEVMGlobalExitRoot {\n    function getLastGlobalExitRoot() external view returns (bytes32);\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/PolygonZkEVM.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/IVerifierRollup.sol\";\nimport \"./interfaces/IPolygonZkEVMGlobalExitRoot.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"./interfaces/IPolygonZkEVMBridge.sol\";\nimport \"./lib/EmergencyManager.sol\";\nimport \"./interfaces/IPolygonZkEVMErrors.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 PolygonZkEVM is\n    OwnableUpgradeable,\n    EmergencyManager,\n    IPolygonZkEVMErrors\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 globalExitRoot Global exit root of the batch\n     * @param timestamp Sequenced timestamp of the batch\n     * @param minForcedTimestamp Minimum timestamp of the force batch data, empty when non forced batch\n     */\n    struct BatchData {\n        bytes transactions;\n        bytes32 globalExitRoot;\n        uint64 timestamp;\n        uint64 minForcedTimestamp;\n    }\n\n    /**\n     * @notice Struct which will be used to call sequenceForceBatches\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 globalExitRoot Global exit root of the batch\n     * @param minForcedTimestamp Indicates the minimum sequenced timestamp of the batch\n     */\n    struct ForcedBatchData {\n        bytes transactions;\n        bytes32 globalExitRoot;\n        uint64 minForcedTimestamp;\n    }\n\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     *  keccak256(bytes32 oldAccInputHash, keccak256(bytes transactions), bytes32 globalExitRoot, uint64 timestamp, address seqAddress)\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    /**\n     * @notice Struct to call initialize, this saves gas because pack the parameters and avoid stack too deep errors.\n     * @param admin Admin address\n     * @param trustedSequencer Trusted sequencer address\n     * @param pendingStateTimeout Pending state timeout\n     * @param trustedAggregator Trusted aggregator\n     * @param trustedAggregatorTimeout Trusted aggregator timeout\n     */\n    struct InitializePackedParameters {\n        address admin;\n        address trustedSequencer;\n        uint64 pendingStateTimeout;\n        address trustedAggregator;\n        uint64 trustedAggregatorTimeout;\n    }\n\n    // Modulus zkSNARK\n    uint256 internal constant _RFIELD =\n        21888242871839275222246405745257275088548364400416034343698204186575808495617;\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    // If a sequenced batch exceeds this timeout without being verified, 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    // 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 = 1 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    // MATIC token address\n    IERC20Upgradeable public immutable matic;\n\n    // Rollup verifier interface\n    IVerifierRollup public immutable rollupVerifier;\n\n    // Global Exit Root interface\n    IPolygonZkEVMGlobalExitRoot public immutable globalExitRootManager;\n\n    // PolygonZkEVM Bridge Address\n    IPolygonZkEVMBridge public immutable bridgeAddress;\n\n    // L2 chain identifier\n    uint64 public immutable chainID;\n\n    // L2 chain identifier\n    uint64 public immutable forkID;\n\n    // Time target of the verification of a batch\n    // Adaptatly 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    // Trusted sequencer address\n    address public trustedSequencer;\n\n    // Current matic fee per batch sequenced\n    uint256 public batchFee;\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    mapping(uint64 => bytes32) public forcedBatches;\n\n    // Queue of batches that defines the virtual state\n    // SequenceBatchNum --> SequencedBatchData\n    mapping(uint64 => SequencedBatchData) public sequencedBatches;\n\n    // Last sequenced timestamp\n    uint64 public lastTimestamp;\n\n    // Last batch sent by the sequencers\n    uint64 public lastBatchSequenced;\n\n    // Last forced batch included in the sequence\n    uint64 public lastForceBatchSequenced;\n\n    // Last forced batch\n    uint64 public lastForceBatch;\n\n    // Last batch verified by the aggregators\n    uint64 public lastVerifiedBatch;\n\n    // Trusted aggregator address\n    address public trustedAggregator;\n\n    // State root mapping\n    // BatchNum --> state root\n    mapping(uint64 => bytes32) public batchNumToStateRoot;\n\n    // Trusted sequencer URL\n    string public trustedSequencerURL;\n\n    // L2 network name\n    string public networkName;\n\n    // Pending state mapping\n    // pendingStateNumber --> PendingState\n    mapping(uint256 => PendingState) public pendingStateTransitions;\n\n    // Last pending state\n    uint64 public lastPendingState;\n\n    // Last pending state consolidated\n    uint64 public lastPendingStateConsolidated;\n\n    // Once a pending state exceeds this timeout it can be consolidated\n    uint64 public pendingStateTimeout;\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    // Address that will be able to adjust contract parameters or stop the emergency state\n    address public admin;\n\n    // This account will be able to accept the admin role\n    address public pendingAdmin;\n\n    // Force batch timeout\n    uint64 public forceBatchTimeout;\n\n    // Indicates if forced batches are disallowed\n    bool public isForcedBatchDisallowed;\n\n    /**\n     * @dev Emitted when the trusted sequencer sends a new batch of transactions\n     */\n    event SequenceBatches(uint64 indexed numBatch);\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 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 trusted aggregator verifies batches\n     */\n    event VerifyBatchesTrustedAggregator(\n        uint64 indexed numBatch,\n        bytes32 stateRoot,\n        address indexed aggregator\n    );\n\n    /**\n     * @dev Emitted when pending state is consolidated\n     */\n    event ConsolidatePendingState(\n        uint64 indexed numBatch,\n        bytes32 stateRoot,\n        uint64 indexed pendingStateNum\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 updates the trusted aggregator timeout\n     */\n    event SetTrustedAggregatorTimeout(uint64 newTrustedAggregatorTimeout);\n\n    /**\n     * @dev Emitted when the admin updates the pending state timeout\n     */\n    event SetPendingStateTimeout(uint64 newPendingStateTimeout);\n\n    /**\n     * @dev Emitted when the admin updates the trusted aggregator address\n     */\n    event SetTrustedAggregator(address newTrustedAggregator);\n\n    /**\n     * @dev Emitted when the admin updates the multiplier batch fee\n     */\n    event SetMultiplierBatchFee(uint16 newMultiplierBatchFee);\n\n    /**\n     * @dev Emitted when the admin updates the verify batch timeout\n     */\n    event SetVerifyBatchTimeTarget(uint64 newVerifyBatchTimeTarget);\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 activate force batches\n     */\n    event ActivateForceBatches();\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    /**\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        uint64 indexed numBatch,\n        bytes32 stateRoot,\n        address indexed aggregator\n    );\n\n    /**\n     * @dev Emitted everytime the forkID is updated, this includes the first initialization of the contract\n     * This event is intended to be emitted for every upgrade of the contract with relevant changes for the nodes\n     */\n    event UpdateZkEVMVersion(uint64 numBatch, uint64 forkID, string version);\n\n    /**\n     * @param _globalExitRootManager Global exit root manager address\n     * @param _matic MATIC token address\n     * @param _rollupVerifier Rollup verifier address\n     * @param _bridgeAddress Bridge address\n     * @param _chainID L2 chainID\n     * @param _forkID Fork Id\n     */\n    constructor(\n        IPolygonZkEVMGlobalExitRoot _globalExitRootManager,\n        IERC20Upgradeable _matic,\n        IVerifierRollup _rollupVerifier,\n        IPolygonZkEVMBridge _bridgeAddress,\n        uint64 _chainID,\n        uint64 _forkID\n    ) {\n        globalExitRootManager = _globalExitRootManager;\n        matic = _matic;\n        rollupVerifier = _rollupVerifier;\n        bridgeAddress = _bridgeAddress;\n        chainID = _chainID;\n        forkID = _forkID;\n    }\n\n    /**\n     * @param initializePackedParameters Struct to save gas and avoid stack too deep errors\n     * @param genesisRoot Rollup genesis root\n     * @param _trustedSequencerURL Trusted sequencer URL\n     * @param _networkName L2 network name\n     */\n    function initialize(\n        InitializePackedParameters calldata initializePackedParameters,\n        bytes32 genesisRoot,\n        string memory _trustedSequencerURL,\n        string memory _networkName,\n        string calldata _version\n    ) external initializer {\n        admin = initializePackedParameters.admin;\n        trustedSequencer = initializePackedParameters.trustedSequencer;\n        trustedAggregator = initializePackedParameters.trustedAggregator;\n        batchNumToStateRoot[0] = genesisRoot;\n        trustedSequencerURL = _trustedSequencerURL;\n        networkName = _networkName;\n\n        // Check initialize parameters\n        if (\n            initializePackedParameters.pendingStateTimeout >\n            _HALT_AGGREGATION_TIMEOUT\n        ) {\n            revert PendingStateTimeoutExceedHaltAggregationTimeout();\n        }\n        pendingStateTimeout = initializePackedParameters.pendingStateTimeout;\n\n        if (\n            initializePackedParameters.trustedAggregatorTimeout >\n            _HALT_AGGREGATION_TIMEOUT\n        ) {\n            revert TrustedAggregatorTimeoutExceedHaltAggregationTimeout();\n        }\n\n        trustedAggregatorTimeout = initializePackedParameters\n            .trustedAggregatorTimeout;\n\n        // Constant deployment variables\n        batchFee = 0.1 ether; // 0.1 Matic\n        verifyBatchTimeTarget = 30 minutes;\n        multiplierBatchFee = 1002;\n        forceBatchTimeout = 5 days;\n        isForcedBatchDisallowed = true;\n\n        // Initialize OZ contracts\n        __Ownable_init_unchained();\n\n        // emit version event\n        emit UpdateZkEVMVersion(0, forkID, _version);\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 onlyTrustedAggregator() {\n        if (trustedAggregator != msg.sender) {\n            revert OnlyTrustedAggregator();\n        }\n        _;\n    }\n\n    modifier isForceBatchAllowed() {\n        if (isForcedBatchDisallowed) {\n            revert ForceBatchNotAllowed();\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 l2Coinbase Address that will receive the fees from L2\n     */\n    function sequenceBatches(\n        BatchData[] calldata batches,\n        address l2Coinbase\n    ) external ifNotEmergencyState 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        // Store storage variables in memory, to save gas, because will be overrided multiple times\n        uint64 currentTimestamp = lastTimestamp;\n        uint64 currentBatchSequenced = lastBatchSequenced;\n        uint64 currentLastForceBatchSequenced = lastForceBatchSequenced;\n        bytes32 currentAccInputHash = sequencedBatches[currentBatchSequenced]\n            .accInputHash;\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.minForcedTimestamp > 0) {\n                currentLastForceBatchSequenced++;\n\n                // Check forced data matches\n                bytes32 hashedForcedBatchData = keccak256(\n                    abi.encodePacked(\n                        currentTransactionsHash,\n                        currentBatch.globalExitRoot,\n                        currentBatch.minForcedTimestamp\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                // Check timestamp is bigger than min timestamp\n                if (currentBatch.timestamp < currentBatch.minForcedTimestamp) {\n                    revert SequencedTimestampBelowForcedTimestamp();\n                }\n            } else {\n                // Check global exit root exists with proper batch length. These checks are already done in the forceBatches call\n                // Note that the sequencer can skip setting a global exit root putting zeros\n                if (\n                    currentBatch.globalExitRoot != bytes32(0) &&\n                    globalExitRootManager.globalExitRootMap(\n                        currentBatch.globalExitRoot\n                    ) ==\n                    0\n                ) {\n                    revert GlobalExitRootNotExist();\n                }\n\n                if (\n                    currentBatch.transactions.length >\n                    _MAX_TRANSACTIONS_BYTE_LENGTH\n                ) {\n                    revert TransactionsLengthAboveMax();\n                }\n            }\n\n            // Check Batch timestamps are correct\n            if (\n                currentBatch.timestamp < currentTimestamp ||\n                currentBatch.timestamp > block.timestamp\n            ) {\n                revert SequencedTimestampInvalid();\n            }\n\n            // Calculate next accumulated input hash\n            currentAccInputHash = keccak256(\n                abi.encodePacked(\n                    currentAccInputHash,\n                    currentTransactionsHash,\n                    currentBatch.globalExitRoot,\n                    currentBatch.timestamp,\n                    l2Coinbase\n                )\n            );\n\n            // Update timestamp\n            currentTimestamp = currentBatch.timestamp;\n        }\n        // Update currentBatchSequenced\n        currentBatchSequenced += uint64(batchesNum);\n\n        // Sanity check, should be unreachable\n        if (currentLastForceBatchSequenced > lastForceBatch) {\n            revert ForceBatchesOverflow();\n        }\n\n        uint256 nonForcedBatchesSequenced = batchesNum -\n            (currentLastForceBatchSequenced - initLastForceBatchSequenced);\n\n        // Update sequencedBatches mapping\n        sequencedBatches[currentBatchSequenced] = SequencedBatchData({\n            accInputHash: currentAccInputHash,\n            sequencedTimestamp: uint64(block.timestamp),\n            previousLastBatchSequenced: lastBatchSequenced\n        });\n\n        // Store back the storage variables\n        lastTimestamp = currentTimestamp;\n        lastBatchSequenced = currentBatchSequenced;\n\n        if (currentLastForceBatchSequenced != initLastForceBatchSequenced)\n            lastForceBatchSequenced = currentLastForceBatchSequenced;\n\n        // Pay collateral for every non-forced batch submitted\n        matic.safeTransferFrom(\n            msg.sender,\n            address(this),\n            batchFee * nonForcedBatchesSequenced\n        );\n\n        // Consolidate pending state if possible\n        _tryConsolidatePendingState();\n\n        // Update global exit root if there are new deposits\n        bridgeAddress.updateGlobalExitRoot();\n\n        emit SequenceBatches(currentBatchSequenced);\n    }\n\n    /**\n     * @notice Allows an aggregator to verify multiple batches\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 proof fflonk proof\n     */\n    function verifyBatches(\n        uint64 pendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        bytes32[24] calldata proof\n    ) external ifNotEmergencyState {\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            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            pendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            proof\n        );\n\n        // Update batch fees\n        _updateBatchFee(finalNewBatch);\n\n        if (pendingStateTimeout == 0) {\n            // Consolidate state\n            lastVerifiedBatch = finalNewBatch;\n            batchNumToStateRoot[finalNewBatch] = newStateRoot;\n\n            // Clean pending state if any\n            if (lastPendingState > 0) {\n                lastPendingState = 0;\n                lastPendingStateConsolidated = 0;\n            }\n\n            // Interact with globalExitRootManager\n            globalExitRootManager.updateExitRoot(newLocalExitRoot);\n        } else {\n            // Consolidate pending state if possible\n            _tryConsolidatePendingState();\n\n            // Update pending state\n            lastPendingState++;\n            pendingStateTransitions[lastPendingState] = PendingState({\n                timestamp: uint64(block.timestamp),\n                lastVerifiedBatch: finalNewBatch,\n                exitRoot: newLocalExitRoot,\n                stateRoot: newStateRoot\n            });\n        }\n\n        emit VerifyBatches(finalNewBatch, newStateRoot, msg.sender);\n    }\n\n    /**\n     * @notice Allows an aggregator to verify multiple batches\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 proof fflonk proof\n     */\n    function verifyBatchesTrustedAggregator(\n        uint64 pendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        bytes32[24] calldata proof\n    ) external onlyTrustedAggregator {\n        _verifyAndRewardBatches(\n            pendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            proof\n        );\n\n        // Consolidate state\n        lastVerifiedBatch = finalNewBatch;\n        batchNumToStateRoot[finalNewBatch] = newStateRoot;\n\n        // Clean pending state if any\n        if (lastPendingState > 0) {\n            lastPendingState = 0;\n            lastPendingStateConsolidated = 0;\n        }\n\n        // Interact with globalExitRootManager\n        globalExitRootManager.updateExitRoot(newLocalExitRoot);\n\n        emit VerifyBatchesTrustedAggregator(\n            finalNewBatch,\n            newStateRoot,\n            msg.sender\n        );\n    }\n\n    /**\n     * @notice Verify and reward batches internal function\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 proof fflonk proof\n     */\n    function _verifyAndRewardBatches(\n        uint64 pendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        bytes32[24] calldata proof\n    ) internal virtual {\n        bytes32 oldStateRoot;\n        uint64 currentLastVerifiedBatch = getLastVerifiedBatch();\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 > lastPendingState) {\n                revert PendingStateDoesNotExist();\n            }\n\n            // Check choosen pending state\n            PendingState storage currentPendingState = pendingStateTransitions[\n                pendingStateNum\n            ];\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 = 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            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            oldStateRoot,\n            newStateRoot\n        );\n\n        // Calulate the snark input\n        uint256 inputSnark = uint256(sha256(snarkHashBytes)) % _RFIELD;\n        // Verify proof\n        if (!rollupVerifier.verifyProof(proof, [inputSnark])) {\n            revert InvalidProof();\n        }\n\n        // Get MATIC reward\n        matic.safeTransfer(\n            msg.sender,\n            calculateRewardPerBatch() *\n                (finalNewBatch - currentLastVerifiedBatch)\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() internal {\n        // Check if there's any state to consolidate\n        if (lastPendingState > lastPendingStateConsolidated) {\n            // Check if it's possible to consolidate the next pending state\n            uint64 nextPendingState = lastPendingStateConsolidated + 1;\n            if (isPendingStateConsolidable(nextPendingState)) {\n                // Check middle pending state ( binary search of 1 step)\n                uint64 middlePendingState = nextPendingState +\n                    (lastPendingState - nextPendingState) /\n                    2;\n\n                // Try to consolidate it, and if not, consolidate the nextPendingState\n                if (isPendingStateConsolidable(middlePendingState)) {\n                    _consolidatePendingState(middlePendingState);\n                } else {\n                    _consolidatePendingState(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 pendingStateNum Pending state to consolidate\n     */\n    function consolidatePendingState(uint64 pendingStateNum) external {\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 (msg.sender != trustedAggregator) {\n            if (isEmergencyState) {\n                revert OnlyNotEmergencyState();\n            }\n\n            if (!isPendingStateConsolidable(pendingStateNum)) {\n                revert PendingStateNotConsolidable();\n            }\n        }\n        _consolidatePendingState(pendingStateNum);\n    }\n\n    /**\n     * @notice Internal function to consolidate any pending state that has already exceed the pendingStateTimeout\n     * @param pendingStateNum Pending state to consolidate\n     */\n    function _consolidatePendingState(uint64 pendingStateNum) 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 <= lastPendingStateConsolidated ||\n            pendingStateNum > lastPendingState\n        ) {\n            revert PendingStateInvalid();\n        }\n\n        PendingState storage currentPendingState = pendingStateTransitions[\n            pendingStateNum\n        ];\n\n        // Update state\n        uint64 newLastVerifiedBatch = currentPendingState.lastVerifiedBatch;\n        lastVerifiedBatch = newLastVerifiedBatch;\n        batchNumToStateRoot[newLastVerifiedBatch] = currentPendingState\n            .stateRoot;\n\n        // Update pending state\n        lastPendingStateConsolidated = pendingStateNum;\n\n        // Interact with globalExitRootManager\n        globalExitRootManager.updateExitRoot(currentPendingState.exitRoot);\n\n        emit ConsolidatePendingState(\n            newLastVerifiedBatch,\n            currentPendingState.stateRoot,\n            pendingStateNum\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(uint64 newLastVerifiedBatch) internal {\n        uint64 currentLastVerifiedBatch = getLastVerifiedBatch();\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\n                storage currentSequencedBatchData = sequencedBatches[\n                    currentBatch\n                ];\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    // 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 maticAmount Max amount of MATIC tokens that the sender is willing to pay\n     */\n    function forceBatch(\n        bytes calldata transactions,\n        uint256 maticAmount\n    ) public isForceBatchAllowed ifNotEmergencyState {\n        // Calculate matic collateral\n        uint256 maticFee = getForcedBatchFee();\n\n        if (maticFee > maticAmount) {\n            revert NotEnoughMaticAmount();\n        }\n\n        if (transactions.length > _MAX_FORCE_BATCH_BYTE_LENGTH) {\n            revert TransactionsLengthAboveMax();\n        }\n\n        matic.safeTransferFrom(msg.sender, address(this), maticFee);\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            )\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        ForcedBatchData[] calldata batches\n    ) external isForceBatchAllowed ifNotEmergencyState {\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 currentBatchSequenced = lastBatchSequenced;\n        uint64 currentLastForceBatchSequenced = lastForceBatchSequenced;\n        bytes32 currentAccInputHash = sequencedBatches[currentBatchSequenced]\n            .accInputHash;\n\n        // Sequence force batches\n        for (uint256 i = 0; i < batchesNum; i++) {\n            // Load current sequence\n            ForcedBatchData 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.globalExitRoot,\n                    currentBatch.minForcedTimestamp\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.minForcedTimestamp + 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.globalExitRoot,\n                    uint64(block.timestamp),\n                    msg.sender\n                )\n            );\n        }\n        // Update currentBatchSequenced\n        currentBatchSequenced += uint64(batchesNum);\n\n        lastTimestamp = uint64(block.timestamp);\n\n        // Store back the storage variables\n        sequencedBatches[currentBatchSequenced] = SequencedBatchData({\n            accInputHash: currentAccInputHash,\n            sequencedTimestamp: uint64(block.timestamp),\n            previousLastBatchSequenced: lastBatchSequenced\n        });\n        lastBatchSequenced = currentBatchSequenced;\n        lastForceBatchSequenced = currentLastForceBatchSequenced;\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 set a new trusted aggregator address\n     * @param newTrustedAggregator Address of the new trusted aggregator\n     */\n    function setTrustedAggregator(\n        address newTrustedAggregator\n    ) external onlyAdmin {\n        trustedAggregator = newTrustedAggregator;\n\n        emit SetTrustedAggregator(newTrustedAggregator);\n    }\n\n    /**\n     * @notice Allow the admin to 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 onlyAdmin {\n        if (newTrustedAggregatorTimeout > _HALT_AGGREGATION_TIMEOUT) {\n            revert TrustedAggregatorTimeoutExceedHaltAggregationTimeout();\n        }\n\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 Allow the admin to 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 onlyAdmin {\n        if (newPendingStateTimeout > _HALT_AGGREGATION_TIMEOUT) {\n            revert PendingStateTimeoutExceedHaltAggregationTimeout();\n        }\n\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 Allow the admin to set a new multiplier batch fee\n     * @param newMultiplierBatchFee multiplier batch fee\n     */\n    function setMultiplierBatchFee(\n        uint16 newMultiplierBatchFee\n    ) external onlyAdmin {\n        if (newMultiplierBatchFee < 1000 || newMultiplierBatchFee > 1023) {\n            revert InvalidRangeMultiplierBatchFee();\n        }\n\n        multiplierBatchFee = newMultiplierBatchFee;\n        emit SetMultiplierBatchFee(newMultiplierBatchFee);\n    }\n\n    /**\n     * @notice Allow the admin to 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 onlyAdmin {\n        if (newVerifyBatchTimeTarget > 1 days) {\n            revert InvalidRangeBatchTimeTarget();\n        }\n        verifyBatchTimeTarget = newVerifyBatchTimeTarget;\n        emit SetVerifyBatchTimeTarget(newVerifyBatchTimeTarget);\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 (!isEmergencyState) {\n            if (newforceBatchTimeout >= forceBatchTimeout) {\n                revert InvalidRangeForceBatchTimeout();\n            }\n        }\n\n        forceBatchTimeout = newforceBatchTimeout;\n        emit SetForceBatchTimeout(newforceBatchTimeout);\n    }\n\n    /**\n     * @notice Allow the admin to turn on the force batches\n     * This action is not reversible\n     */\n    function activateForceBatches() external onlyAdmin {\n        if (!isForcedBatchDisallowed) {\n            revert ForceBatchesAlreadyActive();\n        }\n        isForcedBatchDisallowed = false;\n        emit ActivateForceBatches();\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    // 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 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        uint64 initPendingStateNum,\n        uint64 finalPendingStateNum,\n        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 newStateRoot,\n        bytes32[24] calldata proof\n    ) external onlyTrustedAggregator {\n        _proveDistinctPendingState(\n            initPendingStateNum,\n            finalPendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            proof\n        );\n\n        // Consolidate state state\n        lastVerifiedBatch = finalNewBatch;\n        batchNumToStateRoot[finalNewBatch] = newStateRoot;\n\n        // Clean pending state if any\n        if (lastPendingState > 0) {\n            lastPendingState = 0;\n            lastPendingStateConsolidated = 0;\n        }\n\n        // Interact with globalExitRootManager\n        globalExitRootManager.updateExitRoot(newLocalExitRoot);\n\n        // Update trusted aggregator timeout to max\n        trustedAggregatorTimeout = _HALT_AGGREGATION_TIMEOUT;\n\n        emit OverridePendingState(finalNewBatch, newStateRoot, msg.sender);\n    }\n\n    /**\n     * @notice Allows to halt the PolygonZkEVM if its possible to prove a different state root given the same batches\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        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        _proveDistinctPendingState(\n            initPendingStateNum,\n            finalPendingStateNum,\n            initNumBatch,\n            finalNewBatch,\n            newLocalExitRoot,\n            newStateRoot,\n            proof\n        );\n\n        emit ProveNonDeterministicPendingState(\n            batchNumToStateRoot[finalNewBatch],\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 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        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        // 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 > lastPendingState) {\n                revert PendingStateDoesNotExist();\n            }\n\n            // Check choosen pending state\n            PendingState storage initPendingState = pendingStateTransitions[\n                initPendingStateNum\n            ];\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 = batchNumToStateRoot[initNumBatch];\n            if (oldStateRoot == bytes32(0)) {\n                revert OldStateRootDoesNotExist();\n            }\n\n            // Check initNumBatch is inside the range, sanity check\n            if (initNumBatch > 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 > lastPendingState ||\n            finalPendingStateNum <= initPendingStateNum ||\n            finalPendingStateNum <= lastPendingStateConsolidated\n        ) {\n            revert FinalPendingStateNumInvalid();\n        }\n\n        // Check final num batch\n        if (\n            finalNewBatch !=\n            pendingStateTransitions[finalPendingStateNum].lastVerifiedBatch\n        ) {\n            revert FinalNumBatchDoesNotMatchPendingState();\n        }\n\n        // Get snark bytes\n        bytes memory snarkHashBytes = getInputSnarkBytes(\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 (!rollupVerifier.verifyProof(proof, [inputSnark])) {\n            revert InvalidProof();\n        }\n\n        if (\n            pendingStateTransitions[finalPendingStateNum].stateRoot ==\n            newStateRoot\n        ) {\n            revert StoredRootMustBeDifferentThanNewRoot();\n        }\n    }\n\n    /**\n     * @notice Function to activate emergency state, which also enables the emergency mode on both PolygonZkEVM and PolygonZkEVMBridge contracts\n     * If not called by the owner must be provided a batcnNum that does not have been aggregated in a _HALT_AGGREGATION_TIMEOUT period\n     * @param sequencedBatchNum Sequenced batch number that has not been aggreagated in _HALT_AGGREGATION_TIMEOUT\n     */\n    function activateEmergencyState(uint64 sequencedBatchNum) external {\n        if (msg.sender != owner()) {\n            // Only check conditions if is not called by the owner\n            uint64 currentLastVerifiedBatch = getLastVerifiedBatch();\n\n            // Check that the batch has not been verified\n            if (sequencedBatchNum <= currentLastVerifiedBatch) {\n                revert BatchAlreadyVerified();\n            }\n\n            // Check that the batch has been sequenced and this was the end of a sequence\n            if (\n                sequencedBatchNum > lastBatchSequenced ||\n                sequencedBatches[sequencedBatchNum].sequencedTimestamp == 0\n            ) {\n                revert BatchNotSequencedOrNotSequenceEnd();\n            }\n\n            // Check that has been passed _HALT_AGGREGATION_TIMEOUT since it was sequenced\n            if (\n                sequencedBatches[sequencedBatchNum].sequencedTimestamp +\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 PolygonZkEVM and PolygonZkEVMBridge contracts\n     */\n    function deactivateEmergencyState() external onlyAdmin {\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 PolygonZkEVM 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    // public/view functions\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 Get the last verified batch\n     */\n    function getLastVerifiedBatch() public view returns (uint64) {\n        if (lastPendingState > 0) {\n            return pendingStateTransitions[lastPendingState].lastVerifiedBatch;\n        } else {\n            return lastVerifiedBatch;\n        }\n    }\n\n    /**\n     * @notice Returns a boolean that indicates if the pendingStateNum is or not consolidable\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        uint64 pendingStateNum\n    ) public view returns (bool) {\n        return (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 = matic.balanceOf(address(this));\n\n        // Total Sequenced Batches = forcedBatches to be sequenced (total forced Batches - sequenced Batches) + sequencedBatches\n        // Total Batches to be verified = Total Sequenced Batches - verified Batches\n        uint256 totalBatchesToVerify = ((lastForceBatch -\n            lastForceBatchSequenced) + lastBatchSequenced) -\n            getLastVerifiedBatch();\n\n        if (totalBatchesToVerify == 0) return 0;\n        return currentBalance / totalBatchesToVerify;\n    }\n\n    /**\n     * @notice Function 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        uint64 initNumBatch,\n        uint64 finalNewBatch,\n        bytes32 newLocalExitRoot,\n        bytes32 oldStateRoot,\n        bytes32 newStateRoot\n    ) public view returns (bytes memory) {\n        // sanity checks\n        bytes32 oldAccInputHash = sequencedBatches[initNumBatch].accInputHash;\n        bytes32 newAccInputHash = sequencedBatches[finalNewBatch].accInputHash;\n\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                chainID,\n                forkID,\n                newStateRoot,\n                newAccInputHash,\n                newLocalExitRoot,\n                finalNewBatch\n            );\n    }\n\n    function checkStateRootInsidePrime(\n        uint256 newStateRoot\n    ) public 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"
      },
      "contracts/PolygonZkEVMTimelock.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.20;\n\nimport \"@openzeppelin/contracts/governance/TimelockController.sol\";\nimport \"./PolygonZkEVM.sol\";\n\n/**\n * @dev Contract module which acts as a timelocked controller.\n * This gives time for users of the controlled contract to exit before a potentially dangerous maintenance operation is applied.\n * If emergency mode of the zkevm contract system is active, this timelock have no delay.\n */\ncontract PolygonZkEVMTimelock is TimelockController {\n    // Polygon ZK-EVM address. Will be used to check if it's on emergency state.\n    PolygonZkEVM public immutable polygonZkEVM;\n\n    /**\n     * @notice Constructor of timelock\n     * @param minDelay initial minimum delay for operations\n     * @param proposers accounts to be granted proposer and canceller roles\n     * @param executors accounts to be granted executor role\n     * @param admin optional account to be granted admin role; disable with zero address\n     * @param _polygonZkEVM polygonZkEVM address\n     **/\n    constructor(\n        uint256 minDelay,\n        address[] memory proposers,\n        address[] memory executors,\n        address admin,\n        PolygonZkEVM _polygonZkEVM\n    ) TimelockController(minDelay, proposers, executors, admin) {\n        polygonZkEVM = _polygonZkEVM;\n    }\n\n    /**\n     * @dev Returns the minimum delay for an operation to become valid.\n     *\n     * This value can be changed by executing an operation that calls `updateDelay`.\n     * If Polygon ZK-EVM is on emergency state the minDelay will be 0 instead.\n     */\n    function getMinDelay() public view override returns (uint256 duration) {\n        if (address(polygonZkEVM) != address(0) && polygonZkEVM.isEmergencyState()) {\n            return 0;\n        } else {\n            return super.getMinDelay();\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 999999
      },
      "evmVersion": "shanghai",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}